<commit_before>Kwf.onContentReady(function(readyEl) {
    var els = document.getElementsByTagName('a');
    for (var i=0; i<els.length; i++) {
        if (els[i].kwfLightbox) continue;
        var m = els[i].rel.match(/(^lightbox| lightbox)({.*?})?/);
        if (m) {
            var options = {};
            if (m[2]) options = Ext.decode(m[2]);
            var l;
            if (Kwf.EyeCandy.Lightbox.allByUrl[els[i].href]) {
                l = Kwf.EyeCandy.Lightbox.allByUrl[els[i].href];
            } else {
                l = new Kwf.EyeCandy.Lightbox.Lightbox(Ext.get(els[i]).dom.href, options);
            }
            els[i].kwfLightbox = l;
            Ext.EventManager.addListener(els[i], 'click', function(ev) {
                this.kwfLightbox.show({
                    clickTarget: Ext.get(this)
                });
                Kwf.Utils.HistoryState.currentState.lightbox = this.href;
                Kwf.Utils.HistoryState.pushState(document.title, this.href);
                ev.stopEvent();
            }, els[i], { stopEvent: true });
        }
    }

    Ext.query('.kwfLightbox').each(function(el) {
        if (el.kwfLightbox) return;
        var lightboxEl = Ext.get(el);
        var options = Ext.decode(lightboxEl.child('input.options').dom.value);
        var l = new Kwf.EyeCandy.Lightbox.Lightbox(window.location.href, options);
        Kwf.Utils.HistoryState.currentState.lightbox = window.location.href;
        Kwf.Utils.HistoryState.replaceState(document.title, window.location.href);
        lightboxEl.enableDisplayMode('block');
        l.lightboxEl = lightboxEl;
        l.innerLightboxEl = lightboxEl.down('.kwfLightboxInner');
        l.fetched = true;
        l.initialize();
        l.closeHref = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
        l.contentEl = l.innerLightboxEl.down('.kwfLightboxContent');
        l.style.afterCreateLightboxEl();
        l.style.onShow();
        l.style.onContentReady();
        el.kwfLightbox = l;
        Kwf.EyeCandy.Lightbox.currentOpen = l;
    });

    readyEl = Ext.get(readyEl);
    if (readyEl.isVisible() && Kwf.EyeCandy.Lightbox.currentOpen) {
        if (Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl
            && Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl.isVisible()
            && (Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl.contains(readyEl)
            || readyEl.contains(Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl))
        ) {
            Kwf.EyeCandy.Lightbox.currentOpen.style.onContentReady();
        }
    }
});

Kwf.Utils.HistoryState.on('popstate', function() {
    var lightbox = Kwf.Utils.HistoryState.currentState.lightbox;
    if (lightbox) {
        if (!Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) return;
        if (Kwf.EyeCandy.Lightbox.currentOpen != Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) {
            Kwf.EyeCandy.Lightbox.allByUrl[lightbox].show();
        }
    } else {
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            Kwf.EyeCandy.Lightbox.currentOpen.close();
        }
    }
});

Ext.ns('Kwf.EyeCandy.Lightbox');
Kwf.EyeCandy.Lightbox.currentOpen = null;
Kwf.EyeCandy.Lightbox.allByUrl = {};
Kwf.EyeCandy.Lightbox.Lightbox = function(href, options) {
    this.href = href;
    Kwf.EyeCandy.Lightbox.allByUrl[href] = this;
    this.options = options;
    if (options.style) {
        this.style = new Kwf.EyeCandy.Lightbox.Styles[options.style](this);
    } else {
        this.style = new Kwf.EyeCandy.Lightbox.Styles.CenterBox(this);
    }
};
Kwf.EyeCandy.Lightbox.Lightbox.prototype = {
    fetched: false,
    _blockOnContentReady: false,
    createLightboxEl: function()
    {
        if (this.lightboxEl) return;

        var lightbox = Ext.getBody().createChild({
            cls: 'kwfLightbox' + (this.options.style ? ' kwfLightbox'+this.options.style : ''),
            html: '

'
        });
        lightbox.dom.kwfLightbox = this; //don't initialize again in onContentReady
        lightbox.enableDisplayMode('block');
        this.lightboxEl = lightbox;
        this.innerLightboxEl = lightbox.down('.kwfLightboxInner');

        var el = this.innerLightboxEl;

        if (this.options.width) {
            el.setWidth(parseInt(this.options.width) + el.getBorderWidth("lr") + el.getPadding("lr"));
        }
        if (this.options.height) {
            el.setHeight(parseInt(this.options.height) + el.getBorderWidth("tb") + el.getPadding("tb"));
        }
        this.style.afterCreateLightboxEl();
        this.lightboxEl.hide();
    },
    fetchContent: function()
    {
        if (this.fetched) return;
        this.fetched = true;

        var url = '/kwf/util/kwc/render';
        if (Kwf.Debug.rootFilename) url = Kwf.Debug.rootFilename + url;
        Ext.Ajax.request({
            params: { url: this.href },
            url: url,
            success: function(response, options) {
                this.contentEl = this.innerLightboxEl.createChild({
                    cls: 'kwfLightboxContent'
                });

                this.style.updateContent(response.responseText);

                if (this.lightboxEl.isVisible()) this.contentEl.hide();

                var showContent = function() {
                    this.innerLightboxEl.removeClass('kwfLightboxLoading');
                    this.innerLightboxEl.child('.loading').remove();
                    if (this.lightboxEl.isVisible()) {
                        this.contentEl.fadeIn();
                    }
                    this._blockOnContentReady = true; //don't resize twice
                    Kwf.callOnContentReady(this.contentEl.dom, {newRender: true});
                    this._blockOnContentReady = false;
                    this.style.afterContentShown();
                    if (this.lightboxEl.isVisible()) {
                        this.preloadLinks();
                    }
                };
                var imagesToLoad = 0;
                this.contentEl.query('img.hideWhileLoading').each(function(imgEl) {
                    imagesToLoad++;
                    imgEl.onload = (function() {
                        imagesToLoad--;
                        if (imagesToLoad <= 0) showContent.call(this);
                    }).createDelegate(this);
                }, this);
                if (imagesToLoad == 0) showContent.call(this);
                this.initialize();
            },
            failure: function() {
                //fallback
                location.href = this.href;
            },
            scope: this
        });
    },
    show: function(options)
    {
        this.createLightboxEl();
        this.style.onShow(options);

        if (!this.closeHref) {
            if (Kwf.EyeCandy.Lightbox.currentOpen) {
                this.closeHref = Kwf.EyeCandy.Lightbox.currentOpen.closeHref;
            } else {
                this.closeHref = window.location.href;
            }
        }
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            var closeOptions = {};
            if (options.clickTarget) closeOptions.showClickTarget = options.clickTarget;
            Kwf.EyeCandy.Lightbox.currentOpen.close(closeOptions);
        }
        Kwf.EyeCandy.Lightbox.currentOpen = this;

        this.lightboxEl.addClass('kwfLightboxOpen');
        if (this.fetched) {
            if (!this.lightboxEl.isVisible()) {
                this.lightboxEl.fadeIn();
                this.preloadLinks();
                Kwf.callOnContentReady(this.innerLightboxEl.dom, {newRender: false});
            }
            this.style.afterContentShown();
        } else {
            this.lightboxEl.show();
            this.fetchContent();
        }
        this.style.afterShow(options);
        Kwf.Statistics.count(this.href);
    },
    close: function(options) {
        this.lightboxEl.hide();
        //so eg. flash component can remove object
        Kwf.callOnContentReady(this.lightboxEl, {newRender: false});
        this.lightboxEl.show();

        this.style.onClose(options);
        this.lightboxEl.removeClass('kwfLightboxOpen');
        Kwf.EyeCandy.Lightbox.currentOpen = null;
    },
    closeAndPushState: function() {
        delete Kwf.Utils.HistoryState.currentState.lightbox;
        Kwf.Utils.HistoryState.pushState(document.title, this.closeHref);
        this.close();
    },
    initialize: function()
    {
        var closeButton = this.innerLightboxEl.child('.closeButton');
        if (closeButton) {
            closeButton.on('click', function(ev) {
                this.closeAndPushState();
                ev.stopEvent();
            }, this);
        }
        this.lightboxEl.on('click', function(ev) {
            if (ev.getTarget() == this.lightboxEl.dom) {
                this.closeAndPushState();
            }
        }, this);
    },
    preloadLinks: function() {
        this.innerLightboxEl.query('a.preload').each(function(el) {
            if (el.kwfLightbox) el.kwfLightbox.preload();
        }, this);
    },
    preload: function() {
        this.createLightboxEl();
        this.fetchContent();
    }
};

Kwf.EyeCandy.Lightbox.Styles = {};
Kwf.EyeCandy.Lightbox.Styles.Abstract = function(lightbox) {
    this.lightbox = lightbox;
};
Kwf.EyeCandy.Lightbox.Styles.Abstract.masks = 0;
Kwf.EyeCandy.Lightbox.Styles.Abstract.prototype = {
    afterCreateLightboxEl: Ext.emptyFn,
    afterContentShown: Ext.emptyFn,
    updateContent: function(responseText) {
        this.lightbox.contentEl.update(responseText);
    },
    onShow: Ext.emptyFn,
    afterShow: Ext.emptyFn,
    onClose: Ext.emptyFn,
    afterClose: Ext.emptyFn,
    onContentReady: Ext.emptyFn,

    mask: function() {
        //calling mask multiple times in valid, unmask must be called exactly often
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks++;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 1) return;
        Ext.getBody().addClass('kwfLightboxTheaterMode');
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        Ext.getBody().removeClass('x-masked-relative');
        maskEl.addClass('lightboxMask');
        maskEl.dom.style.height = '';
        maskEl.dom.style.width = '';

        //maskEl.setHeight(Math.max(Ext.lib.Dom.getViewHeight(), Ext.lib.Dom.getDocumentHeight()));

        maskEl.on('click', function() {
            this.lightbox.closeAndPushState();
        }, this);
    },
    unmask: function() {
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks--;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 0) return;
        Ext.getBody()._mask.fadeOut({
            concurrent: true,
            callback: function() {
                Ext.getBody().removeClass('kwfLightboxTheaterMode');
                Ext.getBody()._mask.remove();
            },
            scope: this
        });
    }
};

