<commit_before>Vps.Auto.ImageGridPanel = Ext.extend(Vps.Binding.AbstractPanel,
{
    layout: 'fit',

    initComponent : function()
    {
        if (!this.viewConfig) this.viewConfig = { plugins: [] };
        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        if (!this.tpl) {
            this.tpl = new Ext.XTemplate(
                '<tpl for=".">',
                    '
',
                        '

',
                            '<tpl if="src"></tpl>',
                        '

',
                        '
{label_short}
',
                    '
',
                '</tpl>',
                '

'
            );
        }

        if (!this.bigPreviewTpl) {
            this.bigPreviewTpl = new Ext.XTemplate(
                '
',
                    '
{label}
',
                    '

',
                '
'
            );
        }

        if (!this.prepareViewData) {
            this.prepareViewData = function(data) {
                return data;
            };
        }

        this.actions.reload = new Ext.Action({
            icon    : '/assets/silkicons/arrow_rotate_clockwise.png',
            cls     : 'x-btn-icon',
            tooltip : trlVps('Reload'),
            handler : this.reload,
            scope   : this
        });
        this.actions.add = new Ext.Action({
            text    : trlVps('Add'),
            icon    : '/assets/silkicons/table_add.png',
            cls     : 'x-btn-text-icon',
            handler : this.onAdd,
            scope: this
        });
        this.actions['delete'] = new Ext.Action({
            text    : trlVps('Delete'),
            icon    : '/assets/silkicons/table_delete.png',
            cls     : 'x-btn-text-icon',
            handler : this.onDelete,
            scope: this,
            needsSelection: true
        });
        Vps.Auto.ImageGridPanel.superclass.initComponent.call(this);
    },

    doAutoLoad : function()
    {
        if (!this.autoLoad) return;
        this.load();
    },

    onMetaLoad : function(result) {
        var meta = result.metaData;
        this.metaData = meta;

        if (!this.store) {
            var remoteSort = false;
            if (meta.paging) remoteSort = true;
            if (!meta.sortable) remoteSort = true;
            var storeConfig = {
                proxy: new Ext.data.HttpProxy({ url: this.controllerUrl + '/json-data' }),
                reader: new Ext.data.JsonReader({
                    totalProperty: meta.totalProperty,
                    root: meta.root,
                    id: meta.id,
                    sucessProperty: meta.successProperty,
                    fields: meta.fields
                }),
                remoteSort: remoteSort,
                sortInfo: meta.sortInfo,
                pruneModifiedRecords: true
            };
            this.store = new Ext.data.Store(storeConfig);
            if (this.baseParams) {
                this.setBaseParams(this.baseParams);
                delete this.baseParams;
            }
        }

        this.store.on('beforeload', function() {
            this._selectedIdForReselect = null;
            this._selectedIdForReselect = this.getSelectedId();
        }, this);

        this.store.on('load', function() {
            if (this._selectedIdForReselect) {
                this.selectId(this._selectedIdForReselect);
            }
        }, this);

        this.store.newRecords = []; //hier werden neue records gespeichert die nicht dirty sind
        this.store.on('update', function(store, record, operation) {
            if (operation == Ext.data.Record.EDIT) {
                if (this.isDirty()) {
                    this.getAction('save').enable();
                } else {
                    this.getAction('save').disable();
                }
            }
        }, this);
        this.relayEvents(this.store, ['load']);
        this.on('aftereditcomplete', function() {
            if (this.isDirty()) {
                this.getAction('save').enable();
            } else {
                this.getAction('save').disable();
            }
        }, this);
        this.on('beforeedit', function() {
            this.getAction('save').enable();
        }, this);
        this.store.on('add', function(store, records, index) {
            this.getAction('save').enable();
        }, this);

        this.store.on('loadexception', function(proxy, o, response, e) {
            throw e; //re-throw
        }, this);

        this.relayEvents(this.store, ['load']);

        var viewConfig = Ext.applyIf(this.viewConfig, {
            store: this.store,
            tpl: this.tpl,
            cls: 'imageGrid',
            autoHeight: true,
            itemSelector: 'div.thumb-wrap',
            emptyText: trlVps('No items to display'),
            plugins: [],
            prepareData: this.prepareViewData,
            singleSelect: true,
            border: false,
            listeners: { scope: this }
        });

        if (meta.paging) {
            if (typeof meta.paging == 'object') {
                var t;
                if (meta.paging.type && Vps.PagingToolbar[meta.paging.type]) {
                    this.pagingType = meta.paging.type;
                    t = Vps.PagingToolbar[meta.paging.type];
                } else if(meta.paging.type) {
                    try {
                        t = eval(meta.paging.type);
                    } catch(e) {
                        throw "invalid paging-toolbar: "+meta.paging.type;
                    }
                    this.pagingType = meta.paging.type;
                } else {
                    this.pagingType = 'Ext.PagingToolbar';
                    t = Ext.PagingToolbar;
                }
                delete meta.paging.type;
                var pagingConfig = meta.paging;
                pagingConfig.store = this.store;
                this.bottomToolBar = new t(pagingConfig);
            } else {
                this.pagingType = 'Ext.PagingToolbar';
                this.bottomToolBar = new Ext.PagingToolbar({
                    store: this.store,
                    pageSize: meta.paging,
                    displayInfo: true
                });
            }
        } else {
            this.pagingType = false;
        }

        for (var i in this.actions) {
            if (this.actions[i].initialConfig.needsSelection) {
                this.actions[i].disable();
            }
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        //aktionen die als string in der tbar sind
        if (!this.topToolBar) this.topToolBar = [ ];
        var existingActions = {};
        for (var i = 0; i < this.topToolBar.length; i++) {
            if (typeof this.topToolBar[i] == 'string'
                    && this.getAction(this.topToolBar[i])) {
                existingActions[this.topToolBar[i]] = true;
            }
        }

        if (meta.buttons.add) {
            if (!existingActions.add) {
                this.topToolBar.add(this.getAction('add'));
            }
            delete meta.buttons.add;
        }
        if (meta.buttons['delete']) {
            if (!existingActions['delete']) {
                this.topToolBar.add(this.getAction('delete'));
            }
            delete meta.buttons['delete'];
        }

        for (var i in meta.buttons) {
            if (i != 'reload' && !existingActions[i]) {
                if (this.getAction(i)) {
                    this.topToolBar.add(this.getAction(i));
                } else {
                    this.topToolBar.add(i);
                }
            }
        }

        for (var i = 0; i < this.topToolBar.length; i++) {
            if (typeof this.topToolBar[i] == 'string'
                    && this.getAction(this.topToolBar[i])) {
                this.topToolBar[i] = this.getAction(this.topToolBar[i]);
            }
        }

        this.filters = new Vps.Auto.FilterCollection(meta.filters, this);
        this.filters.each(function(filter) {
            filter.on('filter', function(f, params) {
                this.applyBaseParams(params);
                this.load();
            }, this);
        }, this);
        this.filters.applyToTbar(this.topToolBar);

        if (meta.buttons.reload) {
            this.topToolBar.add('->');
        }
        if (meta.buttons.reload && !existingActions.reload) {
            this.topToolBar.add(this.getAction('reload'));
        }

        if (meta.helpText) {
            this.topToolBar.add('->');
            this.topToolBar.add(new Ext.Action({
                icon : '/assets/silkicons/information.png',
                cls : 'x-btn-icon',
                handler : function (a) {
                    var helpWindow = new Ext.Window({
                        html: meta.helpText,
                        width: 400,
                        bodyStyle: 'padding: 10px; background-color: white;',
                        autoHeight: true,
                        bodyBorder : false,
                        title: trlVps('Info'),
                        resize: false
                    });
                    helpWindow.show();
                },
                scope: this
            }));
        }
        //wenn toolbar leer und keine tbar über config gesetzt dann nicht erstellen
        if (this.topToolBar.length == 0) {
            delete this.topToolBar;
        }

        this.view = new Ext.DataView(viewConfig);
        this.relayEvents(this.view, ['selectionchange', 'beforeselect']);

        this.store.on('beforeload', function() {
            this.el.mask(trlVps('Loading...'));
        }, this);
        this.store.on('load', function(store, records, opts) {
            this.el.unmask();

            var compiledTpl = this.bigPreviewTpl.compile();
            for (var i = 0; i < records.length; i++) {
                Ext.QuickTips.register({
                    target: Ext.get(this.view.getNode(i)).child('img'),
                    text: compiledTpl.apply(records[i].data),
                    dismissDelay: 20000
                });
            }
        }, this);

        this.view.on('selectionchange', function() {
            if (this.getSelectedId()) {
                for (var i in this.actions) {
                    var a = this.actions[i];
                    if (a.initialConfig.needsSelection) a.enable();
                }
            } else {
                for (var i in this.actions) {
                    var a = this.actions[i];
                    if (a.initialConfig.needsSelection) a.disable();
                }
            }
        }, this);

        var panel = new Ext.Panel({
            tbar: this.topToolBar ? this.topToolBar : null,
            bbar: this.bottomToolBar ? this.bottomToolBar : null,
            items: [ this.view],
            border: false,
            autoScroll: true
        });
        this.add(panel);
        this.doLayout();

        this.fireEvent('loaded', this.view);

        if (result.rows) {
            this.store.loadData(result);
        }
    },

    getFilter : function(filterName) {
        if (this.filters) return this.filters.get(filterName);
    },

    getStore : function() {
        return this.store;
    },

    //für AbstractPanel
    getSelectedId: function() {
        var s = this.view.getSelectedRecords();
        if (s && s[0]) return s[0].id;
        return null;
    },

    //für AbstractPanel
    selectId: function(id) {
        if (id) {
            var idx = this.getStore().indexOfId(id);
            if (idx !== -1) {
                this.view.select(idx);
            }
        } else {
            this.clearSelections();
        }
    },
    clearSelections: function() {
        if (this.view) {
            this.view.clearSelections();
        }
    },

    //für AbstractPanel
    reset: function() {
        if (this.getStore()) {
            this.getStore().modified = [];
            this.getStore().newRecords = [];
        }
    },

    reload: function(options) {
        if (this.getStore()) {
            this.getStore().reload(options);
            this.getStore().commitChanges();
        }
    },

    load : function(params) {
        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoGrid.');
        }
        if (!params) params = {};
        if (!this.getStore()) {
            Ext.applyIf(params, Ext.apply({ meta: true }, this.baseParams));
            Ext.Ajax.request({
                mask: true,
                url: this.controllerUrl+'/json-data',
                params: params,
                success: function(response, options, r) {
                    this.onMetaLoad(r);
                },
                scope: this
            });
        } else {
            if (this.pagingType && this.pagingType != 'Date' && !params.start) {
                params.start = 0;
            }
            this.getStore().load({ params: params });
        }
    },

    getStore : function() {
        return this.store;
    },
    getBaseParams : function() {
        if (this.getStore()) {
            return this.getStore().baseParams;
        } else {
            return this.baseParams || {};
        }
    },
    setBaseParams : function(baseParams) {
        if (this.getStore()) {
            this.getStore().baseParams = baseParams;
        } else {
            //no store yet, apply them later
            this.baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        if (this.getStore()) {
            Ext.apply(this.getStore().baseParams, baseParams);
        } else {
            //no store yet, apply them later
            if (!this.baseParams) this.baseParams = {};
            Ext.apply(this.baseParams, baseParams);
        }
    },
    resetFilters: function() {
        this.filters.each(function(f) {
            f.reset();
            this.applyBaseParams(f.getParams());
        }, this);
    },
    isDirty: function() {
        if (!this.store) return false;
        if (this.store.getModifiedRecords().length || this.store.newRecords.legth) {
            return true;
        } else {
            return false;
        }
    },

    onAdd : function()
    {
        //im ersten form-binding hinzufügen
        this.bindings.each(function(b) {
            if (b.item instanceof Vps.Auto.FormPanel) {
                b.item.onAdd();
                return false;
            }
        }, this);
        this.fireEvent('addaction', this);
    },

    onDelete : function() {
        Ext.Msg.show({
            title: trlVps('Delete'),
            msg: trlVps('Do you really wish to remove this entry / these entries?'),
            buttons: Ext.Msg.YESNO,
            scope: this,
            fn: function(button) {
                if (button == 'yes') {
                    var selectedId = this.getSelectedId();
                    if (!selectedId) return;

                    var ids = [ selectedId ];
                    var params = this.getBaseParams() || {};
                    if (!ids.length) return;

                    params[this.store.reader.meta.id] = ids.join(';');

                    this.el.mask(trlVps('Deleting...'));
                    Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: params,
                        success: function(response, options, r) {
                            this.reload();
                            this.fireEvent('deleterow', this.view);
                            this.fireEvent('datachange', r);

                            //wenn gelöscht alle anderen disablen
                            this.bindings.each(function(i) {
                                i.item.disable();
                                i.item.reset();
                            }, this);
                        },
                        callback: function() {
                            this.el.unmask();
                        },
                        scope : this
                    });
                }
            }
        });
    }
});