Kwf.EyeCandy.Lightbox.Styles.CenterBox = Ext.extend(Kwf.EyeCandy.Lightbox.Styles.Abstract, {
    afterCreateLightboxEl: function() {
        this._center();
    },
    afterContentShown: function() {
        this._center();
    },
    updateContent: function(responseText) {
        var isVisible = this.lightbox.lightboxEl.isVisible();

        this.lightbox.lightboxEl.show(); //to mesaure

        var originalSize = this.lightbox.innerLightboxEl.getSize();

        Kwf.EyeCandy.Lightbox.Styles.CenterBox.superclass.updateContent.apply(this, arguments);

        if (!this.lightbox.options.height) this.lightbox.innerLightboxEl.dom.style.height = '';
        if (!this.lightbox.options.width) this.lightbox.innerLightboxEl.dom.style.width = '';
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");

        if (isVisible) {
            this.lightbox.innerLightboxEl.setSize(newSize);
            if (this.lightbox.innerLightboxEl.getColor('backgroundColor')) {
                //animate size only if backgroundColor is set - else it doesn't make sense
                this._center(true);
                this.lightbox.innerLightboxEl.setSize(originalSize);
                this.lightbox.innerLightboxEl.setSize(newSize, null, true);
            } else {
                this._center(false);
            }
        } else {
            this.lightbox.innerLightboxEl.setSize(newSize);
            this._center(false);
            this.lightbox.lightboxEl.hide();
        }
    },
    onShow: function() {
        this.mask();
    },
    onClose: function(options) {
        this.lightboxEl.fadeOut({
            concurrent: true,
            callback: function() {
                this.afterClose();
            },
            scope: this
        });
        this.unmask();
    },
    _getCenterXy: function() {
        var xy = this.lightbox.innerLightboxEl.getAlignToXY(document, 'c-c');
        if (xy[1] < 20) xy[1] = 20;
        return xy;
    },
    _center: function(anim) {
        if (!this.lightbox.lightboxEl.isVisible(true)) return;
        this.lightbox.innerLightboxEl.setXY(this._getCenterXy(), anim);
    },

    onContentReady: function()
    {
        if (this.lightbox._blockOnContentReady) return;
        if (!this.lightbox.contentEl) return;

        //adjust size if height changed
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");
        if (this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter')) {
            newSize['height'] -= this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter').getPadding('tb');
        }
        var originalSize = this.lightbox.innerLightboxEl.getSize();
        this.lightbox.innerLightboxEl.setSize(newSize); //set to new size so centering works (no animation)
        var centerXy = this._getCenterXy();
        var xy = this.lightbox.innerLightboxEl.getXY();
        xy[0] = centerXy[0];
        if (centerXy[1] < xy[1]) xy[1] = centerXy[1]; //move up, but not down
        this.lightbox.innerLightboxEl.setXY(xy, true);
        this.lightbox.innerLightboxEl.setSize(originalSize); //set back to previous size for animation
        this.lightbox.innerLightboxEl.setSize(newSize, null, true); //now animate to new size
    }
});
<commit_msg>move click handler that closes lightbox into style<commit_after>Kwf.onContentReady(function(readyEl) {
    var els = document.getElementsByTagName('a');
    for (var i=0; i<els.length; i++) {
        if (els[i].kwfLightbox) continue;
        var m = els[i].rel.match(/(^lightbox| lightbox)({.*?})?/);
        if (m) {
            var options = {};
            if (m[2]) options = Ext.decode(m[2]);
            var l;
            if (Kwf.EyeCandy.Lightbox.allByUrl[els[i].href]) {
                l = Kwf.EyeCandy.Lightbox.allByUrl[els[i].href];
            } else {
                l = new Kwf.EyeCandy.Lightbox.Lightbox(Ext.get(els[i]).dom.href, options);
            }
            els[i].kwfLightbox = l;
            Ext.EventManager.addListener(els[i], 'click', function(ev) {
                this.kwfLightbox.show({
                    clickTarget: Ext.get(this)
                });
                Kwf.Utils.HistoryState.currentState.lightbox = this.href;
                Kwf.Utils.HistoryState.pushState(document.title, this.href);
                ev.stopEvent();
            }, els[i], { stopEvent: true });
        }
    }

    Ext.query('.kwfLightbox').each(function(el) {
        if (el.kwfLightbox) return;
        var lightboxEl = Ext.get(el);
        var options = Ext.decode(lightboxEl.child('input.options').dom.value);
        var l = new Kwf.EyeCandy.Lightbox.Lightbox(window.location.href, options);
        Kwf.Utils.HistoryState.currentState.lightbox = window.location.href;
        Kwf.Utils.HistoryState.replaceState(document.title, window.location.href);
        lightboxEl.enableDisplayMode('block');
        l.lightboxEl = lightboxEl;
        l.innerLightboxEl = lightboxEl.down('.kwfLightboxInner');
        l.fetched = true;
        l.initialize();
        l.closeHref = window.location.href.substr(0, window.location.href.lastIndexOf('/'));
        l.contentEl = l.innerLightboxEl.down('.kwfLightboxContent');
        l.style.afterCreateLightboxEl();
        l.style.onShow();
        l.style.onContentReady();
        el.kwfLightbox = l;
        Kwf.EyeCandy.Lightbox.currentOpen = l;
    });

    readyEl = Ext.get(readyEl);
    if (readyEl.isVisible() && Kwf.EyeCandy.Lightbox.currentOpen) {
        if (Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl
            && Kwf.EyeCandy.Lightbox.currentOpen.lightboxEl.isVisible()
            && (Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl.contains(readyEl)
            || readyEl.contains(Kwf.EyeCandy.Lightbox.currentOpen.innerLightboxEl))
        ) {
            Kwf.EyeCandy.Lightbox.currentOpen.style.onContentReady();
        }
    }
});

Kwf.Utils.HistoryState.on('popstate', function() {
    var lightbox = Kwf.Utils.HistoryState.currentState.lightbox;
    if (lightbox) {
        if (!Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) return;
        if (Kwf.EyeCandy.Lightbox.currentOpen != Kwf.EyeCandy.Lightbox.allByUrl[lightbox]) {
            Kwf.EyeCandy.Lightbox.allByUrl[lightbox].show();
        }
    } else {
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            Kwf.EyeCandy.Lightbox.currentOpen.close();
        }
    }
});

Ext.ns('Kwf.EyeCandy.Lightbox');
Kwf.EyeCandy.Lightbox.currentOpen = null;
Kwf.EyeCandy.Lightbox.allByUrl = {};
Kwf.EyeCandy.Lightbox.Lightbox = function(href, options) {
    this.href = href;
    Kwf.EyeCandy.Lightbox.allByUrl[href] = this;
    this.options = options;
    if (options.style) {
        this.style = new Kwf.EyeCandy.Lightbox.Styles[options.style](this);
    } else {
        this.style = new Kwf.EyeCandy.Lightbox.Styles.CenterBox(this);
    }
};
Kwf.EyeCandy.Lightbox.Lightbox.prototype = {
    fetched: false,
    _blockOnContentReady: false,
    createLightboxEl: function()
    {
        if (this.lightboxEl) return;

        var lightbox = Ext.getBody().createChild({
            cls: 'kwfLightbox' + (this.options.style ? ' kwfLightbox'+this.options.style : ''),
            html: '

'
        });
        lightbox.dom.kwfLightbox = this; //don't initialize again in onContentReady
        lightbox.enableDisplayMode('block');
        this.lightboxEl = lightbox;
        this.innerLightboxEl = lightbox.down('.kwfLightboxInner');

        var el = this.innerLightboxEl;

        if (this.options.width) {
            el.setWidth(parseInt(this.options.width) + el.getBorderWidth("lr") + el.getPadding("lr"));
        }
        if (this.options.height) {
            el.setHeight(parseInt(this.options.height) + el.getBorderWidth("tb") + el.getPadding("tb"));
        }
        this.style.afterCreateLightboxEl();
        this.lightboxEl.hide();
    },
    fetchContent: function()
    {
        if (this.fetched) return;
        this.fetched = true;

        var url = '/kwf/util/kwc/render';
        if (Kwf.Debug.rootFilename) url = Kwf.Debug.rootFilename + url;
        Ext.Ajax.request({
            params: { url: this.href },
            url: url,
            success: function(response, options) {
                this.contentEl = this.innerLightboxEl.createChild({
                    cls: 'kwfLightboxContent'
                });

                this.style.updateContent(response.responseText);

                if (this.lightboxEl.isVisible()) this.contentEl.hide();

                var showContent = function() {
                    this.innerLightboxEl.removeClass('kwfLightboxLoading');
                    this.innerLightboxEl.child('.loading').remove();
                    if (this.lightboxEl.isVisible()) {
                        this.contentEl.fadeIn();
                    }
                    this._blockOnContentReady = true; //don't resize twice
                    Kwf.callOnContentReady(this.contentEl.dom, {newRender: true});
                    this._blockOnContentReady = false;
                    this.style.afterContentShown();
                    if (this.lightboxEl.isVisible()) {
                        this.preloadLinks();
                    }
                };
                var imagesToLoad = 0;
                this.contentEl.query('img.hideWhileLoading').each(function(imgEl) {
                    imagesToLoad++;
                    imgEl.onload = (function() {
                        imagesToLoad--;
                        if (imagesToLoad <= 0) showContent.call(this);
                    }).createDelegate(this);
                }, this);
                if (imagesToLoad == 0) showContent.call(this);
                this.initialize();
            },
            failure: function() {
                //fallback
                location.href = this.href;
            },
            scope: this
        });
    },
    show: function(options)
    {
        this.createLightboxEl();
        this.style.onShow(options);

        if (!this.closeHref) {
            if (Kwf.EyeCandy.Lightbox.currentOpen) {
                this.closeHref = Kwf.EyeCandy.Lightbox.currentOpen.closeHref;
            } else {
                this.closeHref = window.location.href;
            }
        }
        if (Kwf.EyeCandy.Lightbox.currentOpen) {
            var closeOptions = {};
            if (options.clickTarget) closeOptions.showClickTarget = options.clickTarget;
            Kwf.EyeCandy.Lightbox.currentOpen.close(closeOptions);
        }
        Kwf.EyeCandy.Lightbox.currentOpen = this;

        this.lightboxEl.addClass('kwfLightboxOpen');
        if (this.fetched) {
            if (!this.lightboxEl.isVisible()) {
                this.lightboxEl.fadeIn();
                this.preloadLinks();
                Kwf.callOnContentReady(this.innerLightboxEl.dom, {newRender: false});
            }
            this.style.afterContentShown();
        } else {
            this.lightboxEl.show();
            this.fetchContent();
        }
        this.style.afterShow(options);
        Kwf.Statistics.count(this.href);
    },
    close: function(options) {
        this.lightboxEl.hide();
        //so eg. flash component can remove object
        Kwf.callOnContentReady(this.lightboxEl, {newRender: false});
        this.lightboxEl.show();

        this.style.onClose(options);
        this.lightboxEl.removeClass('kwfLightboxOpen');
        Kwf.EyeCandy.Lightbox.currentOpen = null;
    },
    closeAndPushState: function() {
        delete Kwf.Utils.HistoryState.currentState.lightbox;
        Kwf.Utils.HistoryState.pushState(document.title, this.closeHref);
        this.close();
    },
    initialize: function()
    {
        var closeButton = this.innerLightboxEl.child('.closeButton');
        if (closeButton) {
            closeButton.on('click', function(ev) {
                this.closeAndPushState();
                ev.stopEvent();
            }, this);
        }
    },
    preloadLinks: function() {
        this.innerLightboxEl.query('a.preload').each(function(el) {
            if (el.kwfLightbox) el.kwfLightbox.preload();
        }, this);
    },
    preload: function() {
        this.createLightboxEl();
        this.fetchContent();
    }
};