Ext.reg('vps.imagegrid', Vps.Auto.ImageGridPanel);
<commit_msg>quicktip maxwidth in vps image grid<commit_after>Vps.Auto.ImageGridPanel = Ext.extend(Vps.Binding.AbstractPanel,
{
    layout: 'fit',

    initComponent : function()
    {
        if (!this.viewConfig) this.viewConfig = { plugins: [] };
        if (this.autoLoad !== false) {
            this.autoLoad = true;
        } else {
            delete this.autoLoad;
        }

        if (!this.tpl) {
            this.tpl = new Ext.XTemplate(
                '<tpl for=".">',
                    '
',
                        '

',
                            '<tpl if="src"></tpl>',
                        '

',
                        '
{label_short}
',
                    '
',
                '</tpl>',
                '

'
            );
        }

        if (!this.bigPreviewTpl) {
            this.bigPreviewTpl = new Ext.XTemplate(
                '
',
                    '
{label}
',
                    '

',
                '
'
            );
        }

        if (!this.prepareViewData) {
            this.prepareViewData = function(data) {
                return data;
            };
        }

        this.actions.reload = new Ext.Action({
            icon    : '/assets/silkicons/arrow_rotate_clockwise.png',
            cls     : 'x-btn-icon',
            tooltip : trlVps('Reload'),
            handler : this.reload,
            scope   : this
        });
        this.actions.add = new Ext.Action({
            text    : trlVps('Add'),
            icon    : '/assets/silkicons/table_add.png',
            cls     : 'x-btn-text-icon',
            handler : this.onAdd,
            scope: this
        });
        this.actions['delete'] = new Ext.Action({
            text    : trlVps('Delete'),
            icon    : '/assets/silkicons/table_delete.png',
            cls     : 'x-btn-text-icon',
            handler : this.onDelete,
            scope: this,
            needsSelection: true
        });
        Vps.Auto.ImageGridPanel.superclass.initComponent.call(this);
    },

    doAutoLoad : function()
    {
        if (!this.autoLoad) return;
        this.load();
    },

    onMetaLoad : function(result) {
        var meta = result.metaData;
        this.metaData = meta;

        if (!this.store) {
            var remoteSort = false;
            if (meta.paging) remoteSort = true;
            if (!meta.sortable) remoteSort = true;
            var storeConfig = {
                proxy: new Ext.data.HttpProxy({ url: this.controllerUrl + '/json-data' }),
                reader: new Ext.data.JsonReader({
                    totalProperty: meta.totalProperty,
                    root: meta.root,
                    id: meta.id,
                    sucessProperty: meta.successProperty,
                    fields: meta.fields
                }),
                remoteSort: remoteSort,
                sortInfo: meta.sortInfo,
                pruneModifiedRecords: true
            };
            this.store = new Ext.data.Store(storeConfig);
            if (this.baseParams) {
                this.setBaseParams(this.baseParams);
                delete this.baseParams;
            }
        }

        this.store.on('beforeload', function() {
            this._selectedIdForReselect = null;
            this._selectedIdForReselect = this.getSelectedId();
        }, this);

        this.store.on('load', function() {
            if (this._selectedIdForReselect) {
                this.selectId(this._selectedIdForReselect);
            }
        }, this);

        this.store.newRecords = []; //hier werden neue records gespeichert die nicht dirty sind
        this.store.on('update', function(store, record, operation) {
            if (operation == Ext.data.Record.EDIT) {
                if (this.isDirty()) {
                    this.getAction('save').enable();
                } else {
                    this.getAction('save').disable();
                }
            }
        }, this);
        this.relayEvents(this.store, ['load']);
        this.on('aftereditcomplete', function() {
            if (this.isDirty()) {
                this.getAction('save').enable();
            } else {
                this.getAction('save').disable();
            }
        }, this);
        this.on('beforeedit', function() {
            this.getAction('save').enable();
        }, this);
        this.store.on('add', function(store, records, index) {
            this.getAction('save').enable();
        }, this);

        this.store.on('loadexception', function(proxy, o, response, e) {
            throw e; //re-throw
        }, this);

        this.relayEvents(this.store, ['load']);

        var viewConfig = Ext.applyIf(this.viewConfig, {
            store: this.store,
            tpl: this.tpl,
            cls: 'imageGrid',
            autoHeight: true,
            itemSelector: 'div.thumb-wrap',
            emptyText: trlVps('No items to display'),
            plugins: [],
            prepareData: this.prepareViewData,
            singleSelect: true,
            border: false,
            listeners: { scope: this }
        });

        if (meta.paging) {
            if (typeof meta.paging == 'object') {
                var t;
                if (meta.paging.type && Vps.PagingToolbar[meta.paging.type]) {
                    this.pagingType = meta.paging.type;
                    t = Vps.PagingToolbar[meta.paging.type];
                } else if(meta.paging.type) {
                    try {
                        t = eval(meta.paging.type);
                    } catch(e) {
                        throw "invalid paging-toolbar: "+meta.paging.type;
                    }
                    this.pagingType = meta.paging.type;
                } else {
                    this.pagingType = 'Ext.PagingToolbar';
                    t = Ext.PagingToolbar;
                }
                delete meta.paging.type;
                var pagingConfig = meta.paging;
                pagingConfig.store = this.store;
                this.bottomToolBar = new t(pagingConfig);
            } else {
                this.pagingType = 'Ext.PagingToolbar';
                this.bottomToolBar = new Ext.PagingToolbar({
                    store: this.store,
                    pageSize: meta.paging,
                    displayInfo: true
                });
            }
        } else {
            this.pagingType = false;
        }

        for (var i in this.actions) {
            if (this.actions[i].initialConfig.needsSelection) {
                this.actions[i].disable();
            }
            if (!meta.permissions[i]) {
                this.getAction(i).hide();
            }
        }

        //aktionen die als string in der tbar sind
        if (!this.topToolBar) this.topToolBar = [ ];
        var existingActions = {};
        for (var i = 0; i < this.topToolBar.length; i++) {
            if (typeof this.topToolBar[i] == 'string'
                    && this.getAction(this.topToolBar[i])) {
                existingActions[this.topToolBar[i]] = true;
            }
        }

        if (meta.buttons.add) {
            if (!existingActions.add) {
                this.topToolBar.add(this.getAction('add'));
            }
            delete meta.buttons.add;
        }
        if (meta.buttons['delete']) {
            if (!existingActions['delete']) {
                this.topToolBar.add(this.getAction('delete'));
            }
            delete meta.buttons['delete'];
        }

        for (var i in meta.buttons) {
            if (i != 'reload' && !existingActions[i]) {
                if (this.getAction(i)) {
                    this.topToolBar.add(this.getAction(i));
                } else {
                    this.topToolBar.add(i);
                }
            }
        }

        for (var i = 0; i < this.topToolBar.length; i++) {
            if (typeof this.topToolBar[i] == 'string'
                    && this.getAction(this.topToolBar[i])) {
                this.topToolBar[i] = this.getAction(this.topToolBar[i]);
            }
        }

        this.filters = new Vps.Auto.FilterCollection(meta.filters, this);
        this.filters.each(function(filter) {
            filter.on('filter', function(f, params) {
                this.applyBaseParams(params);
                this.load();
            }, this);
        }, this);
        this.filters.applyToTbar(this.topToolBar);

        if (meta.buttons.reload) {
            this.topToolBar.add('->');
        }
        if (meta.buttons.reload && !existingActions.reload) {
            this.topToolBar.add(this.getAction('reload'));
        }

        if (meta.helpText) {
            this.topToolBar.add('->');
            this.topToolBar.add(new Ext.Action({
                icon : '/assets/silkicons/information.png',
                cls : 'x-btn-icon',
                handler : function (a) {
                    var helpWindow = new Ext.Window({
                        html: meta.helpText,
                        width: 400,
                        bodyStyle: 'padding: 10px; background-color: white;',
                        autoHeight: true,
                        bodyBorder : false,
                        title: trlVps('Info'),
                        resize: false
                    });
                    helpWindow.show();
                },
                scope: this
            }));
        }
        //wenn toolbar leer und keine tbar über config gesetzt dann nicht erstellen
        if (this.topToolBar.length == 0) {
            delete this.topToolBar;
        }

        this.view = new Ext.DataView(viewConfig);
        this.relayEvents(this.view, ['selectionchange', 'beforeselect']);

        this.store.on('beforeload', function() {
            this.el.mask(trlVps('Loading...'));
        }, this);
        this.store.on('load', function(store, records, opts) {
            this.el.unmask();

            Ext.apply(Ext.QuickTips.getQuickTip(), {
                maxWidth: 420,
                minWidth: 100
            });

            var compiledTpl = this.bigPreviewTpl.compile();
            for (var i = 0; i < records.length; i++) {
                Ext.QuickTips.register({
                    target: Ext.get(this.view.getNode(i)).child('img'),
                    text: compiledTpl.apply(records[i].data),
                    dismissDelay: 20000
                });
            }
        }, this);

        this.view.on('selectionchange', function() {
            if (this.getSelectedId()) {
                for (var i in this.actions) {
                    var a = this.actions[i];
                    if (a.initialConfig.needsSelection) a.enable();
                }
            } else {
                for (var i in this.actions) {
                    var a = this.actions[i];
                    if (a.initialConfig.needsSelection) a.disable();
                }
            }
        }, this);

        var panel = new Ext.Panel({
            tbar: this.topToolBar ? this.topToolBar : null,
            bbar: this.bottomToolBar ? this.bottomToolBar : null,
            items: [ this.view],
            border: false,
            autoScroll: true
        });
        this.add(panel);
        this.doLayout();

        this.fireEvent('loaded', this.view);

        if (result.rows) {
            this.store.loadData(result);
        }
    },

    getFilter : function(filterName) {
        if (this.filters) return this.filters.get(filterName);
    },

    getStore : function() {
        return this.store;
    },

    //für AbstractPanel
    getSelectedId: function() {
        var s = this.view.getSelectedRecords();
        if (s && s[0]) return s[0].id;
        return null;
    },

    //für AbstractPanel
    selectId: function(id) {
        if (id) {
            var idx = this.getStore().indexOfId(id);
            if (idx !== -1) {
                this.view.select(idx);
            }
        } else {
            this.clearSelections();
        }
    },
    clearSelections: function() {
        if (this.view) {
            this.view.clearSelections();
        }
    },

    //für AbstractPanel
    reset: function() {
        if (this.getStore()) {
            this.getStore().modified = [];
            this.getStore().newRecords = [];
        }
    },

    reload: function(options) {
        if (this.getStore()) {
            this.getStore().reload(options);
            this.getStore().commitChanges();
        }
    },

    load : function(params) {
        if (!this.controllerUrl) {
            throw new Error('No controllerUrl specified for AutoGrid.');
        }
        if (!params) params = {};
        if (!this.getStore()) {
            Ext.applyIf(params, Ext.apply({ meta: true }, this.baseParams));
            Ext.Ajax.request({
                mask: true,
                url: this.controllerUrl+'/json-data',
                params: params,
                success: function(response, options, r) {
                    this.onMetaLoad(r);
                },
                scope: this
            });
        } else {
            if (this.pagingType && this.pagingType != 'Date' && !params.start) {
                params.start = 0;
            }
            this.getStore().load({ params: params });
        }
    },

    getStore : function() {
        return this.store;
    },
    getBaseParams : function() {
        if (this.getStore()) {
            return this.getStore().baseParams;
        } else {
            return this.baseParams || {};
        }
    },
    setBaseParams : function(baseParams) {
        if (this.getStore()) {
            this.getStore().baseParams = baseParams;
        } else {
            //no store yet, apply them later
            this.baseParams = baseParams;
        }
    },
    applyBaseParams : function(baseParams) {
        if (this.getStore()) {
            Ext.apply(this.getStore().baseParams, baseParams);
        } else {
            //no store yet, apply them later
            if (!this.baseParams) this.baseParams = {};
            Ext.apply(this.baseParams, baseParams);
        }
    },
    resetFilters: function() {
        this.filters.each(function(f) {
            f.reset();
            this.applyBaseParams(f.getParams());
        }, this);
    },
    isDirty: function() {
        if (!this.store) return false;
        if (this.store.getModifiedRecords().length || this.store.newRecords.legth) {
            return true;
        } else {
            return false;
        }
    },

    onAdd : function()
    {
        //im ersten form-binding hinzufügen
        this.bindings.each(function(b) {
            if (b.item instanceof Vps.Auto.FormPanel) {
                b.item.onAdd();
                return false;
            }
        }, this);
        this.fireEvent('addaction', this);
    },

    onDelete : function() {
        Ext.Msg.show({
            title: trlVps('Delete'),
            msg: trlVps('Do you really wish to remove this entry / these entries?'),
            buttons: Ext.Msg.YESNO,
            scope: this,
            fn: function(button) {
                if (button == 'yes') {
                    var selectedId = this.getSelectedId();
                    if (!selectedId) return;

                    var ids = [ selectedId ];
                    var params = this.getBaseParams() || {};
                    if (!ids.length) return;

                    params[this.store.reader.meta.id] = ids.join(';');

                    this.el.mask(trlVps('Deleting...'));
                    Ext.Ajax.request({
                        url: this.controllerUrl+'/json-delete',
                        params: params,
                        success: function(response, options, r) {
                            this.reload();
                            this.fireEvent('deleterow', this.view);
                            this.fireEvent('datachange', r);

                            //wenn gelöscht alle anderen disablen
                            this.bindings.each(function(i) {
                                i.item.disable();
                                i.item.reset();
                            }, this);
                        },
                        callback: function() {
                            this.el.unmask();
                        },
                        scope : this
                    });
                }
            }
        });
    }
});