Kwf.EyeCandy.Lightbox.Styles = {};
Kwf.EyeCandy.Lightbox.Styles.Abstract = function(lightbox) {
    this.lightbox = lightbox;
};
Kwf.EyeCandy.Lightbox.Styles.Abstract.masks = 0;
Kwf.EyeCandy.Lightbox.Styles.Abstract.prototype = {
    afterCreateLightboxEl: Ext.emptyFn,
    afterContentShown: Ext.emptyFn,
    updateContent: function(responseText) {
        this.lightbox.contentEl.update(responseText);
    },
    onShow: Ext.emptyFn,
    afterShow: Ext.emptyFn,
    onClose: Ext.emptyFn,
    afterClose: Ext.emptyFn,
    onContentReady: Ext.emptyFn,

    mask: function() {
        //calling mask multiple times in valid, unmask must be called exactly often
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks++;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 1) return;
        Ext.getBody().addClass('kwfLightboxTheaterMode');
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        Ext.getBody().removeClass('x-masked-relative');
        maskEl.addClass('lightboxMask');
        maskEl.dom.style.height = '';
        maskEl.dom.style.width = '';

        //maskEl.setHeight(Math.max(Ext.lib.Dom.getViewHeight(), Ext.lib.Dom.getDocumentHeight()));

        maskEl.on('click', function() {
            this.lightbox.closeAndPushState();
        }, this);
    },
    unmask: function() {
        Kwf.EyeCandy.Lightbox.Styles.Abstract.masks--;
        if (Kwf.EyeCandy.Lightbox.Styles.Abstract.masks > 0) return;
        Ext.getBody()._mask.fadeOut({
            concurrent: true,
            callback: function() {
                Ext.getBody().removeClass('kwfLightboxTheaterMode');
                Ext.getBody()._mask.remove();
            },
            scope: this
        });
    }
};

Kwf.EyeCandy.Lightbox.Styles.CenterBox = Ext.extend(Kwf.EyeCandy.Lightbox.Styles.Abstract, {
    afterCreateLightboxEl: function() {
        this.lightbox.lightboxEl.on('click', function(ev) {
            if (ev.getTarget() == this.lightbox.lightboxEl.dom) {
                this.lightbox.closeAndPushState();
            }
        }, this);
        this._center();
    },
    afterContentShown: function() {
        this._center();
    },
    updateContent: function(responseText) {
        var isVisible = this.lightbox.lightboxEl.isVisible();

        this.lightbox.lightboxEl.show(); //to mesaure

        var originalSize = this.lightbox.innerLightboxEl.getSize();

        Kwf.EyeCandy.Lightbox.Styles.CenterBox.superclass.updateContent.apply(this, arguments);

        if (!this.lightbox.options.height) this.lightbox.innerLightboxEl.dom.style.height = '';
        if (!this.lightbox.options.width) this.lightbox.innerLightboxEl.dom.style.width = '';
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");

        if (isVisible) {
            this.lightbox.innerLightboxEl.setSize(newSize);
            if (this.lightbox.innerLightboxEl.getColor('backgroundColor')) {
                //animate size only if backgroundColor is set - else it doesn't make sense
                this._center(true);
                this.lightbox.innerLightboxEl.setSize(originalSize);
                this.lightbox.innerLightboxEl.setSize(newSize, null, true);
            } else {
                this._center(false);
            }
        } else {
            this.lightbox.innerLightboxEl.setSize(newSize);
            this._center(false);
            this.lightbox.lightboxEl.hide();
        }
    },
    onShow: function() {
        this.mask();
    },
    onClose: function(options) {
        this.lightboxEl.fadeOut({
            concurrent: true,
            callback: function() {
                this.afterClose();
            },
            scope: this
        });
        this.unmask();
    },
    _getCenterXy: function() {
        var xy = this.lightbox.innerLightboxEl.getAlignToXY(document, 'c-c');
        if (xy[1] < 20) xy[1] = 20;
        return xy;
    },
    _center: function(anim) {
        if (!this.lightbox.lightboxEl.isVisible(true)) return;
        this.lightbox.innerLightboxEl.setXY(this._getCenterXy(), anim);
    },

    onContentReady: function()
    {
        if (this.lightbox._blockOnContentReady) return;
        if (!this.lightbox.contentEl) return;

        //adjust size if height changed
        var newSize = this.lightbox.contentEl.getSize();
        newSize['height'] += this.lightbox.innerLightboxEl.getBorderWidth("tb")+this.lightbox.innerLightboxEl.getPadding("tb");
        newSize['width'] += this.lightbox.innerLightboxEl.getBorderWidth("lr")+this.lightbox.innerLightboxEl.getPadding("lr");
        if (this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter')) {
            newSize['height'] -= this.lightbox.contentEl.child('> .kwfRoundBorderBox > .kwfMiddleCenter').getPadding('tb');
        }
        var originalSize = this.lightbox.innerLightboxEl.getSize();
        this.lightbox.innerLightboxEl.setSize(newSize); //set to new size so centering works (no animation)
        var centerXy = this._getCenterXy();
        var xy = this.lightbox.innerLightboxEl.getXY();
        xy[0] = centerXy[0];
        if (centerXy[1] < xy[1]) xy[1] = centerXy[1]; //move up, but not down
        this.lightbox.innerLightboxEl.setXY(xy, true);
        this.lightbox.innerLightboxEl.setSize(originalSize); //set back to previous size for animation
        this.lightbox.innerLightboxEl.setSize(newSize, null, true); //now animate to new size
    }
});
<|endoftext|>


<commit_before>var assert = require('assert')
var shared_mime = require('..')

describe('Tests most from mime-types', function () {
  describe('.extensions(path)', function () {
    it('should return extensions for mime type', function () {
      assert.deepEqual(shared_mime.extensions('text/html'), ['html', 'htm'])
      assert.notDeepEqual(shared_mime.extensions('text/html'), ['html', 'htm', 'htmx'])
    })

    it('should return false for unknown type', function () {
      assert.strictEqual(shared_mime.extensions('application/x-bogus'), false)
    })

    it('should return false for non-type string', function () {
      assert.strictEqual(shared_mime.extensions('bogus'), false)
    })

    it('should return false for non-strings', function () {
      assert.strictEqual(shared_mime.extensions(null), false)
      assert.strictEqual(shared_mime.extensions(undefined), false)
      assert.strictEqual(shared_mime.extensions(42), false)
      assert.strictEqual(shared_mime.extensions({}), false)
    })

    // freedesktop specific
    it('should return extensions for extra freedesktop mime type', function(){
      assert.deepEqual(shared_mime.extensions('application/x-ruby'), ['rb'])
      assert.deepEqual(shared_mime.extensions('text/x-python'), ['py', 'pyx', 'wsgi'])
    })
  })

  describe('.lookup(extensions)', function () {
    it('should return mime type for ".html"', function () {
      assert.equal(shared_mime.lookup('.html'), 'text/html')
    })

    it('should return mime type for ".js"', function () {
      assert.equal(shared_mime.lookup('.js'), 'application/javascript')
    })

    it('should return mime type for ".json"', function () {
      assert.equal(shared_mime.lookup('.json'), 'application/json')
    })

    it('should return mime type for ".txt"', function () {
      assert.equal(shared_mime.lookup('.txt'), 'text/plain')
    })

    it('should return mime type for ".xml"', function () {
      assert.equal(shared_mime.lookup('.xml'), 'application/xml')
    })

    it('should be case insensitive', function () {
      assert.equal(shared_mime.lookup('.HTML'), 'text/html')
      assert.equal(shared_mime.lookup('.Xml'), 'application/xml')
    })

    it('should return false for unknown extensions', function () {
      assert.strictEqual(shared_mime.lookup('.bogus'), false)
      assert.strictEqual(shared_mime.lookup('bogus'), false)
    })

    it('should return false for non-strings', function () {
      assert.strictEqual(shared_mime.lookup(null), false)
      assert.strictEqual(shared_mime.lookup(undefined), false)
      assert.strictEqual(shared_mime.lookup(42), false)
      assert.strictEqual(shared_mime.lookup({}), false)
    })

    // freedesktop specifics
    it('should return mime type for real directory', function(){
      assert.equal(shared_mime.lookup('.'), "inode/directory")
      assert.equal(shared_mime.lookup('/home'), "inode/directory")
    })

    it('should return false for non-existent directory', function(){
      assert.strictEqual(shared_mime.lookup('bogus_directory'), false)
    })

    it('should return mime type for directory-like string', function(){
      assert.equal(shared_mime.lookup('bogus_directory/'), "inode/directory")
    })

    // WARNING: this has changed from mime-types
    it('should NOT work without the leading dot, case-insensitive', function () {
      assert.equal(shared_mime.lookup('html'), false)
      assert.equal(shared_mime.lookup('xml'), false)
      assert.equal(shared_mime.lookup('HTML'), false)
      assert.equal(shared_mime.lookup('XML'), false)
    })
  })

  describe('.lookup(path)', function () {
    it('should return mime type for file name', function () {
      assert.equal(shared_mime.lookup('page.html'), 'text/html')
    })

    it('should return mime type for relative path', function () {
      assert.equal(shared_mime.lookup('path/to/page.html'), 'text/html')
    })

    it('should return mime type for absolute path', function () {
      assert.equal(shared_mime.lookup('/path/to/page.html'), 'text/html')
    })

    it('should be case insensitive', function () {
      assert.equal(shared_mime.lookup('/path/to/PAGE.HTML'), 'text/html')
    })

    it('should return false for unknown extensions', function () {
      assert.strictEqual(shared_mime.lookup('/path/to/file.bogus'), false)
    })
  })
})