Ext.reg('vps.imagegrid', Vps.Auto.ImageGridPanel);
<|endoftext|>


<commit_before>Vps.Form.SwfUploadField = Ext.extend(Ext.form.Field, {
    allowOnlyImages: false,
    fileSizeLimit: 0,
    showPreview: true,
    showDeleteButton: true,
    infoPosition: 'south',
    defaultAutoCreate : {
        tag: 'div',
        style: 'width: 300px; height: 53px'
    },
    fileIcons: {
        'application/pdf': 'page_white_acrobat',
        'application/x-zip': 'page_white_compressed',
        'application/msexcel': 'page_white_excel',
        'application/msword': 'page_white_word',
        'application/mspowerpoint': 'page_white_powerpoint',
        'default': 'page_white'
    },
    previewTpl: [''],
    // also usable in infoTpl: {href}
    infoTpl: ['{filename}.{extension}
',
              '{fileSize:fileSize}',
              '<tpl if="image">, {imageWidth}x{imageHeight}px</tpl>'],
    emptyTpl: '

('+trlVps('empty')+')
',

    initComponent: function() {
        this.addEvents(['uploaded']);

        if (this.showPreview) {
            if (!(this.previewTpl instanceof Ext.XTemplate)) {
                this.previewTpl = new Ext.XTemplate(this.previewTpl);
            }
            this.previewTpl.compile();
        }

        if (!(this.infoTpl instanceof Ext.XTemplate)) {
            this.infoTpl = new Ext.XTemplate(this.infoTpl);
        }
        this.infoTpl.compile();

        Vps.Form.SwfUploadField.superclass.initComponent.call(this);

    },
    afterRender: function() {
        Vps.Form.SwfUploadField.superclass.afterRender.call(this);

        if (this.showPreview) {
            this.previewImage = this.el.createChild({
                style: 'margin-right: 10px; padding: 5px; float: left; border: 1px solid #b5b8c8;'+
                    'background-color: white;'
            });

            this.previewImage.update(this.emptyTpl); //bild wird in der richtigen größe angezeigt
        }

        if (this.infoPosition == 'west') this.createInfoContainer();

        this.uploadButtonContainer = this.el.createChild({
                                         style: 'float:left; margin-right: 5px; '
                                     });

        this.uploadButtonContainerChildId = 'uploadButton'+Ext.id();
        this.createUploadButton(false);
        if (this.showDeleteButton) {
            this.deleteButton = new Ext.Button({
                text: trlVps('Delete File'),
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/delete.png',
                renderTo: this.el.createChild({}),
                scope: this,
                handler: function() {
                    this.setValue('');
                }
            });
        }
        if (this.infoPosition == 'south') this.createInfoContainer();

        //return; // Flash Uploader deaktiviert
        if (this.allowOnlyImages) {
            fileTypes = '*.jpg;*.jpeg;*.gif;*.png';
            fileTypesDescription = 'Web Image Files';
        } else {
            fileTypes = '*.*';
            fileTypesDescription = 'All Files';
        }

        //cookie als post mitschicken
        var params = {};
        var cookies = document.cookie.split(';');
        Ext.each(cookies, function(c) {
            c = c.split('=');

            if (c[0].trim() == 'PHPSESSID' && c[1]) {
                params.PHPSESSID = c[1];
            }
        });
        if (!params.PHPSESSID) return;
        if (!(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"])){
            return;
        }
//         if (Ext.isLinux) return; //für markus deaktivert

        this.useSwf = false;
        this.swfu = new SWFUpload({
            custom_settings: {field: this},
            upload_url: location.protocol+'/'+'/'+location.host+'/vps/media/upload/json-upload',
            flash_url: '/assets/swfupload/Flash/swfupload.swf',
            file_size_limit: this.fileSizeLimit,
            file_types: fileTypes,
            file_types_description: fileTypesDescription,
            post_params: params,
            button_image_url: "/assets/vps/Vps_js/Form/SwfUploadField/button.jpg",
            button_width: "120",
            button_height: "21",
            button_placeholder_id: this.uploadButtonContainerChildId,
            button_text: ''+trlVps('Upload File')+'',
            button_text_style: ".theFont { font-size: 11px; font-family:tahoma,verdana, helvetica;}",
            button_text_left_padding: 28,
            button_text_top_padding: 2,
            button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,

            file_queued_handler: function(file) {
                this.progress = Ext.MessageBox.show({
                    title : trlVps('Upload'),
                    msg : trlVps('Uploading file'),
                    buttons: false,
                    progress:true,
                    closable:false,
                    minWidth: 250,
                    buttons: Ext.MessageBox.CANCEL,
                    scope: this,
                    fn: function(button) {
                        this.cancelUpload(file.id);
                    }
                });
                this.startUpload(file.id);
            },
            upload_progress_handler: function(file, done, total) {
                this.progress.updateProgress(done/total);
            },
            upload_success_handler: function(file, response) {
                this.progress.hide();
                try {
                    var r = Ext.util.JSON.decode(response);
                } catch(e) {
                    Vps.handleError('Upload Error');
                    return;
                }
                if (r.success) {
                    this.customSettings.field.setValue(r.value);
                    this.customSettings.field.fireEvent('uploaded', this, r.value);
                } else {
                    if (r.wrongversion) {
                        Ext.Msg.alert(trlVps('Error - wrong version'),
                        trlVps('Because of an application update the application has to be reloaded.'),
                        function(){
                            location.reload();
                        });
                        return;
                    }
                    if (r.login) {
                        var dlg = new Vps.User.Login.Dialog({
                            message: r.message,
                            success: function() {
                                //redo action...
                                this.startUpload(file.id);
                            },
                            scope: this
                        });
                        Ext.getBody().unmask();
                        dlg.showLogin();
                        return;
                    }
                    if (r.error) {
                        Ext.Msg.alert(trlVps('Error'), r.error);
                    } else {
                        Vps.handleError(r.exception, 'Error', !r.exception);
                    }
                }
            },
            upload_error_handler: function(file, errorCode, errorMessage) {
                this.progress.hide();
                // Upload Errors
                var message = errorMessage;
                 if (errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR) {
                    message = trlVps("A http Error occured.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL) {
                    message = trlVps("Upload URL string is empty.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR) {
                    message = trlVps("IO Error.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR) {
                    message = trlVps("Security Error.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED) {
                    message = trlVps("The upload limit has been reached.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED) {
                    message = errorMessage;
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND) {
                    message = "File ID not found in the queue.";
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED) {
                    message = "Call to uploadStart return false. Not uploading file.";
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
                    message = trlVps("File Upload Cancelled.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
                    message = trlVps("Upload Stopped");
                }
                if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
                    //Vps.handleError(errorMessage, 'Upload Error');
                     Ext.Msg.alert(trlVps("Upload Error"), message);
                }
            },
            file_queue_error_handler: function(file, errorCode, errorMessage) {
                var message = trlVps("File is zero bytes or cannot be accessed and cannot be uploaded.");
                if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
                    message = trlVps("File size exceeds allowed limit.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
                    message = trlVps("File size exceeds allowed limit.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE) {
                    message = trlVps("File is zero bytes and cannot be uploaded.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE) {
                    message = trlVps("File is not an allowed file type.");
                }
                Ext.Msg.alert(trlVps("Upload Error"), message);
            },
            swfupload_loaded_handler: function() {
                //wenn CallFunction nicht vorhanden funktioniert der uploader nicht.
                //dann einfach durch die html version ersetzen
                if (!this.getMovieElement().CallFunction) {
                    this.customSettings.field.createUploadButton(true);
                    return;
                }
                this.customSettings.field.useSwf = true;
            }
        });
        /*
        //das wurde ursprünglich vom lenz so gemacht
        //ist aber scheinbar ned nötig da der uploader eh in allen browsern geht
        var checkButton = function() {
            if (!this.useSwf) {
                this.createUploadButton(true);
            }
        };
        checkButton.defer(5000, this);
        */
    },

    createInfoContainer: function() {
        this.infoContainer = this.el.createChild({
            style: 'margin-top: 3px;'+((this.infoPosition == 'west') ? ' float: left; margin-right: 3px;' : '')
        });
    },

    createUploadButton : function (check) {
        if (check == true) {
            this.uploadButtonContainer.first().remove();
        }
        this.uploadButton = new Ext.Button({
            text: trlVps('Upload File'),
            cls: 'x-btn-text-icon',
            icon: '/assets/silkicons/add.png',
            renderTo: this.uploadButtonContainer.createChild({
                id: this.uploadButtonContainerChildId
            }),
            scope: this,
            handler: function() {
                var win = new Vps.Form.FileUploadWindow({
                    maxResolution: this.maxResolution
                });
                win.on('uploaded', function(win, result) {
                    this.setValue(result.value);
                    this.fireEvent('uploaded', this, result.value);
                }, this);
                win.show();
            }
        });
    },
    onDestroy: function()
    {
        Vps.Form.SwfUploadField.superclass.onDestroy.call(this);
        if (this.swfu) this.swfu.destroy();
    },

    // überschrieben weil ext implementation auf this.el.dom.value zugreift was wir nicht haben
    initValue : function() {
        if(this.value !== undefined){
            this.setValue(this.value);
        }
    },

    setValue: function(value)
    {
        var v = '';
        if (value.uploadId) {
            v = value.uploadId;
        }
        if (v != this.value) {
            this.fireEvent('change', this, value, this.value);

            var icon = false;
            var href = '/vps/media/upload/download?uploadId='+value.uploadId+'&hashKey='+value.hashKey;
            if (value.mimeType) {
                if (this.showPreview) {
                    if (value.mimeType.match(/(^image\/)/)) {
                        icon = '/vps/media/upload/preview?uploadId='+value.uploadId+'&hashKey='+value.hashKey;
                    } else {
                        icon = this.fileIcons[value.mimeType] || this.fileIcons['default'];
                        icon = '/assets/silkicons/' + icon + '.png';
                    }
                    this.previewTpl.overwrite(this.previewImage, {
                        preview: icon,
                        href: href
                    });
                }

                var infoVars = Vps.clone(value);
                infoVars.href = href;
                this.infoTpl.overwrite(this.infoContainer, infoVars);
            } else {
                if (this.showPreview) {
                    this.previewImage.update(this.emptyTpl);
                }
                this.infoContainer.update('');
            }
        }
        Vps.Form.SwfUploadField.superclass.setValue.call(this, value.uploadId);
    },

    validateValue : function(value){
        if(!value){ // if it's blank
             if(this.allowBlank){
                 this.clearInvalid();
                 return true;
             }else{
                 this.markInvalid(trlVps('This field is required'));
                 return false;
             }
        }
        return true;
    }

});

Ext.reg('swfuploadfield', Vps.Form.SwfUploadField);

<commit_msg>fehlendes trl eingefuegt<commit_after>Vps.Form.SwfUploadField = Ext.extend(Ext.form.Field, {
    allowOnlyImages: false,
    fileSizeLimit: 0,
    showPreview: true,
    showDeleteButton: true,
    infoPosition: 'south',
    defaultAutoCreate : {
        tag: 'div',
        style: 'width: 300px; height: 53px'
    },
    fileIcons: {
        'application/pdf': 'page_white_acrobat',
        'application/x-zip': 'page_white_compressed',
        'application/msexcel': 'page_white_excel',
        'application/msword': 'page_white_word',
        'application/mspowerpoint': 'page_white_powerpoint',
        'default': 'page_white'
    },
    previewTpl: [''],
    // also usable in infoTpl: {href}
    infoTpl: ['{filename}.{extension}
',
              '{fileSize:fileSize}',
              '<tpl if="image">, {imageWidth}x{imageHeight}px</tpl>'],
    emptyTpl: '

('+trlVps('empty')+')
',

    initComponent: function() {
        this.addEvents(['uploaded']);

        if (this.showPreview) {
            if (!(this.previewTpl instanceof Ext.XTemplate)) {
                this.previewTpl = new Ext.XTemplate(this.previewTpl);
            }
            this.previewTpl.compile();
        }

        if (!(this.infoTpl instanceof Ext.XTemplate)) {
            this.infoTpl = new Ext.XTemplate(this.infoTpl);
        }
        this.infoTpl.compile();

        Vps.Form.SwfUploadField.superclass.initComponent.call(this);

    },
    afterRender: function() {
        Vps.Form.SwfUploadField.superclass.afterRender.call(this);

        if (this.showPreview) {
            this.previewImage = this.el.createChild({
                style: 'margin-right: 10px; padding: 5px; float: left; border: 1px solid #b5b8c8;'+
                    'background-color: white;'
            });

            this.previewImage.update(this.emptyTpl); //bild wird in der richtigen größe angezeigt
        }

        if (this.infoPosition == 'west') this.createInfoContainer();

        this.uploadButtonContainer = this.el.createChild({
                                         style: 'float:left; margin-right: 5px; '
                                     });

        this.uploadButtonContainerChildId = 'uploadButton'+Ext.id();
        this.createUploadButton(false);
        if (this.showDeleteButton) {
            this.deleteButton = new Ext.Button({
                text: trlVps('Delete File'),
                cls: 'x-btn-text-icon',
                icon: '/assets/silkicons/delete.png',
                renderTo: this.el.createChild({}),
                scope: this,
                handler: function() {
                    this.setValue('');
                }
            });
        }
        if (this.infoPosition == 'south') this.createInfoContainer();

        //return; // Flash Uploader deaktiviert
        if (this.allowOnlyImages) {
            fileTypes = '*.jpg;*.jpeg;*.gif;*.png';
            fileTypesDescription = trlVps('Web Image Files');
        } else {
            fileTypes = '*.*';
            fileTypesDescription = trlVps('All Files');
        }

        //cookie als post mitschicken
        var params = {};
        var cookies = document.cookie.split(';');
        Ext.each(cookies, function(c) {
            c = c.split('=');

            if (c[0].trim() == 'PHPSESSID' && c[1]) {
                params.PHPSESSID = c[1];
            }
        });
        if (!params.PHPSESSID) return;
        if (!(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"])){
            return;
        }
//         if (Ext.isLinux) return; //für markus deaktivert

        this.useSwf = false;
        this.swfu = new SWFUpload({
            custom_settings: {field: this},
            upload_url: location.protocol+'/'+'/'+location.host+'/vps/media/upload/json-upload',
            flash_url: '/assets/swfupload/Flash/swfupload.swf',
            file_size_limit: this.fileSizeLimit,
            file_types: fileTypes,
            file_types_description: fileTypesDescription,
            post_params: params,
            button_image_url: "/assets/vps/Vps_js/Form/SwfUploadField/button.jpg",
            button_width: "120",
            button_height: "21",
            button_placeholder_id: this.uploadButtonContainerChildId,
            button_text: ''+trlVps('Upload File')+'',
            button_text_style: ".theFont { font-size: 11px; font-family:tahoma,verdana, helvetica;}",
            button_text_left_padding: 28,
            button_text_top_padding: 2,
            button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,

            file_queued_handler: function(file) {
                this.progress = Ext.MessageBox.show({
                    title : trlVps('Upload'),
                    msg : trlVps('Uploading file'),
                    buttons: false,
                    progress:true,
                    closable:false,
                    minWidth: 250,
                    buttons: Ext.MessageBox.CANCEL,
                    scope: this,
                    fn: function(button) {
                        this.cancelUpload(file.id);
                    }
                });
                this.startUpload(file.id);
            },
            upload_progress_handler: function(file, done, total) {
                this.progress.updateProgress(done/total);
            },
            upload_success_handler: function(file, response) {
                this.progress.hide();
                try {
                    var r = Ext.util.JSON.decode(response);
                } catch(e) {
                    Vps.handleError('Upload Error');
                    return;
                }
                if (r.success) {
                    this.customSettings.field.setValue(r.value);
                    this.customSettings.field.fireEvent('uploaded', this, r.value);
                } else {
                    if (r.wrongversion) {
                        Ext.Msg.alert(trlVps('Error - wrong version'),
                        trlVps('Because of an application update the application has to be reloaded.'),
                        function(){
                            location.reload();
                        });
                        return;
                    }
                    if (r.login) {
                        var dlg = new Vps.User.Login.Dialog({
                            message: r.message,
                            success: function() {
                                //redo action...
                                this.startUpload(file.id);
                            },
                            scope: this
                        });
                        Ext.getBody().unmask();
                        dlg.showLogin();
                        return;
                    }
                    if (r.error) {
                        Ext.Msg.alert(trlVps('Error'), r.error);
                    } else {
                        Vps.handleError(r.exception, 'Error', !r.exception);
                    }
                }
            },
            upload_error_handler: function(file, errorCode, errorMessage) {
                this.progress.hide();
                // Upload Errors
                var message = errorMessage;
                 if (errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR) {
                    message = trlVps("A http Error occured.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL) {
                    message = trlVps("Upload URL string is empty.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR) {
                    message = trlVps("IO Error.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR) {
                    message = trlVps("Security Error.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED) {
                    message = trlVps("The upload limit has been reached.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED) {
                    message = errorMessage;
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND) {
                    message = "File ID not found in the queue.";
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED) {
                    message = "Call to uploadStart return false. Not uploading file.";
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
                    message = trlVps("File Upload Cancelled.");
                } else if (errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
                    message = trlVps("Upload Stopped");
                }
                if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
                    //Vps.handleError(errorMessage, 'Upload Error');
                     Ext.Msg.alert(trlVps("Upload Error"), message);
                }
            },
            file_queue_error_handler: function(file, errorCode, errorMessage) {
                var message = trlVps("File is zero bytes or cannot be accessed and cannot be uploaded.");
                if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
                    message = trlVps("File size exceeds allowed limit.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
                    message = trlVps("File size exceeds allowed limit.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE) {
                    message = trlVps("File is zero bytes and cannot be uploaded.");
                } else if (errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE) {
                    message = trlVps("File is not an allowed file type.");
                }
                Ext.Msg.alert(trlVps("Upload Error"), message);
            },
            swfupload_loaded_handler: function() {
                //wenn CallFunction nicht vorhanden funktioniert der uploader nicht.
                //dann einfach durch die html version ersetzen
                if (!this.getMovieElement().CallFunction) {
                    this.customSettings.field.createUploadButton(true);
                    return;
                }
                this.customSettings.field.useSwf = true;
            }
        });
        /*
        //das wurde ursprünglich vom lenz so gemacht
        //ist aber scheinbar ned nötig da der uploader eh in allen browsern geht
        var checkButton = function() {
            if (!this.useSwf) {
                this.createUploadButton(true);
            }
        };
        checkButton.defer(5000, this);
        */
    },

    createInfoContainer: function() {
        this.infoContainer = this.el.createChild({
            style: 'margin-top: 3px;'+((this.infoPosition == 'west') ? ' float: left; margin-right: 3px;' : '')
        });
    },

    createUploadButton : function (check) {
        if (check == true) {
            this.uploadButtonContainer.first().remove();
        }
        this.uploadButton = new Ext.Button({
            text: trlVps('Upload File'),
            cls: 'x-btn-text-icon',
            icon: '/assets/silkicons/add.png',
            renderTo: this.uploadButtonContainer.createChild({
                id: this.uploadButtonContainerChildId
            }),
            scope: this,
            handler: function() {
                var win = new Vps.Form.FileUploadWindow({
                    maxResolution: this.maxResolution
                });
                win.on('uploaded', function(win, result) {
                    this.setValue(result.value);
                    this.fireEvent('uploaded', this, result.value);
                }, this);
                win.show();
            }
        });
    },
    onDestroy: function()
    {
        Vps.Form.SwfUploadField.superclass.onDestroy.call(this);
        if (this.swfu) this.swfu.destroy();
    },

    // überschrieben weil ext implementation auf this.el.dom.value zugreift was wir nicht haben
    initValue : function() {
        if(this.value !== undefined){
            this.setValue(this.value);
        }
    },

    setValue: function(value)
    {
        var v = '';
        if (value.uploadId) {
            v = value.uploadId;
        }
        if (v != this.value) {
            this.fireEvent('change', this, value, this.value);

            var icon = false;
            var href = '/vps/media/upload/download?uploadId='+value.uploadId+'&hashKey='+value.hashKey;
            if (value.mimeType) {
                if (this.showPreview) {
                    if (value.mimeType.match(/(^image\/)/)) {
                        icon = '/vps/media/upload/preview?uploadId='+value.uploadId+'&hashKey='+value.hashKey;
                    } else {
                        icon = this.fileIcons[value.mimeType] || this.fileIcons['default'];
                        icon = '/assets/silkicons/' + icon + '.png';
                    }
                    this.previewTpl.overwrite(this.previewImage, {
                        preview: icon,
                        href: href
                    });
                }

                var infoVars = Vps.clone(value);
                infoVars.href = href;
                this.infoTpl.overwrite(this.infoContainer, infoVars);
            } else {
                if (this.showPreview) {
                    this.previewImage.update(this.emptyTpl);
                }
                this.infoContainer.update('');
            }
        }
        Vps.Form.SwfUploadField.superclass.setValue.call(this, value.uploadId);
    },

    validateValue : function(value){
        if(!value){ // if it's blank
             if(this.allowBlank){
                 this.clearInvalid();
                 return true;
             }else{
                 this.markInvalid(trlVps('This field is required'));
                 return false;
             }
        }
        return true;
    }

});

Ext.reg('swfuploadfield', Vps.Form.SwfUploadField);

<|endoftext|>


<commit_before>var Peer = require('icebreaker-peer')
var util = Peer.util
var _ = require('icebreaker')
var m = require('muxrpc/util')
var ms = require('ms')
var Notify = require('pull-notify')
var MRPC = require('muxrpc')
var URL = require('url')
var clone = require('lodash.clonedeep')
var paramap = require('pull-paramap')
var abortable = require('pull-abortable')
var handshake = require('./handshake')

function para(events) {
  return paramap(function handle(e, cb) {
    if (events[e.type] != null && typeof events[e.type] === 'function')
      return events[e.type].call(this, e, function (d) {
        cb(null, d)
      })
    cb(null, e)
  })
}

var Swarm = module.exports = function Swarm(api) {
  var params = clone(api.config.info)

  if (!params) params = {}
  params.encoding = params.encoding || 'base58'
  params.authenticate = params.authenticate || function authenticate(id, cb) {
    cb(null, true)
  }
  params.encoding = params.encoding || 'base58'

  params.keys = clone(params.keys)
  var peer = Peer(params)
  var peers = {}
  var seen = []
  var _manifest = {}
  var manifest = manifest = {}

  var notify = Notify()
  var _ready = false
  var queue = []
  var gid = 0
  var shutdown = false
  api.config.swarm = api.config.swarm || {}
  var _api = api

  var timeout = function (d, time, onTimeout) {
    var ts = Date.now()
    time = time || ms('20s')
    var closed = false
    var timer = setInterval(function () {
      if (Date.now() - ts >= time) end()

    }, time)

    var end = function () {
      if (closed === true) return
      clearInterval(timer)
      closed = true
      onTimeout()
    }

    var lastChange = function () {
      return _.asyncMap(function (data, cb) {
        ts = Date.now()
        cb(null, data)
      })
    }

    return {
      source: _(d.source, abortable(end), lastChange()),
      sink: _(lastChange(), abortable(end), d.sink)
    }
  }

  function source() {
    if (_ready === false) {

      _ready = notify.listen()
      _(_(peer, peer.asyncMap({
        connection: function (e, cb) {
          api.logger.info('connection from', e.peerID, 'protocol', e.protocol, 'on', api.id)

          _(e, handshake(_manifest || {}, function (err, rest, remote) {

            if (err) {
              if (e.rpcCallback != null) {
                var c = e.rpcCallback
                delete e.rpcCallback
                c(err)
              }
              api.logger.error('handshake error', err)
              return cb(null)
            }

            var close = false

            var found = false
            for (var i in peers) {
              var p = peers[i]
              if (p.peerID === e.peerID) {
                found = true
                break
              }
            }

            if (e.peerID && found === true) {
              err = 'closing connection to peer ' + e.peerID + ' is already connected on ' + api.id
              close = true
            }

            if (e.peerID == null) {
              err = 'closing the connection peerID is undefined or null ' + api.id
              close = true
            }

            if (shutdown === true) {
               err = 'peer cannot accept new connections, because it is shutting down'
               close = true
            }

            e.id = ++gid
            peers[e.id] = e
            e.protocols = []
            Object.keys(remote).forEach(function (i) { e.protocols.push(i) })
            e.manifest = remote

            var muxrpc = MRPC(remote, _manifest)(_api, null, e.id)

            _(rest, timeout(muxrpc.createStream(), api.config.swarm.timeout = api.config.swarm.timeout || ms('40s'), function () {
              if (this.end) this.end()
              close = true
            }.bind(e)), rest)
            e.peer = muxrpc
            e.end = muxrpc.close.bind(muxrpc, err || true, function (err) {
              if (err) api.logger.error(err)
            })
            if (close === true) {
              muxrpc.close(err, function () {
                if (err) api.logger.warn(err)
              })
              return cb(e)
            }

            delete e.peer.close
            delete e.peer.createStream

            cb(e)
          }, e.address == null), e)
        },
        disconnection: function (e, cb) {
          if (e.id != null && peers[e.id] != null) delete peers[e.id]
          cb(e)
        }
      })), _.filter(function (e) {
        return e != null
      }), peer.asyncMap({
        connection: function (e, cb) {
          if (e.rpcCallback != null) {
            var c = e.rpcCallback
            delete e.rpcCallback
            c(null, e)
            return cb(e)
          }
          cb(e)
        }
      }), _.drain(notify, notify.abort))

    }
    return _ready.apply(null, [].slice.call(arguments))
  }

  source.peerID = util.encode(params.keys.publicKey, params.encoding)

  source.map = peer.map
  source.asyncMap = peer.asyncMap
  source.paraMap = para

  source.events = notify.listen
  source.encoding = params.encoding
  source.protoNames = peer.protoNames
  source.push = peer.push
  source.path = 'swarm'
  source.connect = function (addr, params, cb) {

    if (shutdown === true) {
      if (cb) cb(new Error('shutting down'))
      return
    }
    if (_.isFunction(params)) {
      cb = params
      params = null
    }

    params = params || {}
    var id = URL.parse(addr).auth

    var found = false

    for (var i in peers) {
      var p = peers[i]
      if (p.peerID === id) {
        if (cb) return cb(null, p)
        found = true
        if (!cb) break
      }
    }

    if (found !== true && seen.indexOf(id) === -1) {
      seen.push(id)
      return peer.connect(addr, params, function (err, connection) {

        if (seen.indexOf(id) !== -1) seen.splice(seen.indexOf(id), 1)
        if (cb) {

          if (err != null) return cb(err)

          connection.rpcCallback = cb
        }
      })
    }

    return cb(new Error('peer already connecting'))
  }

  source.end = function () {
    if (shutdown === true) return
    shutdown = true
    peer.end.apply(peer, [].slice.call(arguments))
  }

  source.listen = peer.listen
  source.on = peer.on
  source.connections = peers
  source.combine = peer.combine

  var protocols = []

  source.addProtocol = function (protocol) {
    if (protocol.path == null && protocol.manifest == null) return
    protocols.push({ path: protocol.path, manifest: protocol.manifest })
    m.mount(_manifest, protocol.path.split('/'), protocol.manifest)
    m.mount(_api, protocol.path.split('/'), protocol)
  }
  source.path = 'swarm'
  source.manifest = manifest
  source.addProtocol(source)
  return source
}

Swarm.util = Peer.util<commit_msg>clearInterval  on connection end<commit_after>var Peer = require('icebreaker-peer')
var util = Peer.util
var _ = require('icebreaker')
var m = require('muxrpc/util')
var ms = require('ms')
var Notify = require('pull-notify')
var MRPC = require('muxrpc')
var URL = require('url')
var clone = require('lodash.clonedeep')
var paramap = require('pull-paramap')
var handshake = require('./handshake')

function para(events) {
  return paramap(function handle(e, cb) {
    if (events[e.type] != null && typeof events[e.type] === 'function')
      return events[e.type].call(this, e, function (d) {
        cb(null, d)
      })
    cb(null, e)
  })
}

var Swarm = module.exports = function Swarm(api) {
  var params = clone(api.config.info)

  if (!params) params = {}
  params.encoding = params.encoding || 'base58'
  params.authenticate = params.authenticate || function authenticate(id, cb) {
    cb(null, true)
  }
  params.encoding = params.encoding || 'base58'

  params.keys = clone(params.keys)
  var peer = Peer(params)
  var peers = {}
  var seen = []
  var _manifest = {}
  var manifest = manifest = {}

  var notify = Notify()
  var _ready = false
  var queue = []
  var gid = 0
  var shutdown = false
  api.config.swarm = api.config.swarm || {}
  var _api = api

  var timeout = require('./timeout')

  function source() {
    if (_ready === false) {

      _ready = notify.listen()
      _(_(peer, peer.asyncMap({
        connection: function (e, cb) {
          api.logger.info('connection from', e.peerID, 'protocol', e.protocol, 'on', api.id)

          _(e, handshake(_manifest || {}, function (err, rest, remote) {

            if (err) {
              if (e.rpcCallback != null) {
                var c = e.rpcCallback
                delete e.rpcCallback
                c(err)
              }
              api.logger.error('handshake error', err)
              return cb(null)
            }

            var close = false

            var found = false
            for (var i in peers) {
              var p = peers[i]
              if (p.peerID === e.peerID) {
                found = true
                break
              }
            }

            if (e.peerID && found === true) {
              err = 'closing connection to peer ' + e.peerID + ' is already connected on ' + api.id
              close = true
            }

            if (e.peerID == null) {
              err = 'closing the connection peerID is undefined or null ' + api.id
              close = true
            }

            if (shutdown === true) {
               err = 'peer cannot accept new connections, because it is shutting down'
               close = true
            }

            e.id = ++gid
            peers[e.id] = e
            e.protocols = []
            Object.keys(remote).forEach(function (i) { e.protocols.push(i) })
            e.manifest = remote
            var muxrpc = MRPC(remote, _manifest)(_api, null, e.id)

            var t

            _(rest, t=timeout(muxrpc.createStream(), api.config.swarm.timeout = api.config.swarm.timeout || ms('40s'), function () {
              if (this.end) this.end()
              close = true
            }.bind(e)), rest)
            e.peer = muxrpc
            e.end = muxrpc.close.bind(muxrpc, err || true, function (_err) {
              if (_err) api.logger.error(_err)
              else if(err!=null)api.logger.warn(err)
              t.end()
            })
            if (close === true) {
              e.end();
              return cb(e)
            }

            delete e.peer.close
            delete e.peer.createStream

            cb(e)
          }, e.address == null), e)
        },
        disconnection: function (e, cb) {
          if (e.id != null && peers[e.id] != null) delete peers[e.id]
          cb(e)
        }
      })), _.filter(function (e) {
        return e != null
      }), peer.asyncMap({
        connection: function (e, cb) {
          if (e.rpcCallback != null) {
            var c = e.rpcCallback
            delete e.rpcCallback
            c(null, e)
            return cb(e)
          }
          cb(e)
        }
      }), _.drain(notify, notify.abort))

    }
    return _ready.apply(null, [].slice.call(arguments))
  }

  source.peerID = util.encode(params.keys.publicKey, params.encoding)

  source.map = peer.map
  source.asyncMap = peer.asyncMap
  source.paraMap = para

  source.events = notify.listen
  source.encoding = params.encoding
  source.protoNames = peer.protoNames
  source.push = peer.push
  source.path = 'swarm'
  source.connect = function (addr, params, cb) {

    if (shutdown === true) {
      if (cb) cb(new Error('shutting down'))
      return
    }
    if (_.isFunction(params)) {
      cb = params
      params = null
    }

    params = params || {}
    var id = URL.parse(addr).auth

    var found = false

    for (var i in peers) {
      var p = peers[i]
      if (p.peerID === id) {
        if (cb) return cb(null, p)
        found = true
        if (!cb) break
      }
    }

    if (found !== true && seen.indexOf(id) === -1) {
      seen.push(id)
      return peer.connect(addr, params, function (err, connection) {

        if (seen.indexOf(id) !== -1) seen.splice(seen.indexOf(id), 1)
        if (cb) {

          if (err != null) return cb(err)

          connection.rpcCallback = cb
        }
      })
    }

    return cb(new Error('peer already connecting'))
  }

  source.end = function () {
    if (shutdown === true) return
    shutdown = true
    peer.end.apply(peer, [].slice.call(arguments))
  }

  source.listen = peer.listen
  source.on = peer.on
  source.connections = peers
  source.combine = peer.combine

  var protocols = []

  source.addProtocol = function (protocol) {
    if (protocol.path == null && protocol.manifest == null) return
    protocols.push({ path: protocol.path, manifest: protocol.manifest })
    m.mount(_manifest, protocol.path.split('/'), protocol.manifest)
    m.mount(_api, protocol.path.split('/'), protocol)
  }
  source.path = 'swarm'
  source.manifest = manifest
  source.addProtocol(source)
  return source
}

Swarm.util = Peer.util<|endoftext|>


<commit_before>/*
 * Swipe 1.0
 *
 * Brad Birdsall, Prime
 * Copyright 2011, Licensed GPL & MIT
 *
*/

window.Swipe = function(element, options) {

  // return immediately if element doesn't exist
  if (!element) return null;

  var _this = this;

  // retreive options
  this.options = options || {};
  this.index = this.options.startSlide || 0;
  this.speed = this.options.speed || 300;
  this.callback = this.options.callback || function() {};
  this.delay = this.options.auto || 0;

  // reference dom elements
  this.container = element;
  this.element = this.container.children[0]; // the slide pane

  // static css
  this.container.style.overflow = 'hidden';
  this.element.style.listStyle = 'none';

  // trigger slider initialization
  this.setup();

  // begin auto slideshow
  this.begin();

  // add event listeners
  if (this.element.addEventListener) {
    this.element.addEventListener('touchstart', this, false);
    this.element.addEventListener('touchmove', this, false);
    this.element.addEventListener('touchend', this, false);
    this.element.addEventListener('webkitTransitionEnd', this, false);
    this.element.addEventListener('msTransitionEnd', this, false);
    this.element.addEventListener('oTransitionEnd', this, false);
    this.element.addEventListener('transitionend', this, false);
    window.addEventListener('resize', this, false);
  }

};

Swipe.prototype = {

  setup: function() {

    // get and measure amt of slides
    this.slides = this.element.children;
    this.length = this.slides.length;

    // return immediately if their are less than two slides
    if (this.length < 2) return null;

    // determine width of each slide
    this.width = this.container.getBoundingClientRect().width;

    // return immediately if measurement fails
    if (!this.width) return null;

    // hide slider element but keep positioning during setup
    this.container.style.visibility = 'hidden';

    // dynamic css
    this.element.style.width = (this.slides.length * this.width) + 'px';
    var index = this.slides.length;
    while (index--) {
      var el = this.slides[index];
      el.style.width = this.width + 'px';
      el.style.display = 'table-cell';
      el.style.verticalAlign = 'top';
    }

    // set start position and force translate to remove initial flickering
    this.slide(this.index, 0);

    // show slider element
    this.container.style.visibility = 'visible';

  },

  slide: function(index, duration) {

    var style = this.element.style;

    // set duration speed (0 represents 1-to-1 scrolling)
    style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = duration + 'ms';

    // translate to given index position
    style.webkitTransform = 'translate3d(' + -(index * this.width) + 'px,0,0)';
    style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + -(index * this.width) + 'px)';

    // set new index to allow for expression arguments
    this.index = index;

  },

  getPos: function() {

    // return current index position
    return this.index;

  },

  prev: function(delay) {

    // cancel slideshow
    this.delay = delay || 0;
    clearTimeout(this.interval);

    // if not at first slide
    if (this.index) this.slide(this.index-1, this.speed);

  },

  next: function(delay) {

    // cancel slideshow
    this.delay = delay || 0;
    clearTimeout(this.interval);

    if (this.index < this.length - 1) this.slide(this.index+1, this.speed); // if not last slide
    else this.slide(0, this.speed); //if last slide return to start

  },

  begin: function() {

    var _this = this;

    this.interval = (this.delay)
      ? setTimeout(function() {
        _this.next(_this.delay);
      }, this.delay)
      : 0;

  },

  stop: function() {
    this.delay = 0;
    clearTimeout(this.interval);
  },

  handleEvent: function(e) {
    switch (e.type) {
      case 'touchstart': this.onTouchStart(e); break;
      case 'touchmove': this.onTouchMove(e); break;
      case 'touchend': this.onTouchEnd(e); break;
      case 'webkitTransitionEnd':
      case 'msTransitionEnd':
      case 'oTransitionEnd':
      case 'transitionend': this.transitionEnd(e); break;
      case 'resize': this.setup(); break;
    }
  },

  transitionEnd: function(e) {

    if (this.delay) this.begin();

    this.callback(e, this.index, this.slides[this.index]);

  },

  onTouchStart: function(e) {

    this.start = {

      // get touch coordinates for delta calculations in onTouchMove
      pageX: e.touches[0].pageX,
      pageY: e.touches[0].pageY,

      // set initial timestamp of touch sequence
      time: Number( new Date() )

    };

    // used for testing first onTouchMove event
    this.isScrolling = undefined;

    // reset deltaX
    this.deltaX = 0;

    // set transition time to 0 for 1-to-1 touch movement
    this.element.style.webkitTransitionDuration = 0;

  },

  onTouchMove: function(e) {

    // ensure swiping with one touch and not pinching
    if(e.touches.length > 1 || e.scale && e.scale !== 1) return;

    this.deltaX = e.touches[0].pageX - this.start.pageX;

    // determine if scrolling test has run - one time test
    if ( typeof this.isScrolling == 'undefined') {
      this.isScrolling = !!( this.isScrolling || Math.abs(this.deltaX) < Math.abs(e.touches[0].pageY - this.start.pageY) );
    }

    // if user is not trying to scroll vertically
    if (!this.isScrolling) {

      // prevent native scrolling
      e.preventDefault();

      // cancel slideshow
      clearTimeout(this.interval);

      // increase resistance if first or last slide
      this.deltaX =
        this.deltaX /
          ( (!this.index && this.deltaX > 0               // if first slide and sliding left
            || this.index == this.length - 1              // or if last slide and sliding right
            && this.deltaX < 0                            // and if sliding at all
          ) ?
          ( Math.abs(this.deltaX) / this.width + 1 )      // determine resistance level
          : 1 );                                          // no resistance if false

      // translate immediately 1-to-1
      this.element.style.webkitTransform = 'translate3d(' + (this.deltaX - this.index * this.width) + 'px,0,0)';

    }

  },

  onTouchEnd: function(e) {

    // determine if slide attempt triggers next/prev slide
    var isValidSlide =
          Number(new Date()) - this.start.time < 250      // if slide duration is less than 250ms
          && Math.abs(this.deltaX) > 20                   // and if slide amt is greater than 20px
          || Math.abs(this.deltaX) > this.width/2,        // or if slide amt is greater than half the width

    // determine if slide attempt is past start and end
        isPastBounds =
          !this.index && this.deltaX > 0                          // if first slide and slide amt is greater than 0
          || this.index == this.length - 1 && this.deltaX < 0;    // or if last slide and slide amt is less than 0

    // if not scrolling vertically
    if (!this.isScrolling) {

      // call slide function with slide end value based on isValidSlide and isPastBounds tests
      this.slide( this.index + ( isValidSlide && !isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0 ), this.speed );

    }

  }

};
<commit_msg>clarified comments  a little<commit_after>/*
 * Swipe 1.0
 *
 * Brad Birdsall, Prime
 * Copyright 2011, Licensed GPL & MIT
 *
*/

window.Swipe = function(element, options) {

  // return immediately if element doesn't exist
  if (!element) return null;

  var _this = this;

  // retreive options
  this.options = options || {};
  this.index = this.options.startSlide || 0;
  this.speed = this.options.speed || 300;
  this.callback = this.options.callback || function() {};
  this.delay = this.options.auto || 0;

  // reference dom elements
  this.container = element;
  this.element = this.container.children[0]; // the slide pane

  // static css
  this.container.style.overflow = 'hidden';
  this.element.style.listStyle = 'none';

  // trigger slider initialization
  this.setup();

  // begin auto slideshow
  this.begin();

  // add event listeners
  if (this.element.addEventListener) {
    this.element.addEventListener('touchstart', this, false);
    this.element.addEventListener('touchmove', this, false);
    this.element.addEventListener('touchend', this, false);
    this.element.addEventListener('webkitTransitionEnd', this, false);
    this.element.addEventListener('msTransitionEnd', this, false);
    this.element.addEventListener('oTransitionEnd', this, false);
    this.element.addEventListener('transitionend', this, false);
    window.addEventListener('resize', this, false);
  }

};

Swipe.prototype = {

  setup: function() {

    // get and measure amt of slides
    this.slides = this.element.children;
    this.length = this.slides.length;

    // return immediately if their are less than two slides
    if (this.length < 2) return null;

    // determine width of each slide
    this.width = this.container.getBoundingClientRect().width;

    // return immediately if measurement fails
    if (!this.width) return null;

    // hide slider element but keep positioning during setup
    this.container.style.visibility = 'hidden';

    // dynamic css
    this.element.style.width = (this.slides.length * this.width) + 'px';
    var index = this.slides.length;
    while (index--) {
      var el = this.slides[index];
      el.style.width = this.width + 'px';
      el.style.display = 'table-cell';
      el.style.verticalAlign = 'top';
    }

    // set start position and force translate to remove initial flickering
    this.slide(this.index, 0);

    // show slider element
    this.container.style.visibility = 'visible';

  },

  slide: function(index, duration) {

    var style = this.element.style;

    // set duration speed (0 represents 1-to-1 scrolling)
    style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = duration + 'ms';

    // translate to given index position
    style.webkitTransform = 'translate3d(' + -(index * this.width) + 'px,0,0)';
    style.msTransform = style.MozTransform = style.OTransform = 'translateX(' + -(index * this.width) + 'px)';

    // set new index to allow for expression arguments
    this.index = index;

  },

  getPos: function() {

    // return current index position
    return this.index;

  },

  prev: function(delay) {

    // cancel next scheduled automatic transition, if any
    this.delay = delay || 0;
    clearTimeout(this.interval);

    // if not at first slide
    if (this.index) this.slide(this.index-1, this.speed);

  },

  next: function(delay) {

    // cancel next scheduled automatic transition, if any
    this.delay = delay || 0;
    clearTimeout(this.interval);

    if (this.index < this.length - 1) this.slide(this.index+1, this.speed); // if not last slide
    else this.slide(0, this.speed); //if last slide return to start

  },

  begin: function() {

    var _this = this;

    this.interval = (this.delay)
      ? setTimeout(function() {
        _this.next(_this.delay);
      }, this.delay)
      : 0;

  },

  stop: function() {
    this.delay = 0;
    clearTimeout(this.interval);
  },

  handleEvent: function(e) {
    switch (e.type) {
      case 'touchstart': this.onTouchStart(e); break;
      case 'touchmove': this.onTouchMove(e); break;
      case 'touchend': this.onTouchEnd(e); break;
      case 'webkitTransitionEnd':
      case 'msTransitionEnd':
      case 'oTransitionEnd':
      case 'transitionend': this.transitionEnd(e); break;
      case 'resize': this.setup(); break;
    }
  },

  transitionEnd: function(e) {

    if (this.delay) this.begin();

    this.callback(e, this.index, this.slides[this.index]);

  },

  onTouchStart: function(e) {

    this.start = {

      // get touch coordinates for delta calculations in onTouchMove
      pageX: e.touches[0].pageX,
      pageY: e.touches[0].pageY,

      // set initial timestamp of touch sequence
      time: Number( new Date() )

    };

    // used for testing first onTouchMove event
    this.isScrolling = undefined;

    // reset deltaX
    this.deltaX = 0;

    // set transition time to 0 for 1-to-1 touch movement
    this.element.style.webkitTransitionDuration = 0;

  },

  onTouchMove: function(e) {

    // ensure swiping with one touch and not pinching
    if(e.touches.length > 1 || e.scale && e.scale !== 1) return;

    this.deltaX = e.touches[0].pageX - this.start.pageX;

    // determine if scrolling test has run - one time test
    if ( typeof this.isScrolling == 'undefined') {
      this.isScrolling = !!( this.isScrolling || Math.abs(this.deltaX) < Math.abs(e.touches[0].pageY - this.start.pageY) );
    }

    // if user is not trying to scroll vertically
    if (!this.isScrolling) {

      // prevent native scrolling
      e.preventDefault();

      // cancel slideshow
      clearTimeout(this.interval);

      // increase resistance if first or last slide
      this.deltaX =
        this.deltaX /
          ( (!this.index && this.deltaX > 0               // if first slide and sliding left
            || this.index == this.length - 1              // or if last slide and sliding right
            && this.deltaX < 0                            // and if sliding at all
          ) ?
          ( Math.abs(this.deltaX) / this.width + 1 )      // determine resistance level
          : 1 );                                          // no resistance if false

      // translate immediately 1-to-1
      this.element.style.webkitTransform = 'translate3d(' + (this.deltaX - this.index * this.width) + 'px,0,0)';

    }

  },

  onTouchEnd: function(e) {

    // determine if slide attempt triggers next/prev slide
    var isValidSlide =
          Number(new Date()) - this.start.time < 250      // if slide duration is less than 250ms
          && Math.abs(this.deltaX) > 20                   // and if slide amt is greater than 20px
          || Math.abs(this.deltaX) > this.width/2,        // or if slide amt is greater than half the width

    // determine if slide attempt is past start and end
        isPastBounds =
          !this.index && this.deltaX > 0                          // if first slide and slide amt is greater than 0
          || this.index == this.length - 1 && this.deltaX < 0;    // or if last slide and slide amt is less than 0

    // if not scrolling vertically
    if (!this.isScrolling) {

      // call slide function with slide end value based on isValidSlide and isPastBounds tests
      this.slide( this.index + ( isValidSlide && !isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0 ), this.speed );

    }

  }

};
<|endoftext|>


<commit_before> /**
* e 为初始化该插件传进的参数
* e.startIndex 默认在第几屏（默认从0开始）
* e.swipeTime 滑动一次时间 (毫秒级别)
* e.continues false/true 是否以无限滑动方式(滑倒最后一页，继续下滑时翻到第一页)
* e.swipeWhenSwiping false/true 在一页滑动过程中，是否可以连续滑动
* e.onSwipeStart 滑动开始回调函数,返回true/false,true会继续触发滑动，false停止该动作
* e.onSwipeEnd 滑动结束触发函数
* e.swipeLimitedSize 设置判定用户竖向滑动的移动像素大小(默认为100像素)
* e.floowSwipe 页面是否跟随手指滑动产生滑动效果
*/
function Swipe(e) {
	var that = this;
	var swipeBody, children, swipeBodyStyle, startPos, endPos, movePos, timer,
		UP = 1,
		DOWN = -1,
		SWIPE_LIMITED_SIZE = 100,
		DEFAULT_SWIPE_TIME = 400;
	var handler = {
		currentIndex: function() {
			var currentIndex = that.currentIndex;
			return that.e.continues ? currentIndex - 1 : currentIndex;
		},
		next: function() {
			quickSwipe(that.currentIndex);
			swipeTo(that.currentIndex + 1);
		},
		prev: function() {
			quickSwipe(that.currentIndex);
			swipeTo(that.currentIndex - 1);
		},
		swipeTo: function(index) {
			if(typeof index !== "number" || index <= 0 || index > that.e.defaultEndIndex) {
				return false;
			}

			quickSwipe(that.currentIndex);
			swipeTo(index);
		}
	};

	var Helper = {
		setTransitionYMove: function(dist, time) {
			swipeBodyStyle.webkitTransitionDuration =
			swipeBodyStyle.MozTransitionDuration =
			swipeBodyStyle.msTransitionDuration =
			swipeBodyStyle.OTransitionDuration =
			swipeBodyStyle.transitionDuration = time + 'ms';

			swipeBodyStyle.webkitTransform = 'translate(0, ' + dist+')' + 'translateZ(0)';
			swipeBodyStyle.msTransform =
			swipeBodyStyle.MozTransform =
			swipeBodyStyle.OTransform = 'translateY(' + dist+')';
		},
		resetIndex: function() {
			if(!that.e.continues) {
				return false;
			};

			switch(that.currentIndex) {
				case that.childrenLength-1:
					that.currentIndex = that.e.defaultStartIndex;
					that.isResetIndex = true;
				break;
				case 0:
					that.currentIndex = that.e.defaultEndIndex;
					that.isResetIndex = true;
				break;
				default:
					that.isResetIndex = false;
			}

			return that.isResetIndex;
		},
		getEventPos: function(e, isTouchEnd) {
			if(that.touch) {
				return {
					x: isTouchEnd ? (e.changedTouches[0].pageX || e.changedTouches[0].clientX) : (e.touches[0].pageX || e.touches[0].pageY),
					y: isTouchEnd ? (e.changedTouches[0].pageY || e.changedTouches[0].clientY) : (e.touches[0].pageY || e.touches[0].clientY)
				};
			}

			return {
				x: e.pageX || e.clientX,
				y: e.pageY || e.clientY
			}
		},
		animate: {
			run: function(from, to, speed, callback) {
			    if (!speed) {
		      		swipeBodyStyle.top = to + '%';
			      return;
			    }

			    var start = +new Date;
			    timer = setInterval(function() {
		     	 	var timeElap = +new Date - start;
	     		 	if (timeElap > speed) {
			        	swipeBodyStyle.top = to + '%';
			        	callback && callback();

			        	clearInterval(timer);
			        	return;
			      	}

		     		swipeBodyStyle.top = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + '%';
			    }, 4);
		  	},
			stop: function() {
				clearInterval(timer);

				return this;
			}
		},
		eventHandlers: {
			bindInitedEvent: function() {
				if(that.transitions) {
					swipeBody.addEventListener('webkitTransitionEnd', Helper.eventHandlers.swipeEnd, false);
					swipeBody.addEventListener('msTransitionEnd', Helper.eventHandlers.swipeEnd, false);
					swipeBody.addEventListener('oTransitionEnd', Helper.eventHandlers.swipeEnd, false);
					swipeBody.addEventListener('otransitionend', Helper.eventHandlers.swipeEnd, false);
					swipeBody.addEventListener('transitionend', Helper.eventHandlers.swipeEnd, false);
				}
				if(that.touch) {
					that.e.dom.addEventListener("touchstart", Helper.eventHandlers.touchStart, false);
				} else {
					that.e.dom.addEventListener("mousedown", Helper.eventHandlers.touchStart, false);
				}
			},
			bindOtherEvents: function() {
				if(that.touch) {
					that.e.dom.addEventListener("touchmove", Helper.eventHandlers.touchMove, false);
					that.e.dom.addEventListener("touchend", Helper.eventHandlers.touchEnd, false);
				} else {
					that.e.dom.addEventListener("mousemove", Helper.eventHandlers.touchMove, false);
					that.e.dom.addEventListener("mouseup", Helper.eventHandlers.touchEnd, false);
				}
			},
			unbindOtherEvents: function() {
				if(that.touch) {
					that.e.dom.removeEventListener("touchmove", Helper.eventHandlers.touchMove, false);
					that.e.dom.removeEventListener("touchend", Helper.eventHandlers.touchEnd, false);
				} else {
					that.e.dom.removeEventListener("mousemove", Helper.eventHandlers.touchMove, false);
					that.e.dom.removeEventListener("mouseup", Helper.eventHandlers.touchEnd, false);
				}
			},
			swipeEnd: function() {
				that.swiping = false;
				Helper.resetIndex();
				if(that.e.continues && that.isResetIndex) {
					if(that.transitions) {
						Helper.setTransitionYMove(-that.currentIndex*100+"%", 0);
					} else {
						swipeBodyStyle.top = -that.currentIndex*100+"%";
					}
				}

				that.e.onSwipeEnd && that.e.onSwipeEnd.call(children[that.currentIndex]);
			},
			touchStart: function(e) {
			    startPos = Helper.getEventPos(e);
			    startPos.time = +new Date();

			    Helper.eventHandlers.bindOtherEvents();
			},
			touchMove: function(e) {
				e.preventDefault && e.preventDefault();
				if(!that.e.floowSwipe) {
					movePos = {
						time: 0
					};
					return true;
				}
				movePos = Helper.getEventPos(e);
				movePos.time = +new Date();

			    var distPosY = "calc("+(-that.currentIndex*100+"% + "+(movePos.y-startPos.y))+"px)";
			    // 同步拖动过程
			    if(that.transitions) {
			    	Helper.setTransitionYMove(distPosY, 0);
			    } else {
					Helper.animate.stop().run(-that.currentIndex*100, distPosY, 0);
			    }
			},
			touchEnd: function(e) {
				endPos = Helper.getEventPos(e, true);
		     	if(Math.abs(endPos.y - startPos.y) < that.swipeLimitedSize) {
		     		// 还原设置
		     		if(that.transitions) {
		     			Helper.setTransitionYMove((-that.currentIndex*100)+"%", that.e.swipeTime / 2);
		     		} else {
		     			Helper.animate.stop().run(parseFloat(swipeBodyStyle.top), -that.currentIndex*100, 0);
		     		}
		     		return;
		     	}
		     	Helper.eventHandlers.swipeHandler(endPos.y > startPos.y ? DOWN : UP);
		     	Helper.eventHandlers.unbindOtherEvents();
			},
			swipeHandler: function(offsetIndex) {
				if(that.swipeHandlerExecing) {
					return;
				}
				that.swipeHandlerExecing = true;
				if(!that.swiping) {
					if(that.e.onSwipeStart && !that.e.onSwipeStart()) {
						that.swipeHandlerExecing = false;
						return;
					}
				} else {
					if(!that.e.swipeWhenSwiping) {
						that.swipeHandlerExecing = false;
						return;
					}
					quickSwipe(that.currentIndex, function() {
						swipeTo(that.currentIndex + offsetIndex);
						that.swipeHandlerExecing = false;
					});
					return;
				}

				swipeTo(that.currentIndex + offsetIndex);
				that.swipeHandlerExecing = false;
			}
		}
	};
	function initParam() {
		!e && (e = {});
		if(!e.dom) {
			throw new Error("缺少参数！");
		}

		var dom = e.dom;
		swipeBody = dom.getElementsByClassName("swipeBody")[0];
		children = swipeBody.children;
		swipeBodyStyle = swipeBody.style;
		e.startIndex = e.startIndex ? e.startIndex-1 : 0;
		e.defaultStartIndex = 0;
		e.defaultEndIndex = children.length-1;
		e.swipeTime = e.swipeTime || DEFAULT_SWIPE_TIME;
		that.e = e;
		that.currentIndex = 0;
		that.swiping = false;
		that.transitions = false;
		that.swipeLimitedSize = e.swipeLimitedSize || SWIPE_LIMITED_SIZE;
		that.touch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;
		// check transitions
		(function(undefined) {
			var checkTransitionArray = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
			var checkTransitionDom = document.createElement("div");
			for(var i=0, len=checkTransitionArray.length; i<len; i++) {
				if(checkTransitionDom.style[checkTransitionArray[i]] !== undefined) {
					that.transitions = true;
					break;
				}
			}
		})();
	};

	function init() {
		initParam();
		/*初始化无限滑动部分*/
		if(that.e.continues && children.length > 2) {
			var last = children[children.length - 1];
			var first = children[0];
			swipeBody.appendChild(first.cloneNode(true));
			swipeBody.insertBefore(last.cloneNode(true), first);
			children = swipeBody.children;
			that.e.defaultStartIndex += 1;
			that.e.startIndex += 1;
			that.e.defaultEndIndex += 1;
		}
		that.childrenLength = children.length;

		Helper.eventHandlers.bindInitedEvent();
	};
	function swipeTo(index) {
		if(index < 0 || (!that.e.continues && index >= that.childrenLength)) {
			return;
		}
		var prevIndex = that.currentIndex;
		that.currentIndex = index;
		that.swiping = true;
		var moveCostTime = that.e.floowSwipe ? (movePos.time - startPos.time): 0;
		var time = that.e.swipeTime - moveCostTime;
		time = time < that.e.swipeTime/3 ? that.e.swipeTime/3 : time;
		if(that.transitions) {
			Helper.setTransitionYMove(-index*100+"%", time);
		} else {
			Helper.animate.stop().run((parseFloat(swipeBodyStyle.top) || 0), -index*100, time, Helper.eventHandlers.swipeEnd);
		}
	};
	function quickSwipe(index, callback) {
		if(index < 0 || (!that.e.continues && index >= that.childrenLength)) {
			return;
		}

		that.currentIndex = index;
		Helper.resetIndex();
		if(that.transitions) {
			Helper.setTransitionYMove(-that.currentIndex*100+"%", 0);
		} else {
			Helper.animate.stop().run((parseFloat(swipeBodyStyle.top) || 0), -that.currentIndex*100, 0);
		}

		that.swiping = false;
		// 防止浏览器针对脚本优化产生的bug
		setTimeout(function() {
			callback && callback();
		}, 0);
	};

	init();
	quickSwipe(that.e.startIndex);

	return handler;
}
<commit_msg>Update swipe.js<commit_after>
<|endoftext|>