describe("Freedesktop Specifics:", function(){
  describe(".aliases", function(){
    it("should return aliases for mime type with aliases", function(){
      assert.deepEqual(shared_mime.aliases("video/vnd.mpegurl"), ["video/x-mpegurl"])
      assert.deepEqual(shared_mime.aliases("text/x-gettext-translation"),
                       ["text/x-po", "application/x-gettext"])
    })

    it("should return false for mime type with no aliases", function(){
      assert.strictEqual(shared_mime.aliases("text/cache-manifest"), false)
    })

    it("should return false for unknow type", function(){
      assert.strictEqual(shared_mime.aliases('application/x-bogus'), false)
    })
  })

  describe(".supertype", function(){
    it("should return supertype for mime type", function(){
      assert.equal(shared_mime.supertype("application/epub+zip"),
                   "application/zip")
      assert.equal(shared_mime.supertype("application/x-windows-themepack"),
                   "application/vnd.ms-cab-compressed")
      assert.equal(shared_mime.supertype("application/javascript"),
                   "application/ecmascript")
    })

    it("should return false for mime type without super type", function(){
      assert.strictEqual(shared_mime.supertype("text/plain"), false)
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.supertype('application/x-bogus'), false)
    })
  })

  describe(".comment", function(){
    it("should return comment for mime type", function(){
      assert.strictEqual(shared_mime.comment("application/javascript"),
                         "JavaScript program")
      assert.strictEqual(shared_mime.comment("application/x-jbuilder-project"),
                         "JBuilder project")
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.comment('application/x-bogus'), false)
    })
  })

  describe(".generic_icon", function(){
    it("should return generic icon if there is one", function(){
      assert.equal(shared_mime.generic_icon("application/rss+xml"),
                   "text-html")
    })

    it("should return false if there is no generic icon assigned", function(){
      assert.strictEqual(shared_mime.generic_icon("text/rfc822-headers"),
                         false)
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.generic_icon('application/x-bogus'),
                         false)
    })

  })
})
<commit_msg>Fix test.js indent level to 2<commit_after>// -*- js-indent-level: 2 -*-
var assert = require('assert')
var shared_mime = require('..')

describe('Tests most from mime-types', function () {
  describe('.extensions(path)', function () {
    it('should return extensions for mime type', function () {
      assert.deepEqual(shared_mime.extensions('text/html'), ['html', 'htm'])
      assert.notDeepEqual(shared_mime.extensions('text/html'), ['html', 'htm', 'htmx'])
    })

    it('should return false for unknown type', function () {
      assert.strictEqual(shared_mime.extensions('application/x-bogus'), false)
    })

    it('should return false for non-type string', function () {
      assert.strictEqual(shared_mime.extensions('bogus'), false)
    })

    it('should return false for non-strings', function () {
      assert.strictEqual(shared_mime.extensions(null), false)
      assert.strictEqual(shared_mime.extensions(undefined), false)
      assert.strictEqual(shared_mime.extensions(42), false)
      assert.strictEqual(shared_mime.extensions({}), false)
    })

    // freedesktop specific
    it('should return extensions for extra freedesktop mime type', function(){
      assert.deepEqual(shared_mime.extensions('application/x-ruby'), ['rb'])
      assert.deepEqual(shared_mime.extensions('text/x-python'), ['py', 'pyx', 'wsgi'])
    })
  })

  describe('.lookup(extensions)', function () {
    it('should return mime type for ".html"', function () {
      assert.equal(shared_mime.lookup('.html'), 'text/html')
    })

    it('should return mime type for ".js"', function () {
      assert.equal(shared_mime.lookup('.js'), 'application/javascript')
    })

    it('should return mime type for ".json"', function () {
      assert.equal(shared_mime.lookup('.json'), 'application/json')
    })

    it('should return mime type for ".txt"', function () {
      assert.equal(shared_mime.lookup('.txt'), 'text/plain')
    })

    it('should return mime type for ".xml"', function () {
      assert.equal(shared_mime.lookup('.xml'), 'application/xml')
    })

    it('should be case insensitive', function () {
      assert.equal(shared_mime.lookup('.HTML'), 'text/html')
      assert.equal(shared_mime.lookup('.Xml'), 'application/xml')
    })

    it('should return false for unknown extensions', function () {
      assert.strictEqual(shared_mime.lookup('.bogus'), false)
      assert.strictEqual(shared_mime.lookup('bogus'), false)
    })

    it('should return false for non-strings', function () {
      assert.strictEqual(shared_mime.lookup(null), false)
      assert.strictEqual(shared_mime.lookup(undefined), false)
      assert.strictEqual(shared_mime.lookup(42), false)
      assert.strictEqual(shared_mime.lookup({}), false)
    })

    // freedesktop specifics
    it('should return mime type for real directory', function(){
      assert.equal(shared_mime.lookup('.'), "inode/directory")
      assert.equal(shared_mime.lookup('/home'), "inode/directory")
    })

    it('should return false for non-existent directory', function(){
      assert.strictEqual(shared_mime.lookup('bogus_directory'), false)
    })

    it('should return mime type for directory-like string', function(){
      assert.equal(shared_mime.lookup('bogus_directory/'), "inode/directory")
    })

    // WARNING: this has changed from mime-types
    it('should NOT work without the leading dot, case-insensitive', function () {
      assert.equal(shared_mime.lookup('html'), false)
      assert.equal(shared_mime.lookup('xml'), false)
      assert.equal(shared_mime.lookup('HTML'), false)
      assert.equal(shared_mime.lookup('XML'), false)
    })
  })

  describe('.lookup(path)', function () {
    it('should return mime type for file name', function () {
      assert.equal(shared_mime.lookup('page.html'), 'text/html')
    })

    it('should return mime type for relative path', function () {
      assert.equal(shared_mime.lookup('path/to/page.html'), 'text/html')
    })

    it('should return mime type for absolute path', function () {
      assert.equal(shared_mime.lookup('/path/to/page.html'), 'text/html')
    })

    it('should be case insensitive', function () {
      assert.equal(shared_mime.lookup('/path/to/PAGE.HTML'), 'text/html')
    })

    it('should return false for unknown extensions', function () {
      assert.strictEqual(shared_mime.lookup('/path/to/file.bogus'), false)
    })
  })
})

describe("Freedesktop Specifics:", function(){
  describe(".aliases", function(){
    it("should return aliases for mime type with aliases", function(){
      assert.deepEqual(shared_mime.aliases("video/vnd.mpegurl"), ["video/x-mpegurl"])
      assert.deepEqual(shared_mime.aliases("text/x-gettext-translation"),
                       ["text/x-po", "application/x-gettext"])
    })

    it("should return false for mime type with no aliases", function(){
      assert.strictEqual(shared_mime.aliases("text/cache-manifest"), false)
    })

    it("should return false for unknow type", function(){
      assert.strictEqual(shared_mime.aliases('application/x-bogus'), false)
    })
  })

  describe(".supertype", function(){
    it("should return supertype for mime type", function(){
      assert.equal(shared_mime.supertype("application/epub+zip"),
                   "application/zip")
      assert.equal(shared_mime.supertype("application/x-windows-themepack"),
                   "application/vnd.ms-cab-compressed")
      assert.equal(shared_mime.supertype("application/javascript"),
                   "application/ecmascript")
    })

    it("should return false for mime type without super type", function(){
      assert.strictEqual(shared_mime.supertype("text/plain"), false)
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.supertype('application/x-bogus'), false)
    })
  })

  describe(".comment", function(){
    it("should return comment for mime type", function(){
      assert.strictEqual(shared_mime.comment("application/javascript"),
                         "JavaScript program")
      assert.strictEqual(shared_mime.comment("application/x-jbuilder-project"),
                         "JBuilder project")
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.comment('application/x-bogus'), false)
    })
  })

  describe(".generic_icon", function(){
    it("should return generic icon if there is one", function(){
      assert.equal(shared_mime.generic_icon("application/rss+xml"),
                   "text-html")
    })

    it("should return false if there is no generic icon assigned", function(){
      assert.strictEqual(shared_mime.generic_icon("text/rfc822-headers"),
                         false)
    })

    it("should return false for unknown type", function(){
      assert.strictEqual(shared_mime.generic_icon('application/x-bogus'),
                         false)
    })

  })
})
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var _ = require('lodash');
_.mixin(require("lodash-deep"));
var path = require('path');
var serve_static = require('serve-static');
var cacheTimes = require('../../web/config/cache-times');

module.exports = function (options) {
  var seneca = this;
  var plugin = 'dojos';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({ role: plugin, spec: 'web' }, spec_web);

  seneca.add({role: plugin, cmd: 'search'}, proxy);
  seneca.add({role: plugin, cmd: 'load'}, proxy);
  seneca.add({role: plugin, cmd: 'find'}, proxy);
  seneca.add({role: plugin, cmd: 'list'}, proxy);
  seneca.add({role: plugin, cmd: 'create'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'update'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'delete'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'my_dojos'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'dojos_count'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_by_country'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_state_count'}, proxy);
  seneca.add({role: plugin, cmd: 'bulk_update'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'bulk_delete'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'get_stats'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'save_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'update_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_user_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_setup_dojo_steps'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'search_dojo_leads'}, proxy);
  seneca.add({role: plugin, cmd: 'uncompleted_dojos'}, proxy);
  seneca.add({role: plugin, cmd: 'load_dojo_users'}, proxy);
  seneca.add({role: plugin, cmd: 'send_email'}, proxy);
  seneca.add({role: plugin, cmd: 'generate_user_invite_token'}, proxy);
  seneca.add({role: plugin, cmd: 'accept_user_invite'}, proxy);
  seneca.add({role: plugin, cmd: 'request_user_invite'}, proxy);
  seneca.add({role: plugin, cmd: 'accept_user_request'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'save_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'remove_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'get_user_permissions'}, proxy);
  seneca.add({role: plugin, cmd: 'get_user_types'}, proxy);
  seneca.add({role: plugin, cmd: 'get_dojo_config'}, proxy);
  seneca.add({role: plugin, cmd: 'update_founder'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'search_nearest_dojos'}, proxy);
  seneca.add({role: plugin, cmd: 'search_bounding_box'}, proxy);
  // from countries service
  seneca.add({role: plugin, cmd: 'countries_continents'}, proxy);
  seneca.add({role: plugin, cmd: 'list_countries'}, proxy);
  seneca.add({role: plugin, cmd: 'list_places'}, proxy);
  seneca.add({role: plugin, cmd: 'countries_lat_long'}, proxy);
  seneca.add({role: plugin, cmd: 'continents_lat_long'}, proxy);
  seneca.add({role: plugin, cmd: 'continent_codes'}, proxy);

  function proxy(args, done) {
    var user = null;
    var zenHostname = args.req$.headers.host || '127.0.0.1:8000';
    var reqId = args.req$.headers['X-REQ-ID'];

    var locality = (args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$.headers['accept-language'];
    if(!locality) locality = 'en_US';
    locality = formatLocaleCode(locality);
    if(args.req$.seneca.user) user = args.req$.seneca.user;
    args.reqId = reqId;

    seneca.act(seneca.util.argprops(
      {user:user, reqId: reqId, zenHostname: zenHostname, locality: locality, fatal$: false},
      args,
      {role:'cd-dojos'}
    ), done);
  }

  function proxyNeedUser(args, done) {
    // TODO - how to set response code of 400 here??
    if(!_.deepHas(args.req$, 'user.user')) return done(new Error('Not logged in, please log in first.'));
    return proxy(args, done);
  }

  function spec_web(args, done) {
    var public_folder = path.join(__dirname, 'public');

    done(null, {
      name: 'dojos',
      public: public_folder
    });
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  seneca.add({ init: plugin }, function (args, done) {
    var seneca = this;

    seneca.act({ role: plugin, spec: 'web' }, function (err, spec) {
      if (err) { return done(err); }

      var serve = serve_static(spec.public);
      var prefix = '/content/' + spec.name;

      seneca.act({ role: 'web', use: function (req, res, next) {
        var origurl = req.url;
        if (0 === origurl.indexOf(prefix)) {
          req.url = origurl.substring(prefix.length);
          serve(req, res, function () {
            req.url = origurl;
            next();
          });
        } else {
          return next();
        }
      }});

      done();
    });
  });

  // web interface
  seneca.act({ role: 'web', use: {
    prefix: options.prefix + version + '/',
    pin: { role: plugin, cmd: '*' },
    map: {
      'search': {POST: true, alias: 'dojos/search'},
      'create': {POST: true, alias: 'dojo_create'},
      'update': {PUT: true,  alias: 'dojos/:id'},
      'delete': {DELETE: true, alias: 'dojos/:id'},
      'list'  : {POST: true, alias: 'dojos'},
      'load'  : {GET: true, alias: 'dojos/:id'},
      'find'  : {POST: true, alias: 'dojos/find'},
      'my_dojos': {POST: true, alias: 'dojos/my_dojos'},
      'dojos_count': {GET: true, alias: 'dojos_count'},
      'dojos_by_country': {POST: true, alias:'dojos_by_country'},
      'dojos_state_count': {GET: true, alias: 'dojos_state_count/:country'},
      'bulk_update': {POST: true, alias: 'dojos/bulk_update'},
      'bulk_delete': {POST: true, alias: 'dojos/bulk_delete'},
      'get_stats': {POST: true, alias: 'dojos/stats'},
      'save_dojo_lead': {POST: true, alias: 'dojos/save_dojo_lead'},
      'update_dojo_lead': {PUT: true, alias: 'dojos/update_dojo_lead/:id'},
      'load_user_dojo_lead': {GET: true, alias: 'dojos/user_dojo_lead/:id'},
      'load_dojo_lead': {GET: true, alias: 'dojos/dojo_lead/:id'},
      'load_setup_dojo_steps': {GET: true, alias: 'load_setup_dojo_steps'},
      'load_usersdojos': {POST: true, alias: 'dojos/users'},
      'search_dojo_leads': {POST: true, alias: 'dojos/search_dojo_leads'},
      'uncompleted_dojos': {GET: true, alias: 'uncompleted_dojos'},
      'load_dojo_users': {POST: true, alias: 'dojos/load_dojo_users'},
      'generate_user_invite_token': {POST: true, alias: 'dojos/generate_user_invite_token'},
      'accept_user_invite': {POST: true, alias: 'dojos/accept_user_invite'},
      'request_user_invite': {POST: true, alias: 'dojos/request_user_invite'},
      'accept_user_request': {POST: true, alias: 'dojos/accept_user_request'},
      'dojos_for_user': {GET:true, alias: 'dojos/dojos_for_user/:id'},
      'save_usersdojos': {POST: true, alias: 'dojos/save_usersdojos'},
      'remove_usersdojos': {POST: true, alias: 'dojos/remove_usersdojos/:userId/:dojoId'},
      'get_user_permissions': {GET:true, alias: 'get_user_permissions'},
      'get_user_types': {GET: true, alias: 'get_user_types'},
      'get_dojo_config': {GET: true, alias: 'get_dojo_config'},
      'update_founder': {POST: true, alias: 'update_founder'},
      'search_nearest_dojos': {POST: true, alias: 'dojos/search_nearest_dojos'},
      'search_bounding_box': {POST: true, alias: 'dojos/search_bounding_box'},
      'list_countries': {GET: true, alias: 'countries', expiresIn: cacheTimes.long },
      'list_places': {POST: true, alias: 'places'},
      'continents_lat_long': {GET: true, alias: 'continents_lat_long', expiresIn: cacheTimes.long },
      'countries_lat_long': {GET: true, alias: 'countries_lat_long', expiresIn: cacheTimes.long },
      'continent_codes': {GET: true, alias: 'continent_codes', expiresIn: cacheTimes.long },
      'countries_continents': {GET: true, alias: 'countries_continents', expiresIn: cacheTimes.long }
    }
  }});

  return {
    name: plugin
  };

}
<commit_msg>Removed unnecessary TODO<commit_after>'use strict';

var util = require('util');
var _ = require('lodash');
_.mixin(require("lodash-deep"));
var path = require('path');
var serve_static = require('serve-static');
var cacheTimes = require('../../web/config/cache-times');

module.exports = function (options) {
  var seneca = this;
  var plugin = 'dojos';
  var version = '1.0';

  options = seneca.util.deepextend({
    prefix: '/api/'
  }, options);

  seneca.add({ role: plugin, spec: 'web' }, spec_web);

  seneca.add({role: plugin, cmd: 'search'}, proxy);
  seneca.add({role: plugin, cmd: 'load'}, proxy);
  seneca.add({role: plugin, cmd: 'find'}, proxy);
  seneca.add({role: plugin, cmd: 'list'}, proxy);
  seneca.add({role: plugin, cmd: 'create'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'update'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'delete'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'my_dojos'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'dojos_count'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_by_country'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_state_count'}, proxy);
  seneca.add({role: plugin, cmd: 'bulk_update'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'bulk_delete'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'get_stats'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'save_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'update_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_user_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_dojo_lead'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_setup_dojo_steps'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'load_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'search_dojo_leads'}, proxy);
  seneca.add({role: plugin, cmd: 'uncompleted_dojos'}, proxy);
  seneca.add({role: plugin, cmd: 'load_dojo_users'}, proxy);
  seneca.add({role: plugin, cmd: 'send_email'}, proxy);
  seneca.add({role: plugin, cmd: 'generate_user_invite_token'}, proxy);
  seneca.add({role: plugin, cmd: 'accept_user_invite'}, proxy);
  seneca.add({role: plugin, cmd: 'request_user_invite'}, proxy);
  seneca.add({role: plugin, cmd: 'accept_user_request'}, proxy);
  seneca.add({role: plugin, cmd: 'dojos_for_user'}, proxy);
  seneca.add({role: plugin, cmd: 'save_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'remove_usersdojos'}, proxy);
  seneca.add({role: plugin, cmd: 'get_user_permissions'}, proxy);
  seneca.add({role: plugin, cmd: 'get_user_types'}, proxy);
  seneca.add({role: plugin, cmd: 'get_dojo_config'}, proxy);
  seneca.add({role: plugin, cmd: 'update_founder'}, proxyNeedUser);
  seneca.add({role: plugin, cmd: 'search_nearest_dojos'}, proxy);
  seneca.add({role: plugin, cmd: 'search_bounding_box'}, proxy);
  // from countries service
  seneca.add({role: plugin, cmd: 'countries_continents'}, proxy);
  seneca.add({role: plugin, cmd: 'list_countries'}, proxy);
  seneca.add({role: plugin, cmd: 'list_places'}, proxy);
  seneca.add({role: plugin, cmd: 'countries_lat_long'}, proxy);
  seneca.add({role: plugin, cmd: 'continents_lat_long'}, proxy);
  seneca.add({role: plugin, cmd: 'continent_codes'}, proxy);

  function proxy(args, done) {
    var user = null;
    var zenHostname = args.req$.headers.host || '127.0.0.1:8000';
    var reqId = args.req$.headers['X-REQ-ID'];

    var locality = (args.req$.cookies.NG_TRANSLATE_LANG_KEY && args.req$.cookies.NG_TRANSLATE_LANG_KEY.replace(/\"/g, '')) || args.req$.headers['accept-language'];
    if(!locality) locality = 'en_US';
    locality = formatLocaleCode(locality);
    if(args.req$.seneca.user) user = args.req$.seneca.user;
    args.reqId = reqId;

    seneca.act(seneca.util.argprops(
      {user:user, reqId: reqId, zenHostname: zenHostname, locality: locality, fatal$: false},
      args,
      {role:'cd-dojos'}
    ), done);
  }

  function proxyNeedUser(args, done) {
    if(!_.deepHas(args.req$, 'user.user')) return done(new Error('Not logged in, please log in first.'));
    return proxy(args, done);
  }

  function spec_web(args, done) {
    var public_folder = path.join(__dirname, 'public');

    done(null, {
      name: 'dojos',
      public: public_folder
    });
  }

  function formatLocaleCode(code) {
    return code.slice(0, 3) + code.charAt(3).toUpperCase() + code.charAt(4).toUpperCase();
  }

  seneca.add({ init: plugin }, function (args, done) {
    var seneca = this;

    seneca.act({ role: plugin, spec: 'web' }, function (err, spec) {
      if (err) { return done(err); }

      var serve = serve_static(spec.public);
      var prefix = '/content/' + spec.name;

      seneca.act({ role: 'web', use: function (req, res, next) {
        var origurl = req.url;
        if (0 === origurl.indexOf(prefix)) {
          req.url = origurl.substring(prefix.length);
          serve(req, res, function () {
            req.url = origurl;
            next();
          });
        } else {
          return next();
        }
      }});

      done();
    });
  });

  // web interface
  seneca.act({ role: 'web', use: {
    prefix: options.prefix + version + '/',
    pin: { role: plugin, cmd: '*' },
    map: {
      'search': {POST: true, alias: 'dojos/search'},
      'create': {POST: true, alias: 'dojo_create'},
      'update': {PUT: true,  alias: 'dojos/:id'},
      'delete': {DELETE: true, alias: 'dojos/:id'},
      'list'  : {POST: true, alias: 'dojos'},
      'load'  : {GET: true, alias: 'dojos/:id'},
      'find'  : {POST: true, alias: 'dojos/find'},
      'my_dojos': {POST: true, alias: 'dojos/my_dojos'},
      'dojos_count': {GET: true, alias: 'dojos_count'},
      'dojos_by_country': {POST: true, alias:'dojos_by_country'},
      'dojos_state_count': {GET: true, alias: 'dojos_state_count/:country'},
      'bulk_update': {POST: true, alias: 'dojos/bulk_update'},
      'bulk_delete': {POST: true, alias: 'dojos/bulk_delete'},
      'get_stats': {POST: true, alias: 'dojos/stats'},
      'save_dojo_lead': {POST: true, alias: 'dojos/save_dojo_lead'},
      'update_dojo_lead': {PUT: true, alias: 'dojos/update_dojo_lead/:id'},
      'load_user_dojo_lead': {GET: true, alias: 'dojos/user_dojo_lead/:id'},
      'load_dojo_lead': {GET: true, alias: 'dojos/dojo_lead/:id'},
      'load_setup_dojo_steps': {GET: true, alias: 'load_setup_dojo_steps'},
      'load_usersdojos': {POST: true, alias: 'dojos/users'},
      'search_dojo_leads': {POST: true, alias: 'dojos/search_dojo_leads'},
      'uncompleted_dojos': {GET: true, alias: 'uncompleted_dojos'},
      'load_dojo_users': {POST: true, alias: 'dojos/load_dojo_users'},
      'generate_user_invite_token': {POST: true, alias: 'dojos/generate_user_invite_token'},
      'accept_user_invite': {POST: true, alias: 'dojos/accept_user_invite'},
      'request_user_invite': {POST: true, alias: 'dojos/request_user_invite'},
      'accept_user_request': {POST: true, alias: 'dojos/accept_user_request'},
      'dojos_for_user': {GET:true, alias: 'dojos/dojos_for_user/:id'},
      'save_usersdojos': {POST: true, alias: 'dojos/save_usersdojos'},
      'remove_usersdojos': {POST: true, alias: 'dojos/remove_usersdojos/:userId/:dojoId'},
      'get_user_permissions': {GET:true, alias: 'get_user_permissions'},
      'get_user_types': {GET: true, alias: 'get_user_types'},
      'get_dojo_config': {GET: true, alias: 'get_dojo_config'},
      'update_founder': {POST: true, alias: 'update_founder'},
      'search_nearest_dojos': {POST: true, alias: 'dojos/search_nearest_dojos'},
      'search_bounding_box': {POST: true, alias: 'dojos/search_bounding_box'},
      'list_countries': {GET: true, alias: 'countries', expiresIn: cacheTimes.long },
      'list_places': {POST: true, alias: 'places'},
      'continents_lat_long': {GET: true, alias: 'continents_lat_long', expiresIn: cacheTimes.long },
      'countries_lat_long': {GET: true, alias: 'countries_lat_long', expiresIn: cacheTimes.long },
      'continent_codes': {GET: true, alias: 'continent_codes', expiresIn: cacheTimes.long },
      'countries_continents': {GET: true, alias: 'countries_continents', expiresIn: cacheTimes.long }
    }
  }});

  return {
    name: plugin
  };

}
<|endoftext|>


<commit_before>"use strict";
var now = Date.now();
var util = require('util');
var fs = require('fs');
var assert = require('assert')
var fileDir = __dirname+'/filekv_test_data_folder_'+now;
var fkvObj = require('../index.js').create({
	fileDir:fileDir,
	workMax:1000
});

assert.equal(typeof fkvObj,'object');
assert.notEqual(fkvObj,null);
assert.notEqual(fkvObj,undefined);

var value = 'filekv test string';

//test set, and, get
fkvObj.set('testkey',value,function(err){
	fkvObj.get('testkey',function(err,data,info){
		util.error(err);
		util.error(data);
		util.error(info);
		assert.equal(typeof data,'string');
		assert.equal(data,value);

	})
})

//test set, delete, get
fkvObj.set('testkey2',value,function(err){
	fkvObj.del('testkey2',function(){
		fkvObj.get('testkey2',function(err,data){

			assert.equal(!!data,false);
			assert.notEqual(data,value);

		})
	});
})

//test key life time
fkvObj.set('testkey3',value,5,function(){
	fkvObj.get('testkey3',function(err,data){
		assert.equal(value,data);
		assert.equal(typeof value,typeof data);

	})
	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.equal(value,data);
			assert.equal(typeof value,typeof data);

		})
	},3e3);

	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.notEqual(value,data);
			assert.notEqual(typeof value,typeof data);
			assert.equal(!!data,false);

		})
	},5e3);

	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.notEqual(value,data);
			assert.notEqual(typeof value,typeof data);
			assert.equal(!!data,false);
		})
	},7e3);
})

//test add function
fkvObj.set('testkey4',value,function(){
	fkvObj.add('testkey4',value,function(err){
		assert.equal(err instanceof Error,true);
	})
	fkvObj.add('testkey4-2',value,function(err){
		assert.equal(err,null);
	})

});

//test replace function
fkvObj.set('testkey5',value,function(){
	fkvObj.replace('testkey5',value,function(err){
		util.error(err);
		assert.equal(err,null);
	})
	fkvObj.replace('testkey5-2',value,function(err){
		assert.equal(err instanceof Error,true);
	})

});

/*
 * lib md5 testing
 */
var _md5 = require('../lib/crypto.js').md5;
assert.equal(_md5('123').toUpperCase(),'202cb962ac59075b964b07152d234b70'.toUpperCase());
assert.equal(_md5('filekv').toUpperCase(),'ec9310957ee4cedd23ce617051c58ea3'.toUpperCase());
assert.equal(_md5('中文').toUpperCase(),'a7bac2239fcdcb3a067903d8077c4a07'.toUpperCase());

/*
 * lib tool testing
 */
var tool = require('../lib/tool.js');
var nowMd5 = _md5(now);
assert.equal(tool.buildDataFileSubDir(nowMd5),nowMd5.substr(0,3)+'/'+nowMd5.substr(3,3));

/*
 * lib mkdirs testing
 */

var testDataFolder = fileDir+'/'+tool.buildDataFileSubDir(_md5(Date.now()));
util.error(testDataFolder);
var filekvFSTool = require('../lib/fs.js');
fs.unlink(testDataFolder,function(err){
	util.error(err);
	filekvFSTool.mkdirs(testDataFolder,function(err){
		util.error(err);
		fs.exists(testDataFolder,function(isExsts){
			assert.equal(isExsts,true);
		});
	});
});
<commit_msg>oh shit~<commit_after>"use strict";
var now = Date.now();
var util = require('util');
var fs = require('fs');
var assert = require('assert')
var fileDir = __dirname+'/filekv_test_data_folder_'+now;
var fkvObj = require('../index.js').create({
	fileDir:fileDir,
	workMax:1000
});

assert.equal(typeof fkvObj,'object');
assert.notEqual(fkvObj,null);
assert.notEqual(fkvObj,undefined);

var value = 'filekv test string';

//test set, and, get
fkvObj.set('testkey',value,function(err){
	fkvObj.get('testkey',function(err,data,info){

		assert.equal(typeof data,'string');
		assert.equal(data,value);

	})
})

//test set, delete, get
fkvObj.set('testkey2',value,function(err){
	fkvObj.del('testkey2',function(){
		fkvObj.get('testkey2',function(err,data){

			assert.equal(!!data,false);
			assert.notEqual(data,value);

		})
	});
})

//test key life time
fkvObj.set('testkey3',value,5,function(){
	fkvObj.get('testkey3',function(err,data,info){
		util.error(err);
		util.error(data);
		util.error(info);
		assert.equal(value,data);
		assert.equal(typeof value,typeof data);

	})
	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.equal(value,data);
			assert.equal(typeof value,typeof data);

		})
	},3e3);

	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.notEqual(value,data);
			assert.notEqual(typeof value,typeof data);
			assert.equal(!!data,false);

		})
	},5e3);

	setTimeout(function(){
		fkvObj.get('testkey3',function(err,data){
			assert.notEqual(value,data);
			assert.notEqual(typeof value,typeof data);
			assert.equal(!!data,false);
		})
	},7e3);
})

//test add function
fkvObj.set('testkey4',value,function(){
	fkvObj.add('testkey4',value,function(err){
		assert.equal(err instanceof Error,true);
	})
	fkvObj.add('testkey4-2',value,function(err){
		assert.equal(err,null);
	})

});

//test replace function
fkvObj.set('testkey5',value,function(){
	fkvObj.replace('testkey5',value,function(err){
		util.error(err);
		assert.equal(err,null);
	})
	fkvObj.replace('testkey5-2',value,function(err){
		assert.equal(err instanceof Error,true);
	})

});

/*
 * lib md5 testing
 */
var _md5 = require('../lib/crypto.js').md5;
assert.equal(_md5('123').toUpperCase(),'202cb962ac59075b964b07152d234b70'.toUpperCase());
assert.equal(_md5('filekv').toUpperCase(),'ec9310957ee4cedd23ce617051c58ea3'.toUpperCase());
assert.equal(_md5('中文').toUpperCase(),'a7bac2239fcdcb3a067903d8077c4a07'.toUpperCase());

/*
 * lib tool testing
 */
var tool = require('../lib/tool.js');
var nowMd5 = _md5(now);
assert.equal(tool.buildDataFileSubDir(nowMd5),nowMd5.substr(0,3)+'/'+nowMd5.substr(3,3));

/*
 * lib mkdirs testing
 */

var testDataFolder = fileDir+'/'+tool.buildDataFileSubDir(_md5(Date.now()));
util.error(testDataFolder);
var filekvFSTool = require('../lib/fs.js');
fs.unlink(testDataFolder,function(err){
	util.error(err);
	filekvFSTool.mkdirs(testDataFolder,function(err){
		util.error(err);
		fs.exists(testDataFolder,function(isExsts){
			assert.equal(isExsts,true);
		});
	});
});
<|endoftext|>


<commit_before>/**
 * Visual Blocks Editor
 *
 * Copyright 2014 Massachusetts Institute of Technology
 * http://zerorobotics.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating C++ for basic ZR API blocks.
 * @author dininno@mit.edu (Ethan DiNinno)
 */
'use strict';

Blockly.zr_cpp['zrms14_getDebrisLocation'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	var loc = Blockly.zr_cpp.valueToCode(block, 'loc',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.getDebrisLocation(' + debrisId + ', ' + loc + ');\n';
};

Blockly.zr_cpp['zrms14_haveDebris'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	return ['game.haveDebris(' + debrisId + ')', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_startLasso'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	return 'game.startLasso(' + debrisId + ');\n';
};

Blockly.zr_cpp['zrms14_havePack'] = {
	var player = block.getFieldValue('player');
	var objectNum = block.getFieldValue('objectNum');
	return ['game.havePack(' + player + ', ' + objectNum + ')', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_predictCometState'] = function() {
	var dtSteps = Blockly.zr_cpp.valueToCode(block, 'dtSteps',
			Blockly.zr_cpp.ORDER_NONE);
	var initState = Blockly.zr_cpp.valueToCode(block, 'initState',
			Blockly.zr_cpp.ORDER_NONE);
	var finalState = Blockly.zr_cpp.valueToCode(block, 'finalState',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.predictCometState(' + dtSteps + ', ' + initState + ', ' + finalState + ');\n';
};

Blockly.zr_cpp['zrms14_getCometState'] = function() {
	var state = Blockly.zr_cpp.valueToCode(block, 'state',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.getCometState(' + state + ');\n';
};

Blockly.zr_cpp['zrms14_faceTarget'] = function() {
	var target = Blockly.zr_cpp.valueToCode(block, 'target',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.faceTarget(' + target + ');\n';
};

Blockly.zr_cpp['zrms14_isFacingTarget'] = function() {
	return ['game.isFacingTarget()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_shootLaserBool'] = function() {
	return ['game.shootLaser()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_shootLaserVoid'] = function() {
	return 'game.shootLaser();\n';
};

Blockly.zr_cpp['zrms14_laserShotsRemaining'] = function() {
	return ['game.laserShotsRemaining()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getMass'] = function() {
	return ['game.getMass()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getFuelRemaining'] = function() {
	return ['game.getFuelRemaining()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getScore'] = function() {
	return ['game.getScore()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getOtherScore'] = function() {
	return ['game.getOtherScore()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_isSlowDownActive'] = function() {
	return ['game.isSlowDownActive()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_isBounceActive'] = function() {
	return ['game.isBounceActive()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};<commit_msg>Blocks for ZRMS14<commit_after>/**
 * Visual Blocks Editor
 *
 * Copyright 2014 Massachusetts Institute of Technology
 * http://zerorobotics.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Generating C++ for basic ZR API blocks.
 * @author dininno@mit.edu (Ethan DiNinno)
 */
'use strict';

Blockly.zr_cpp['zrms14_getDebrisLocation'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	var loc = Blockly.zr_cpp.valueToCode(block, 'loc',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.getDebrisLocation(' + debrisId + ', ' + loc + ');\n';
};

Blockly.zr_cpp['zrms14_haveDebris'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	return ['game.haveDebris(' + debrisId + ')', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_startLasso'] = function() {
	var debrisId = block.getFieldValue('debrisId');
	return 'game.startLasso(' + debrisId + ');\n';
};

Blockly.zr_cpp['zrms14_havePack'] = function() {
	var player = block.getFieldValue('player');
	var objectNum = block.getFieldValue('objectNum');
	return ['game.havePack(' + player + ', ' + objectNum + ')', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_predictCometState'] = function() {
	var dtSteps = Blockly.zr_cpp.valueToCode(block, 'dtSteps',
			Blockly.zr_cpp.ORDER_NONE);
	var initState = Blockly.zr_cpp.valueToCode(block, 'initState',
			Blockly.zr_cpp.ORDER_NONE);
	var finalState = Blockly.zr_cpp.valueToCode(block, 'finalState',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.predictCometState(' + dtSteps + ', ' + initState + ', ' + finalState + ');\n';
};

Blockly.zr_cpp['zrms14_getCometState'] = function() {
	var state = Blockly.zr_cpp.valueToCode(block, 'state',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.getCometState(' + state + ');\n';
};

Blockly.zr_cpp['zrms14_faceTarget'] = function() {
	var target = Blockly.zr_cpp.valueToCode(block, 'target',
			Blockly.zr_cpp.ORDER_NONE);
	return 'game.faceTarget(' + target + ');\n';
};

Blockly.zr_cpp['zrms14_isFacingTarget'] = function() {
	return ['game.isFacingTarget()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_shootLaserBool'] = function() {
	return ['game.shootLaser()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_shootLaserVoid'] = function() {
	return 'game.shootLaser();\n';
};

Blockly.zr_cpp['zrms14_laserShotsRemaining'] = function() {
	return ['game.laserShotsRemaining()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getMass'] = function() {
	return ['game.getMass()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getFuelRemaining'] = function() {
	return ['game.getFuelRemaining()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getScore'] = function() {
	return ['game.getScore()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_getOtherScore'] = function() {
	return ['game.getOtherScore()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_isSlowDownActive'] = function() {
	return ['game.isSlowDownActive()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};

Blockly.zr_cpp['zrms14_isBounceActive'] = function() {
	return ['game.isBounceActive()', Blockly.zr_cpp.ORDER_FUNCTION_CALL];
};<|endoftext|>


<commit_before>var async = require('async')
var crypto = require('crypto')
var exec = require('child_process').exec
var fs = require('fs')
var punycode = require('punycode')

module.exports = function(session) {
  return function(track, path, callback) {
    var tracktitle = track.artist.name + ' - ' + track.title

    if (track.availability === 'UNAVAILABLE') {
      console.log('Track unavavailabe, skipping: ' + tracktitle)
      return callback(null)
    }

    var player = session.getPlayer()

    // var destiny = path + '/' + track.artist.name + '/' + track.album.name + '/' + track.name
    var destiny = path + '/' + tracktitle

    var hashedName = crypto.createHash('sha1').update(
      tracktitle
    ).digest('hex')

    //getting a hash cuz eyeD3 is a motherfucker with special chars.
    var destinyHash = path + '/' + hashedName

    // skip if already exists
    if (fs.existsSync(destiny + '.mp3')) {
      console.log('File already exists, skipping: ' + tracktitle + '.mp3')
      return callback(null)
    }

    console.log('Downloading: ' + tracktitle)

    if (!fs.existsSync(path)) fs.mkdirSync(path)
    var ws = fs.createWriteStream(destinyHash + '.raw')

    player.load(track)
    player.play()
    player.pipe(ws)

    player.once('track-end', function() {
      player.stop()
      ws.end()

      async.waterfall([

        function(callback) {
          console.log('Converting raw file to wav')
          exec('sox ' + [
            '-r', 44100,
            '-b', 16,
            '-L',
            '-c', 2,
            '-e', 'signed-integer',
            '-t', 'raw',
            '"' + destinyHash + '.raw"',
            '"' + destinyHash + '.wav"'
          ].join(' '), function(err) {
            callback(err)
          })
        },
        function(callback) {
          console.log('Converting wav file to mp3 at 320kbps')
          exec('lame ' + [
            '--preset', 'insane',
            '-b', 320,
            '-h',
            '"' + destinyHash + '.wav"',
            '"' + destinyHash + '.mp3"'
          ].join(' '), function(err) {
            callback(err)
          })
        },
        function(callback) {
          track.album.coverImage(function(err, buffer) {
            if (err) {
              return callback(null, false)
            }
            fs.writeFile(destinyHash + '.png', buffer, function(err) {
              callback(null, true)
            })
          })
        },
        function(cover, callback) {
          console.log('Adding id3 tags')

          var coverCmd = ['--add-image', '"' + destinyHash + '.png:FRONT_COVER"']

          var args = [
            '-t', '"' + punycode.toASCII(track.title) + '"',
            '-a', '"' + punycode.toASCII(track.artist.name) + '"',
            '-A', '"' + punycode.toASCII(track.album.name) + '"',
            '-Y', '"' + track.album.year + '"',
            '"' + destinyHash + '.mp3"'
          ]

          // Adds the command to add a ilustration to the file
          if (cover)
            args = coverCmd.concat(args)

          var cmd = 'eyeD3 ' + args.join(' ')

          exec(cmd, function(err) {
            callback(err, cover)
          })

        },
        function(cover, callback) {
          // if (config.copy)
          //   exec('cp ' + destinyHash + '.mp3 ' + config.copy + '/' + destinyHash + '.mp3', function(err) {
          //     console.log(err)
          //   })
          // if (config.itunes)
          //   exec('open -a "itunes" ' + destinyHash + '.mp3 ', function(err) {
          //     console.log(err)
          //   })

          // cleanup
          fs.unlinkSync(destinyHash + '.raw')
          fs.unlinkSync(destinyHash + '.wav')
          fs.unlinkSync(destinyHash + '.png') // use flag? some may want it as cover.png or something

          fs.renameSync(destinyHash + '.mp3', destiny + '.mp3')

          // if (cover) {
          //   fs.renameSync(destinyHash + '.png', path + '/' + track.artist.name + ' - ' + track.title + '.png')
          // }
          callback()
        }

      ], function(err) {
        console.log('Finished: ' + tracktitle)
        ws.end()
        player.removeAllListeners('error')
        delete player, ws
        callback(err)
      })

    })

    player.on('error', function(err) {
      ws.end()
      callback(err)
    })
  }
}
<commit_msg>minor changes<commit_after>var async = require('async')
var crypto = require('crypto')
var exec = require('child_process').exec
var fs = require('fs')
var punycode = require('punycode')

module.exports = function(session) {
  return function(track, path, callback) {
    var tracktitle = track.artist.name + ' - ' + track.title

    if (track.availability === 'UNAVAILABLE') {
      console.log('Track unavavailabe, skipping: ' + tracktitle)
      return callback(null)
    }

    var player = session.getPlayer()

    // var destiny = path + '/' + track.artist.name + '/' + track.album.name + '/' + track.name
    var destiny = path + '/' + tracktitle

    var hashedName = crypto.createHash('sha1').update(
      tracktitle
    ).digest('hex')

    //getting a hash cuz eyeD3 is a motherfucker with special chars.
    var destinyHash = path + '/' + hashedName

    // skip if already exists
    if (fs.existsSync(destiny + '.mp3')) {
      console.log('File already exists, skipping: ' + tracktitle)
      return callback(null, tracktitle + '.mp3')
    }

    console.log('Downloading: ' + tracktitle)

    if (!fs.existsSync(path)) fs.mkdirSync(path)
    var ws = fs.createWriteStream(destinyHash + '.raw')

    player.load(track)
    player.play()
    player.pipe(ws)

    player.once('track-end', function() {
      player.stop()
      ws.end()

      async.waterfall([

        function(callback) {
          console.log('Converting raw file to wav')
          exec('sox ' + [
            '-r', 44100,
            '-b', 16,
            '-L',
            '-c', 2,
            '-e', 'signed-integer',
            '-t', 'raw',
            '"' + destinyHash + '.raw"',
            '"' + destinyHash + '.wav"'
          ].join(' '), function(err) {
            callback(err)
          })
        },
        function(callback) {
          console.log('Converting wav file to mp3 at 320kbps')
          exec('lame ' + [
            '--preset', 'insane',
            '-b', 320,
            '-h',
            '"' + destinyHash + '.wav"',
            '"' + destinyHash + '.mp3"'
          ].join(' '), function(err) {
            callback(err)
          })
        },
        function(callback) {
          track.album.coverImage(function(err, buffer) {
            if (err) {
              return callback(null, false)
            }
            fs.writeFile(destinyHash + '.png', buffer, function(err) {
              callback(null, true)
            })
          })
        },
        function(cover, callback) {
          console.log('Adding id3 tags')

          var coverCmd = ['--add-image', '"' + destinyHash + '.png:FRONT_COVER"']

          var args = [
            '-t', '"' + punycode.toASCII(track.title) + '"',
            '-a', '"' + punycode.toASCII(track.artist.name) + '"',
            '-A', '"' + punycode.toASCII(track.album.name) + '"',
            '-Y', '"' + track.album.year + '"',
            '"' + destinyHash + '.mp3"'
          ]

          // Adds the command to add a ilustration to the file
          if (cover)
            args = coverCmd.concat(args)

          var cmd = 'eyeD3 ' + args.join(' ')

          exec(cmd, function(err) {
            callback(err, cover)
          })

        },
        function(cover, callback) {
          // if (config.copy)
          //   exec('cp ' + destinyHash + '.mp3 ' + config.copy + '/' + destinyHash + '.mp3', function(err) {
          //     console.log(err)
          //   })
          // if (config.itunes)
          //   exec('open -a "itunes" ' + destinyHash + '.mp3 ', function(err) {
          //     console.log(err)
          //   })

          // cleanup
          fs.unlinkSync(destinyHash + '.raw')
          fs.unlinkSync(destinyHash + '.wav')
          // fs.unlinkSync(destinyHash + '.png') // use flag? some may want it as cover.png or something

          fs.renameSync(destinyHash + '.mp3', destiny + '.mp3')
          fs.renameSync(destinyHash + '.png', destiny + '.png')

          // if (cover) {
          //   fs.renameSync(destinyHash + '.png', path + '/' + track.artist.name + ' - ' + track.title + '.png')
          // }
          callback(null)
        }

      ], function(err) {
        console.log('Finished: ' + tracktitle)
        ws.end()
        player.removeAllListeners('error')
        delete player, ws
        callback(err, tracktitle)
      })

    })

    player.on('error', function(err) {
      ws.end()
      callback(err)
    })
  }
}
<|endoftext|>


<commit_before>let chai				= require("chai");
let expect				= chai.expect;
let assert				= chai.assert;

const API_KEY = process.env.API_KEY;
const API_SECRET = process.env.API_SECRET;

chai.should();

let PostcodeClient		= require("../lib/postcode");
let JSONRequest			= require("../lib/request");

describe("Postcode.nl API wrapper", () => {
	describe("PostcodeClient", () => {
		describe("#constructor()", () => {
			it("requires 'options.key' and 'options.secret'", () => {
				(() => {
					new PostcodeClient();
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({key: "test"});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({secret: "test"});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({key: "test", secret: "test"});
				}).should.not.throw(TypeError);
			});

			it("should have an instance of JSONRequest and options", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});
				client._r.should.be.instanceof(JSONRequest);
				client._options.should.be.an("object");
			});
		});

		describe("#address()", () => {
			it("should throw an error on invalid postcodes", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("0000");
				}).should.throw(TypeError);

				(() => {
					client.address("0000AA");
				}).should.throw(TypeError);
			});

			it("should fix simple client errors in postcodes", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("1111    Aa", 1);
				}).should.not.throw(TypeError);
			});

			it("should not accept non-integers or invalid ranges", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("1111AA", -1);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", 100000);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", 3.14);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", "10");
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", {foo: "bar"});
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", () => {});
				}).should.throw(TypeError);
			});

			it("should be able to start requesting the address", () => {
				(() => {
					client.address("1111AA", 1);
				}).should.not.throw(TypeError);
			});

			it("should be able to return valid address info", () => {
				expect(API_KEY).to.be.ok;
				expect(API_SECRET).to.be.ok;

				var client = new PostcodeClient({
					key: API_KEY,
					secret: API_SECRET
				});

				return client.address("1111AA", 1)
					.then((addressDetails) => {
						addressDetails.should.be.an("object");
					})
					.catch((err) => {
						assert(err === undefined, "Bad credentials supplied in environment variables");
						done();
					});
			});
		});

		describe("#signal()", () => {
			expect(API_KEY).to.be.ok;
			expect(API_SECRET).to.be.ok;

			var client = new PostcodeClient({
				key: API_KEY,
				secret: API_SECRET
			});

			it("should error on empty / invalid options object", () => {
				(() => {
					client.signal();
				}).should.throw(TypeError);

				(() => {
					client.signal({});
				}).should.throw(TypeError);
			});

			it("should return a promise on 'valid' options object", () => {
				client.signal({
					test: "test"
				}).should.be.instanceof(Promise);
			});

			it("should be able to generate a response", () => {
				return client.signal({
						transaction: {
							deliveryAddress: {
								postcode: "1111AA",
								houseNumber: 1,
								country: "NL"
							}
						}
					})
					.then((signalDetails) => {
						signalDetails.should.be.an("object");
						signalDetails.checkId.should.be.a("string");
					})
					.catch((err) => {
						assert(err === undefined, "Error calling the API: "+err.message);
						done();
					});
			});
		});
	});
});<commit_msg>Fix undefined stuff<commit_after>let chai				= require("chai");
let expect				= chai.expect;
let assert				= chai.assert;

const API_KEY = process.env.API_KEY;
const API_SECRET = process.env.API_SECRET;

chai.should();

let PostcodeClient		= require("../lib/postcode");
let JSONRequest			= require("../lib/request");

describe("Postcode.nl API wrapper", () => {
	describe("PostcodeClient", () => {
		describe("#constructor()", () => {
			it("requires 'options.key' and 'options.secret'", () => {
				(() => {
					new PostcodeClient();
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({key: "test"});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({secret: "test"});
				}).should.throw(TypeError);

				(() => {
					new PostcodeClient({key: "test", secret: "test"});
				}).should.not.throw(TypeError);
			});

			it("should have an instance of JSONRequest and options", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});
				client._r.should.be.instanceof(JSONRequest);
				client._options.should.be.an("object");
			});
		});

		describe("#address()", () => {
			it("should throw an error on invalid postcodes", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("0000");
				}).should.throw(TypeError);

				(() => {
					client.address("0000AA");
				}).should.throw(TypeError);
			});

			it("should fix simple client errors in postcodes", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("1111    Aa", 1);
				}).should.not.throw(TypeError);
			});

			it("should not accept non-integers or invalid ranges", () => {
				var client = new PostcodeClient({key: "test", secret: "test"});

				(() => {
					client.address("1111AA", -1);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", 100000);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", 3.14);
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", "10");
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", {foo: "bar"});
				}).should.throw(TypeError);

				(() => {
					client.address("1111AA", () => {});
				}).should.throw(TypeError);
			});

			it("should be able to start requesting the address", () => {
                var client = new PostcodeClient({
    				key: API_KEY,
    				secret: API_SECRET
    			});

				(() => {
					client.address("1111AA", 1);
				}).should.not.throw(TypeError);
			});

			it("should be able to return valid address info", (done) => {
				expect(API_KEY).to.be.ok;
				expect(API_SECRET).to.be.ok;

				var client = new PostcodeClient({
					key: API_KEY,
					secret: API_SECRET
				});

				return client.address("1111AA", 1)
					.then((addressDetails) => {
						addressDetails.should.be.an("object");
					})
					.catch((err) => {
						assert(err === undefined, "Bad credentials supplied in environment variables");
						done();
					});
			});
		});

		describe("#signal()", () => {
			expect(API_KEY).to.be.ok;
			expect(API_SECRET).to.be.ok;

			var client = new PostcodeClient({
				key: API_KEY,
				secret: API_SECRET
			});

			it("should error on empty / invalid options object", () => {
				(() => {
					client.signal();
				}).should.throw(TypeError);

				(() => {
					client.signal({});
				}).should.throw(TypeError);
			});

			it("should return a promise on 'valid' options object", () => {
				client.signal({
					test: "test"
				}).should.be.instanceof(Promise);
			});

			it("should be able to generate a response", (done) => {
				return client.signal({
						transaction: {
							deliveryAddress: {
								postcode: "1111AA",
								houseNumber: 1,
								country: "NL"
							}
						}
					})
					.then((signalDetails) => {
						signalDetails.should.be.an("object");
						signalDetails.checkId.should.be.a("string");
					})
					.catch((err) => {
						assert(err === undefined, "Error calling the API: "+err.message);
						done();
					});
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	sel = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'sort-selection-asc', function tests() {

	it( 'should export a function', function test() {
		expect( sel ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided a non-array', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			function(){},
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				sel( value );
			};
		}
	});

	it( 'should sort the array into ascending order', function test() {
		var data, expected;

		data = [ 14, -7, 4, 76, 30 ];
		expected = [ -7, 4, 14, 30, 76 ];

		// Apply selection sort, modifying data
		sel( data );

		for ( var i = 0; i < data.length; i++ ){
			assert.strictEqual( data[i], expected[i] );
		}

	});

});
<commit_msg>[UPDATE] Add tests<commit_after>'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	quick = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'sort-quicksort-asc', function tests() {

	it( 'should export a function', function test() {
		expect( quick ).to.be.a( 'function' );
	});

	it( 'should throw an error if provided a non-array', function test() {
		var values = [
			'5',
			5,
			true,
			undefined,
			null,
			NaN,
			function(){},
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}

		function badValue( value ) {
			return function() {
				quick( value );
			};
		}
	});

	it( 'should create an array sorted into ascending order', function test() {
		var data, expected, sorted;

		data = [ 14, -7, 4, 76, 30 ];
		expected = [ -7, 4, 14, 30, 76 ];

		// Apply quicksort, creating new, sorted array
		sorted = quick( data );

		for ( var i = 0; i < data.length; i++ ){
			assert.strictEqual( sorted[i], expected[i] );
		}

	});

});
<|endoftext|>