<commit_before>/*
Copyright 2014 Lcf.vs
Released under the MIT license
https://github.com/Lcfvs/easy-require
*/
var require;

require = function (global) {
    'use strict';

    var env,
        modules,
        url,
        Module,
        require;

    if (!Function.prototype.bind) {
        Function.prototype.bind = function bind(target) {
            var instance,
                args,
                constructor,
                bound;

            instance = this;

            if (typeof instance !== 'function') {
                throw new TypeError('Unable to bind '.concat(instance));
            }

            args = Array.prototype.slice.call(arguments, 1);
            constructor = function () {};

            bound = function bound() {
                return instance.apply(
                    this instanceof constructor
                    && target
                        ? this
                        : target,
                    args.concat(Array.prototype.slice.call(arguments))
                );
            };

            constructor.prototype = instance.prototype;
            bound.prototype = new constructor();

            return bound;
        };
    }

    env = {};
    modules = {};

    url = (function () {
        var absolutePattern,
            trailings1Pattern,
            trailings2Pattern,
            trailings3Pattern,
            rootPattern,
            parentsPattern,
            currentPattern,
            resolve,
            clean,
            concat,
            parseHost,
            isSegment,
            isAbsolute,
            removeTraillingSlashes;

        absolutePattern = /^(\w+:)?\/\//;
        trailings1Pattern = /([^/][^:])\/+/g;
        trailings2Pattern = /^(\/\/)\/+(.*)(\/+)?/;
        trailings3Pattern = /(\/)+$/;
        rootPattern = /^((?:[^:]+:)?\/\/[^/]+)(.*)/;
        parentsPattern = /((?:\/[^/]+)?\/\.\.)/g;
        currentPattern = /\/\./g;

        resolve = function resolve() {
            var segments;

            segments = Array.prototype.slice.call(arguments);

            if (!arguments.length) {
                return env.root;
            }

            return concat(parseHost(clean(segments)))
                .replace(trailings3Pattern, '');
        }

        clean = function clean(segments) {
            var iterator,
                length,
                segment;

            iterator = 0;
            length = segments.length;

            for (; iterator < segments.length; iterator += 1) {
                segment = segments[iterator];

                if (!isSegment(segment)) {
                    segments.splice(iterator, 1);

                    continue;
                }

                segment = removeTraillingSlashes(segment);
                segments[iterator] = segment;
            }

            return segments;
        };

        parseHost = function parseHost(segments) {
            var iterator,
                segment;

            iterator = segments.length - 1;

            for (; iterator > -1; iterator -= 1) {
                segment = segments[iterator];

                if (isAbsolute(segment)) {
                    segments.splice(0, iterator);

                    break;
                }
            }

            if (iterator === -1) {
                segments.unshift(env.root);
            }

            return segments;
        };

        concat = function concat(segments) {
            var result,
                iterator,
                length,
                segment,
                root;

            result = segments[0];
            iterator = 1;
            length = segments.length;

            for (; iterator < length; iterator += 1) {
                segment = segments[iterator];

                if (segment.charAt(0) !== '/') {
                    result = result.concat('/', segment);

                    continue;
                }

                result = result.replace(rootPattern, '$1'.concat(segment));
            }

            root = result.match(rootPattern)[1];

            return root.concat(
                result.substr(root.length)
                    .replace(parentsPattern, '')
                ).replace(currentPattern, '');
        };

        isSegment = function isSegment(segment) {
            if (typeof segment !== 'string') {
                throw new TypeError('Arguments to url.resolve must be strings');
            }

            return !!segment;
        };

        isAbsolute = function isAbsolute(segment) {
            return absolutePattern.test(segment);
        };

        removeTraillingSlashes = function removeTraillingSlashes(segment) {
            return segment.replace(trailings1Pattern, '$1/')
                .replace(trailings2Pattern, '$1$2')
                .replace(trailings3Pattern, '');
        };

        return {
            resolve: resolve
        };
    }());

    void function detectCwd() {
        var iterator,
            scripts,
            length,
            requirePattern,
            location,
            matches,
            cwd;

        iterator = 0;
        scripts = global.document.getElementsByTagName('script');
        length = scripts.length;
        requirePattern = /(.*)\/(?:easy-require)((?:\.min)?\.js$)/;
        location = global.location;

        for (; iterator < length; iterator += 1) {
            matches = scripts[iterator].src
                .match(requirePattern);

            if (matches && matches.length === 3) {
                break;
            }
        }

        cwd = matches[1];
        env.root = location.protocol.concat('//', location.host);

        if (cwd.indexOf('//') === -1) {
            cwd = url.resolve(env.root, cwd);
        }

        env.cwd = cwd;
        env.extension = matches[2];
    }();

    Module = (function build() {
        var dirnamePattern,
            extensionPattern,
            noop,
            execute,
            Module,
            prototype,
            parseUrl;

        dirnamePattern = /(\/[^\/]+)$/;
        extensionPattern = /(\.js)$/;
        noop = function noop() {};

        execute = Function.bind(
            undefined,
            'global',
            'module',
            'exports',
            'require',
            '__dirname',
            '__filename'
        );

        Module = function Module(url) {
            var instance;

            instance = this;
            instance.status = Module.INIT;
            instance.url = url;
            instance.mode = 0;

            instance.dirname = url.replace(dirnamePattern, '/');

            instance.callers = [];
            instance.dependencies = [];
            instance.require = instance.require.bind(instance);
            instance.onload = instance.onload.bind(instance);

            instance.module = {
                exports: {}
            };
        };

        Module.INIT = 0;
        Module.MODULE_LOADING = 1;
        Module.MODULE_LOADED = 2;
        Module.DEPENDENCIES_LOADING = 3;
        Module.DEPENDENCIES_LOADED = 4;
        Module.MODULE_DEFINED = 5;

        Module.loadInstance = function loadInstance(caller, modulePath) {
            var url,
                instance;

            url = parseUrl(caller.dirname, modulePath);
            instance = modules[url];

            if (!instance) {
                modules[url] =
                instance = new Module(url);
            }

            setTimeout(instance.addCaller.bind(instance, caller));

            return instance;
        };

        prototype = Module.prototype;

        prototype.addCaller = function addCaller(caller) {
            var instance,
                status;

            instance = this;
            instance.callers.push(caller);
            status = instance.status;

            if (status === Module.MODULE_DEFINED) {
                return instance.dispatch();
            }

            status === Module.INIT
            && instance.load();
        };

        prototype.load = function load() {
            var instance,
                ajax;

            instance = this;
            instance.status = Module.MODULE_LOADING;
            ajax = modules.ajax.module.exports;
            ajax(instance);

            return instance;
        };

        prototype.dispatch = function dispatch() {
            var instance,
                callers,
                caller;

            instance = this;
            callers = instance.callers;

            while (callers.length) {
                caller = callers.shift();
                caller.ondependency();
            }
        };

        prototype.onload = function onload(xhr) {
            var instance,
                module,
                closure;

            instance = this;

            if (instance.status === Module.MODULE_LOADING) {
                module = instance.module;
                instance.status = Module.MODULE_LOADED;

                closure = execute(
                    'void function () {'.concat(
                        prototype.require.plugins.join(';'),
                        ';',
                        xhr.responseText,
                        '}();'
                    )
                );

                closure.call(
                    instance,
                    global,
                    module,
                    module.exports,
                    instance.require,
                    instance.dirname,
                    instance.url
                );
            }
        };

        prototype.require = function require(dependencies, define) {
            var instance,
                iterator,
                length,
                url,
                dependency;

            instance = this;

            instance.define = typeof define === 'function'
                ? define
                : noop;

            instance.status = Module.DEPENDENCIES_LOADING;

            if (!dependencies.length) {
                instance.status = Module.DEPENDENCIES_LOADED;
                instance.define.call({});
                instance.exports = instance.module.exports;
                instance.status = Module.MODULE_DEFINED;

                return instance.dispatch();
            }

            iterator = 0;

            instance.remainingDependencies =
            length = dependencies.length;

            for (; iterator < length; iterator += 1) {
                url = dependencies[iterator];
                dependency = Module.loadInstance(instance, url);
                instance.dependencies.push(dependency);
            }
        };

        prototype.require.plugins = [];

        prototype.ondependency = function ondependency() {
            var instance,
                args,
                iterator,
                length,
                dependencies;

            instance = this;
            instance.remainingDependencies -= 1;

            if (instance.remainingDependencies) {
                return;
            }

            args = [];
            iterator = 0;
            dependencies = instance.dependencies;
            length = dependencies.length;

            for (; iterator < length; iterator += 1) {
                args.push(dependencies[iterator].module.exports);
            }

            instance.status = Module.DEPENDENCIES_LOADED;

            typeof instance.define === 'function'
            && instance.define.apply({}, args);

            instance.status = Module.MODULE_DEFINED;
            instance.dispatch();
        };

        parseUrl = function parseUrl(dirname, filename) {
            var resolve,
                extension,
                resolved,
                url;

            if (filename === 'ajax' || filename === 'url') {
                return filename;
            }

            extension = env.extension;
            resolve = modules.url.module.exports.resolve;

            if (filename.charAt(0) === '.') {
                resolved = resolve(dirname, filename);
            } else {
                resolved = resolve(env.cwd, filename);
            }

            url = resolved.substring(resolved.length - 3) === '.js'
                ? extension === '.js'
                    ? resolved
                    : resolved.replace(extensionPattern, extension)
                : resolved.concat('/index', extension);

            return url;
        };

        return Module;
    }());

    void function defineEmbeddedModules() {
        var ajax;

        modules.ajax =
        ajax = new Module('ajax');

        ajax.module.exports = (function() {
            var queue,
                ajax,
                parseRequest;

            queue = [];

            ajax = function ajax(request) {
                var xhr;

                xhr = new XMLHttpRequest();

                parseRequest(xhr, request);

                xhr.onreadystatechange = function onreadystatechange() {
                    var onload;

                    onload = xhr.onload;

                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {

                            if (onload) {
                                onload(xhr);
                            }

                            xhr.sendNext();
                        } else {
                            clearTimeout(xhr._timeout);

                            xhr._timeout = setTimeout(function() {
                                if ('sendRequest' in xhr) {
                                    xhr.sendRequest();
                                }
                            }, xhr.delay);
                        }
                    }
                };

                xhr.sendRequest = function sendRequest() {
                    var iterator,
                        method,
                        headers,
                        length,
                        data,
                        isGet,
                        url,
                        name;

                    iterator = 0;
                    method = xhr.method;
                    headers = xhr.headers;
                    length = headers.length;
                    data = xhr.data;
                    isGet = method === 'get';
                    url = xhr.url;

                    if (isGet && data) {
                        if (url.indexOf('?') !== -1) {
                            url = url.concat('&', data);
                        } else if (data.indexOf('?') === -1) {
                            url = url.concat('?', data);
                        }
                    }

                    xhr.open(method, url, xhr.async);

                    if (isGet) {
                        xhr.send('');

                        return;
                    }

                    for (name in headers) {
                        if (headers.hasOwnProperty(name)) {
                            xhr.setRequestHeader(name, headers[name]);
                        }
                    }

                    xhr.send(data === undefined
                        ? ''
                        : data
                    );
                };

                xhr.sendNext = function sendNext() {
                    var request,
                        readyState;

                    request = queue[0];

                    if (request) {
                        readyState = request.readyState;

                        if (readyState === 4 && request.status === 200) {
                            queue.shift();

                            if (queue.length !== 0) {
                                request.sendRequest();
                            }
                        } else if (readyState === 0) {
                            this.sendRequest();
                        }
                    }
                };

                xhr.cancel = function(deep) {
                    if (deep && deep > 0 && queue.length !== 1) {
                        queue[1].cancel(deep - 1);
                    }

                    this.abort();
                    queue.shift();
                };

                if (xhr.mode > ajax.ENQUEUE) {
                    xhr.sendRequest();

                    return xhr;
                }

                queue.push(xhr);
                queue[0].sendNext();

                return xhr;
            };

            ajax.ENQUEUE = 0;
            ajax.ASYNC = 1;
            ajax.SYNC = 2;

            parseRequest = function parseRequest(xhr, request) {
                var mode;

                xhr.url = request.url;

                xhr.mode =
                mode = ~~request.mode % 3;

                xhr.async = mode < ajax.SYNC;

                xhr.data = request.hasOwnProperty('data')
                    ? request.data
                    : null;

                xhr.method = request.hasOwnProperty('method')
                    ? request.method
                    : 'GET';

                xhr.onload = typeof request.onload === 'function'
                    ? request.onload
                    : null;

                xhr.delay = request.hasOwnProperty('delay')
                    ? request.delay
                    : 1000;

                xhr.headers = request.hasOwnProperty('headers')
                    ? request.headers
                    : {};

                xhr.headers['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';

                if (xhr.method !== 'GET') {
                    xhr.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                }
            };

            return ajax;
        }());

        ajax.status = Module.MODULE_DEFINED;

        modules.url = new Module('url');

        modules.url.module.exports = url;

        modules.url.status = Module.MODULE_DEFINED;
    }();

    require = function require(dependencies, define) {
        var instance,
            deferred;

        instance = new Module(env.cwd);
        deferred = instance.require.bind(instance, dependencies, define);
        setTimeout(deferred);
    };

    require.plugins = Module.prototype.require.plugins;

    return require;
}(this);
<commit_msg>Simplifying the require arguments<commit_after>/*
Copyright 2014 Lcf.vs
Released under the MIT license
https://github.com/Lcfvs/easy-require
*/
var require;

require = function (global) {
    'use strict';

    var env,
        modules,
        url,
        Module,
        require;

    if (!Function.prototype.bind) {
        Function.prototype.bind = function bind(target) {
            var instance,
                args,
                constructor,
                bound;

            instance = this;

            if (typeof instance !== 'function') {
                throw new TypeError('Unable to bind '.concat(instance));
            }

            args = Array.prototype.slice.call(arguments, 1);
            constructor = function () {};

            bound = function bound() {
                return instance.apply(
                    this instanceof constructor
                    && target
                        ? this
                        : target,
                    args.concat(Array.prototype.slice.call(arguments))
                );
            };

            constructor.prototype = instance.prototype;
            bound.prototype = new constructor();

            return bound;
        };
    }

    env = {};
    modules = {};

    url = (function () {
        var absolutePattern,
            trailings1Pattern,
            trailings2Pattern,
            trailings3Pattern,
            rootPattern,
            parentsPattern,
            currentPattern,
            resolve,
            clean,
            concat,
            parseHost,
            isSegment,
            isAbsolute,
            removeTraillingSlashes;

        absolutePattern = /^(\w+:)?\/\//;
        trailings1Pattern = /([^/][^:])\/+/g;
        trailings2Pattern = /^(\/\/)\/+(.*)(\/+)?/;
        trailings3Pattern = /(\/)+$/;
        rootPattern = /^((?:[^:]+:)?\/\/[^/]+)(.*)/;
        parentsPattern = /((?:\/[^/]+)?\/\.\.)/g;
        currentPattern = /\/\./g;

        resolve = function resolve() {
            var segments;

            segments = Array.prototype.slice.call(arguments);

            if (!arguments.length) {
                return env.root;
            }

            return concat(parseHost(clean(segments)))
                .replace(trailings3Pattern, '');
        }

        clean = function clean(segments) {
            var iterator,
                length,
                segment;

            iterator = 0;
            length = segments.length;

            for (; iterator < segments.length; iterator += 1) {
                segment = segments[iterator];

                if (!isSegment(segment)) {
                    segments.splice(iterator, 1);

                    continue;
                }

                segment = removeTraillingSlashes(segment);
                segments[iterator] = segment;
            }

            return segments;
        };

        parseHost = function parseHost(segments) {
            var iterator,
                segment;

            iterator = segments.length - 1;

            for (; iterator > -1; iterator -= 1) {
                segment = segments[iterator];

                if (isAbsolute(segment)) {
                    segments.splice(0, iterator);

                    break;
                }
            }

            if (iterator === -1) {
                segments.unshift(env.root);
            }

            return segments;
        };

        concat = function concat(segments) {
            var result,
                iterator,
                length,
                segment,
                root;

            result = segments[0];
            iterator = 1;
            length = segments.length;

            for (; iterator < length; iterator += 1) {
                segment = segments[iterator];

                if (segment.charAt(0) !== '/') {
                    result = result.concat('/', segment);

                    continue;
                }

                result = result.replace(rootPattern, '$1'.concat(segment));
            }

            root = result.match(rootPattern)[1];

            return root.concat(
                result.substr(root.length)
                    .replace(parentsPattern, '')
                ).replace(currentPattern, '');
        };

        isSegment = function isSegment(segment) {
            if (typeof segment !== 'string') {
                throw new TypeError('Arguments to url.resolve must be strings');
            }

            return !!segment;
        };

        isAbsolute = function isAbsolute(segment) {
            return absolutePattern.test(segment);
        };

        removeTraillingSlashes = function removeTraillingSlashes(segment) {
            return segment.replace(trailings1Pattern, '$1/')
                .replace(trailings2Pattern, '$1$2')
                .replace(trailings3Pattern, '');
        };

        return {
            resolve: resolve
        };
    }());

    void function detectCwd() {
        var iterator,
            scripts,
            length,
            requirePattern,
            location,
            matches,
            cwd;

        iterator = 0;
        scripts = global.document.getElementsByTagName('script');
        length = scripts.length;
        requirePattern = /(.*)\/(?:easy-require)((?:\.min)?\.js$)/;
        location = global.location;

        for (; iterator < length; iterator += 1) {
            matches = scripts[iterator].src
                .match(requirePattern);

            if (matches && matches.length === 3) {
                break;
            }
        }

        cwd = matches[1];
        env.root = location.protocol.concat('//', location.host);

        if (cwd.indexOf('//') === -1) {
            cwd = url.resolve(env.root, cwd);
        }

        env.cwd = cwd;
        env.extension = matches[2];
    }();

    Module = (function build() {
        var dirnamePattern,
            extensionPattern,
            noop,
            execute,
            Module,
            prototype,
            parseUrl;

        dirnamePattern = /(\/[^\/]+)$/;
        extensionPattern = /(\.js)$/;
        noop = function noop() {};

        execute = Function.bind(
            undefined,
            'global',
            'module',
            'exports',
            'require',
            '__dirname',
            '__filename'
        );

        Module = function Module(url) {
            var instance;

            instance = this;
            instance.status = Module.INIT;
            instance.url = url;
            instance.mode = 0;

            instance.dirname = url.replace(dirnamePattern, '/');

            instance.callers = [];
            instance.dependencies = [];
            instance.require = instance.require.bind(instance);
            instance.onload = instance.onload.bind(instance);

            instance.module = {
                exports: {}
            };
        };

        Module.INIT = 0;
        Module.MODULE_LOADING = 1;
        Module.MODULE_LOADED = 2;
        Module.DEPENDENCIES_LOADING = 3;
        Module.DEPENDENCIES_LOADED = 4;
        Module.MODULE_DEFINED = 5;

        Module.loadInstance = function loadInstance(caller, modulePath) {
            var url,
                instance;

            url = parseUrl(caller.dirname, modulePath);
            instance = modules[url];

            if (!instance) {
                modules[url] =
                instance = new Module(url);
            }

            setTimeout(instance.addCaller.bind(instance, caller));

            return instance;
        };

        prototype = Module.prototype;

        prototype.addCaller = function addCaller(caller) {
            var instance,
                status;

            instance = this;
            instance.callers.push(caller);
            status = instance.status;

            if (status === Module.MODULE_DEFINED) {
                return instance.dispatch();
            }

            status === Module.INIT
            && instance.load();
        };

        prototype.load = function load() {
            var instance,
                ajax;

            instance = this;
            instance.status = Module.MODULE_LOADING;
            ajax = modules.ajax.module.exports;
            ajax(instance);

            return instance;
        };

        prototype.dispatch = function dispatch() {
            var instance,
                callers,
                caller;

            instance = this;
            callers = instance.callers;

            while (callers.length) {
                caller = callers.shift();
                caller.ondependency();
            }
        };

        prototype.onload = function onload(xhr) {
            var instance,
                module,
                closure;

            instance = this;

            if (instance.status === Module.MODULE_LOADING) {
                module = instance.module;
                instance.status = Module.MODULE_LOADED;

                closure = execute(
                    'void function () {'.concat(
                        prototype.require.plugins.join(';'),
                        ';',
                        xhr.responseText,
                        '}();'
                    )
                );

                closure.call(
                    instance,
                    global,
                    module,
                    module.exports,
                    instance.require,
                    instance.dirname,
                    instance.url
                );
            }
        };

        prototype.require = function require(dependencies, define) {
            var instance,
                type,
                argsLength,
                dependencyList,
                iterator,
                length,
                url,
                dependency;

            instance = this;
            argsLength = arguments.length;
            type = typeof dependencies;

            if (argsLength === 2) {
                if (type === 'string') {
                    dependencyList = [dependencies];
                } else if (dependencies instanceof Array) {
                    dependencyList = dependencies;
                }

                instance.define = define;
            } else if (argsLength === 1) {
                if (type === 'string') {
                    dependencyList = [dependencies];
                    instance.define = noop;
                } else if (type === 'function') {
                    dependencyList = [];
                    instance.define = define;
                } else if (dependencies instanceof Array) {
                    dependencyList = dependencies;
                    instance.define = noop;
                }
            }

            if (typeof instance.define !== 'function') {
                throw new Error('Unable to internally name a module');
            }

            instance.status = Module.DEPENDENCIES_LOADING;

            if (!dependencyList.length) {
                instance.status = Module.DEPENDENCIES_LOADED;
                instance.define.call({});
                instance.exports = instance.module.exports;
                instance.status = Module.MODULE_DEFINED;

                return instance.dispatch();
            }

            iterator = 0;

            instance.remainingDependencies =
            length = dependencyList.length;

            for (; iterator < length; iterator += 1) {
                url = dependencyList[iterator];
                dependency = Module.loadInstance(instance, url);
                instance.dependencies.push(dependency);
            }
        };

        prototype.require.plugins = [];

        prototype.ondependency = function ondependency() {
            var instance,
                args,
                iterator,
                length,
                dependencies;

            instance = this;
            instance.remainingDependencies -= 1;

            if (instance.remainingDependencies) {
                return;
            }

            args = [];
            iterator = 0;
            dependencies = instance.dependencies;
            length = dependencies.length;

            for (; iterator < length; iterator += 1) {
                args.push(dependencies[iterator].module.exports);
            }

            instance.status = Module.DEPENDENCIES_LOADED;
            instance.define.apply({}, args);
            instance.status = Module.MODULE_DEFINED;
            instance.dispatch();
        };

        parseUrl = function parseUrl(dirname, filename) {
            var resolve,
                extension,
                resolved,
                url;

            if (filename === 'ajax' || filename === 'url') {
                return filename;
            }

            extension = env.extension;
            resolve = modules.url.module.exports.resolve;

            if (filename.charAt(0) === '.') {
                resolved = resolve(dirname, filename);
            } else {
                resolved = resolve(env.cwd, filename);
            }

            url = resolved.substring(resolved.length - 3) === '.js'
                ? extension === '.js'
                    ? resolved
                    : resolved.replace(extensionPattern, extension)
                : resolved.concat('/index', extension);

            return url;
        };

        return Module;
    }());

    void function defineEmbeddedModules() {
        var ajax;

        modules.ajax =
        ajax = new Module('ajax');

        ajax.module.exports = (function() {
            var queue,
                ajax,
                parseRequest;

            queue = [];

            ajax = function ajax(request) {
                var xhr;

                xhr = new XMLHttpRequest();

                parseRequest(xhr, request);

                xhr.onreadystatechange = function onreadystatechange() {
                    var onload;

                    onload = xhr.onload;

                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {

                            if (onload) {
                                onload(xhr);
                            }

                            xhr.sendNext();
                        } else {
                            clearTimeout(xhr._timeout);

                            xhr._timeout = setTimeout(function() {
                                if ('sendRequest' in xhr) {
                                    xhr.sendRequest();
                                }
                            }, xhr.delay);
                        }
                    }
                };

                xhr.sendRequest = function sendRequest() {
                    var iterator,
                        method,
                        headers,
                        length,
                        data,
                        isGet,
                        url,
                        name;

                    iterator = 0;
                    method = xhr.method;
                    headers = xhr.headers;
                    length = headers.length;
                    data = xhr.data;
                    isGet = method === 'get';
                    url = xhr.url;

                    if (isGet && data) {
                        if (url.indexOf('?') !== -1) {
                            url = url.concat('&', data);
                        } else if (data.indexOf('?') === -1) {
                            url = url.concat('?', data);
                        }
                    }

                    xhr.open(method, url, xhr.async);

                    if (isGet) {
                        xhr.send('');

                        return;
                    }

                    for (name in headers) {
                        if (headers.hasOwnProperty(name)) {
                            xhr.setRequestHeader(name, headers[name]);
                        }
                    }

                    xhr.send(data === undefined
                        ? ''
                        : data
                    );
                };

                xhr.sendNext = function sendNext() {
                    var request,
                        readyState;

                    request = queue[0];

                    if (request) {
                        readyState = request.readyState;

                        if (readyState === 4 && request.status === 200) {
                            queue.shift();

                            if (queue.length !== 0) {
                                request.sendRequest();
                            }
                        } else if (readyState === 0) {
                            this.sendRequest();
                        }
                    }
                };

                xhr.cancel = function(deep) {
                    if (deep && deep > 0 && queue.length !== 1) {
                        queue[1].cancel(deep - 1);
                    }

                    this.abort();
                    queue.shift();
                };

                if (xhr.mode > ajax.ENQUEUE) {
                    xhr.sendRequest();

                    return xhr;
                }

                queue.push(xhr);
                queue[0].sendNext();

                return xhr;
            };

            ajax.ENQUEUE = 0;
            ajax.ASYNC = 1;
            ajax.SYNC = 2;

            parseRequest = function parseRequest(xhr, request) {
                var mode;

                xhr.url = request.url;

                xhr.mode =
                mode = ~~request.mode % 3;

                xhr.async = mode < ajax.SYNC;

                xhr.data = request.hasOwnProperty('data')
                    ? request.data
                    : null;

                xhr.method = request.hasOwnProperty('method')
                    ? request.method
                    : 'GET';

                xhr.onload = typeof request.onload === 'function'
                    ? request.onload
                    : null;

                xhr.delay = request.hasOwnProperty('delay')
                    ? request.delay
                    : 1000;

                xhr.headers = request.hasOwnProperty('headers')
                    ? request.headers
                    : {};

                xhr.headers['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';

                if (xhr.method !== 'GET') {
                    xhr.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                }
            };

            return ajax;
        }());

        ajax.status = Module.MODULE_DEFINED;

        modules.url = new Module('url');

        modules.url.module.exports = url;

        modules.url.status = Module.MODULE_DEFINED;
    }();

    require = function require(dependencies, define) {
        var instance,
            deferred;

        instance = new Module(env.cwd);
        deferred = instance.require.bind(instance, dependencies, define);
        setTimeout(deferred);
    };

    require.plugins = Module.prototype.require.plugins;

    return require;
}(this);
<|endoftext|>


<commit_before>var _ = require('lodash'),
  dom = require('./dom'),
  references = require('./references'),
  formCreator = require('./form-creator'),
  edit = require('./edit'),
  formValues = require('./form-values'),
  currentForm = {}, // Store form currently open, as only one form can be open at a time.
  inlineSelector = '.editor-inline',
  overlaySelector = '.editor-overlay-background';

/**
 * Check if a form is currently open. Only one form can be open at a time.
 * @returns {boolean}
 */
function formIsOpen() {
  return !!currentForm.ref;
}

/**
 * Check if data is top level of the component. e.g. Top level when in a settings form
 * @param {string} ref
 * @param {string} path
 * @returns {boolean}
 */
function isTopLevel(ref, path) {
  return path === references.getComponentNameFromReference(ref);
}

/**
 * Find the form container.
 * @returns {Element}
 */
function findFormContainer() {
  return dom.find(overlaySelector) || dom.find(inlineSelector);
}

/**
 * Get the current form's data.
 * @param {Element} form
 * @param {string} ref
 * @param {string} path
 * @returns {Object}
 */
function getFormData(form, ref, path) {
  var data = formValues.get(ref, form);

  if (!isTopLevel(ref, path)) {
    data = _.get(data, path);
  }
  return data;
}

/**
 * Store the data from the server to compare for changes.
 * @param {string} ref
 * @param {string} path
 * @param {object} data
 */
function storeServerData(ref, path, data) {
  var dataOnly = edit.removeSchemaFromData(_.cloneDeep(data));

  currentForm.serverData = isTopLevel(ref, path) ? dataOnly : _.get(dataOnly, path);
}

/**
 * Check if the local data is different than the data on the server.
 * @param {object} data   Edited data.
 * @returns {boolean}
 */
function dataChanged(data) {
  return !_.isEqual(data, currentForm.serverData);
}

/**
 * if it's an inline form, replace it with the original elements
 * @param {Element} el  form container, possibly inline
 */
function replaceInlineForm(el) {
  var parent = el.parentNode;

  if (el.classList.contains('editor-inline')) {
    dom.unwrapElements(parent, dom.find(parent, '.hidden-wrapped'));
  }
}

/**
 * Remove the form element and clear the currentForm object.
 * @param {Element} container
 */
function removeCurrentForm(container) {
  if (container) {
    replaceInlineForm(container);
    dom.removeElement(container);
  }
  currentForm = {};
}

/**
 * Reload page. Disabled during unit tests.
 */
function reload() {
  window.location.reload();
}

/**
 * Open a form.
 * @param {string} ref
 * @param {Element} el    The element that has `data-editable`, not always the parent of the form.
 * @param {string} path
 * @param {MouseEvent} [e]
 * @return {Promise|undefined}
 */
function open(ref, el, path, e) {
  if (!formIsOpen()) {
    if (e) {
      e.stopPropagation();
      e.preventDefault();
    }
    currentForm = {
      ref: ref,
      path: path
    };
    return edit.getData(ref).then(function (data) {
      storeServerData(ref, path, data);
      if (path) {
        data = _.get(data, path);
        if (data._schema[references.displayProperty] === 'inline') {
          // inline forms have a path and _display: inline
          return formCreator.createInlineForm(ref, path, data, el);
        } else {
          // overlay forms have a path and are the default
          formCreator.createForm(ref, path, data);
        }
      } else {
        // settings forms don't have a path, since they're operating on the whole component
        return formCreator.createSettingsForm(ref, data);
      }
    });
  }
}

/**
 * Close and save the open form.
 * @returns {Promise}
 */
function close() {
  return Promise.resolve((function () {
    var ref, path, container, form, data;

    if (formIsOpen()) {
      ref = currentForm.ref;
      path = currentForm.path;
      container = findFormContainer();
      form = container && dom.find(container, 'form');
      data = form && getFormData(form, ref, path);

      if (dataChanged(data)) {
        return edit.update(ref, data, path)
          .then(function () {
            removeCurrentForm(container);
            // Todo: don't reload the entire page.
            module.exports.reload();
          })
          .catch(function () {
            console.warn('Did not save.');
          });
      } else {
        // Nothing changed, so do not reload.
        removeCurrentForm(container);
      }
    }
  }()));
}

exports.open = open;
exports.close = close;
exports.reload = reload; // For unit tests.
<commit_msg>Remove isTop.<commit_after>var _ = require('lodash'),
  dom = require('./dom'),
  references = require('./references'),
  formCreator = require('./form-creator'),
  edit = require('./edit'),
  formValues = require('./form-values'),
  currentForm = {}, // Store form currently open, as only one form can be open at a time.
  inlineSelector = '.editor-inline',
  overlaySelector = '.editor-overlay-background';

/**
 * Check if a form is currently open. Only one form can be open at a time.
 * @returns {boolean}
 */
function formIsOpen() {
  return !!currentForm.ref;
}

/**
 * Find the form container.
 * @returns {Element}
 */
function findFormContainer() {
  return dom.find(overlaySelector) || dom.find(inlineSelector);
}

/**
 * Get the current form's data.
 * @param {Element} form
 * @param {string} ref
 * @param {string} path
 * @returns {Object}
 */
function getFormData(form, ref, path) {
  return _.get(formValues.get(ref, form), path);
}

/**
 * Store the data from the server to compare for changes.
 * @param {string} path
 * @param {object} data
 */
function storeServerData(path, data) {
  var dataOnly = edit.removeSchemaFromData(_.cloneDeep(data));

  currentForm.serverData = _.get(dataOnly, path);
}

/**
 * Check if the local data is different than the data on the server.
 * @param {object} data   Edited data.
 * @returns {boolean}
 */
function dataChanged(data) {
  return !_.isEqual(data, currentForm.serverData);
}

/**
 * if it's an inline form, replace it with the original elements
 * @param {Element} el  form container, possibly inline
 */
function replaceInlineForm(el) {
  var parent = el.parentNode;

  if (el.classList.contains('editor-inline')) {
    dom.unwrapElements(parent, dom.find(parent, '.hidden-wrapped'));
  }
}

/**
 * Remove the form element and clear the currentForm object.
 * @param {Element} container
 */
function removeCurrentForm(container) {
  if (container) {
    replaceInlineForm(container);
    dom.removeElement(container);
  }
  currentForm = {};
}

/**
 * Reload page. Disabled during unit tests.
 */
function reload() {
  window.location.reload();
}

/**
 * Open a form.
 * @param {string} ref
 * @param {Element} el    The element that has `data-editable`, not always the parent of the form.
 * @param {string} path
 * @param {MouseEvent} [e]
 * @return {Promise|undefined}
 */
function open(ref, el, path, e) {
  if (!formIsOpen()) {
    if (e) {
      e.stopPropagation();
      e.preventDefault();
    }
    currentForm = {
      ref: ref,
      path: path
    };
    return edit.getData(ref).then(function (data) {
      storeServerData(path, data);
      if (path) {
        data = _.get(data, path);
        if (data._schema[references.displayProperty] === 'inline') {
          // inline forms have a path and _display: inline
          return formCreator.createInlineForm(ref, path, data, el);
        } else {
          // overlay forms have a path and are the default
          formCreator.createForm(ref, path, data);
        }
      } else {
        // settings forms don't have a path, since they're operating on the whole component
        return formCreator.createSettingsForm(ref, data);
      }
    });
  }
}

/**
 * Close and save the open form.
 * @returns {Promise}
 */
function close() {
  return Promise.resolve((function () {
    var ref, path, container, form, data;

    if (formIsOpen()) {
      ref = currentForm.ref;
      path = currentForm.path;
      container = findFormContainer();
      form = container && dom.find(container, 'form');
      data = form && getFormData(form, ref, path);

      if (dataChanged(data)) {
        return edit.update(ref, data, path)
          .then(function () {
            removeCurrentForm(container);
            // Todo: don't reload the entire page.
            module.exports.reload();
          })
          .catch(function () {
            console.warn('Did not save.');
          });
      } else {
        // Nothing changed, so do not reload.
        removeCurrentForm(container);
      }
    }
  }()));
}

exports.open = open;
exports.close = close;
exports.reload = reload; // For unit tests.
<|endoftext|>


<commit_before>const config = require('./config');
const _ = require('lodash');

let helpers = {};

const REQUIRED_HELPERS = [
  'cleanDocumentId',
  'determinePlayer',
  'documentDescription',
  'documentLicense',
  'documentTitle',
  'generateSitemapElements',
  'getDownloadOptions',
  'isDownloadable',
  'isWatermarkRequired'
];

helpers.capitalizeFirstLetter = string => {
  if(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  } else {
    return string;
  }
};

helpers.checkRequiredHelpers = () => {
  REQUIRED_HELPERS.forEach((requiredHelper) => {
    if(typeof(helpers[requiredHelper]) !== 'function') {
      throw new Error('Missing required helper function: ' + requiredHelper);
    }
  });
};

helpers.decimals = function(n, decimals) {
  if (typeof(n) !== 'undefined' && n !== null) {
    return parseFloat(n).toFixed(decimals).replace('.', ',');
  } else {
    return n;
  }
};

helpers.generateSearchTitle = filters => {
  if(filters.q) {
    return 'Søgning på "' + filters.q + '"';
  } else {
    return 'Søgning';
  }
};

helpers.getDocumentURL = (metadata) => {
  let path = [metadata.collection];
  if(Object.keys(config.types).length > 1) {
    path.push(metadata.type);
  }
  path.push(metadata.id);
  return '/' + path.join('/');
};

helpers.getThumbnailURL = (metadata, size, watermarkPosition) => {
  let path = [
    helpers.getDocumentURL(metadata),
    'thumbnail'
  ];
  if(size) {
    path.push(size);
    if(watermarkPosition) {
      path.push(watermarkPosition);
    }
  }
  return path.join('/');
};

const SOCIAL_THUMBNAIL_SIZE = 500;

helpers.getSocialThumbnailURL = (metadata) => {
  if(config.thumbnailSize >= SOCIAL_THUMBNAIL_SIZE) {
    console.warn('config.thumbnailSize should be < ' + SOCIAL_THUMBNAIL_SIZE);
  }
  return helpers.getThumbnailURL(metadata, SOCIAL_THUMBNAIL_SIZE);
};

helpers.getDownloadURL = (metadata, size) => {
  let path = [
    helpers.getDocumentURL(metadata),
    'download'
  ];
  if(size) {
    path.push(size);
  }
  return path.join('/');
};

helpers.getAbsoluteURL = (req, relativePath) => {
  return req.protocol + '://' + req.get('host') + relativePath;
};

helpers.getDirectDownloadURL = (metadata) => {
  if(!config.cip || !config.cip.baseURL) {
    throw new Error('Expected the baseURL of the CIP to be configered');
  }
  return [
    config.cip.baseURL,
    'asset',
    'download',
    metadata.collection,
    metadata.id
  ].join('/');
};

helpers.getAssetField = (shortName) => {
  if(!config.types || !config.types.asset || !config.types.asset.fields) {
    throw new Error('Cannot get field. Missing config.types.asset.fields');
  }
  return config.types.asset.fields.find((field) => field.short === shortName);
};

helpers.licenseMapped = (metadata) => {
  let license = helpers.documentLicense(metadata);
  if(license) {
    return config.licenseMapping[license];
  } else {
    return null;
  }
};

helpers.licenseLinked = function(license) {
  if (license && license in config.licenseMapping) {
    const licenseOptions = config.licenseMapping[license];
    return helpers.link(licenseOptions.url, license);
  } else {
    return license || 'Ukendt';
  }
};

helpers.link = function(url, text) {
  if(!text) {
    text = url;
  }
  return '' + text + '';
};

// TODO: Consider if a localization function might be easier to use
helpers.thousandsSeparator = (number) => {
  if(number) {
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.');
  } else {
    return number;
  }
};

helpers.translate = key => {
  if(config.translations[key]) {
    return config.translations[key];
  } else {
    return key;
  }
};

/**
 * Use this method to get all values at the "end of a path" in an object.
 * It traverses the object along the path, if an array is found along the way
 * the result will contain an array of values for that sub-tree of the object.
 *
 * Example:
 *    object = {a: [{b: [{c: 'test'}, {c: 'this'}]}]}
 *    path = 'a.b.c'
 *    returns [[['test', 'this']]]
 *
 * @param {Object} object The object to look for values in.
 * @param {string} path The path used when looking for values.
 */
helpers.getAny = (object, path) => {
  if(typeof(path) === 'string') {
    // If given a string, split on dots and call recursively
    return helpers.getAny(object, path.split('.'));
  } else if(Array.isArray(path)){
    if(path.length === 0) {
      // Throw an error if requested with an empty path
      throw new Error('Expected some path');
    } else if(path.length === 1) {
      // We have arrived at the leaf of the path
      return object[path[0]] || null;
    } else {
      const value = object[path[0]];
      const restOfPath = path.slice(1);
      if(value && Array.isArray(value)) {
        return value.map(item => {
          return helpers.getAny(item, restOfPath);
        });
      } else if(value) {
        return helpers.getAny(value, restOfPath);
      }
    }
  } else {
    throw new Error('Path had an unexpected type: ' + typeof(path));
  }
};

 /**
  * Use this method to get all values at the "end of a path" in an object,
  * you have multiple such paths and you want a flat array of values.
  * It traverses the object along each of the paths and returns a flattened
  * array of values.
  *
  * Example:
  *    object = {a: {b: [{c: 'test', d: 123}, {c: 'this'}]}}
  *    path = ['a.b.c', 'a.b.d']
  *    returns ['test', 'this', 123]
  *
  * @param {Object} object The object to look for values in.
  * @param {string[]} paths The paths used when looking for values.
  */
helpers.getAnyFlat = (object, paths) => {
  // For every path - getAny values
  const values = paths.map(path => {
    return helpers.getAny(object, path);
  });
  // Flatten them deep and filter out empty values.
  return _.flattenDeep(values).filter(value => value);
};

module.exports = helpers;
<commit_msg>isArray will return false on a falsely value anyway<commit_after>const config = require('./config');
const _ = require('lodash');

let helpers = {};

const REQUIRED_HELPERS = [
  'cleanDocumentId',
  'determinePlayer',
  'documentDescription',
  'documentLicense',
  'documentTitle',
  'generateSitemapElements',
  'getDownloadOptions',
  'isDownloadable',
  'isWatermarkRequired'
];

helpers.capitalizeFirstLetter = string => {
  if(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  } else {
    return string;
  }
};

helpers.checkRequiredHelpers = () => {
  REQUIRED_HELPERS.forEach((requiredHelper) => {
    if(typeof(helpers[requiredHelper]) !== 'function') {
      throw new Error('Missing required helper function: ' + requiredHelper);
    }
  });
};

helpers.decimals = function(n, decimals) {
  if (typeof(n) !== 'undefined' && n !== null) {
    return parseFloat(n).toFixed(decimals).replace('.', ',');
  } else {
    return n;
  }
};

helpers.generateSearchTitle = filters => {
  if(filters.q) {
    return 'Søgning på "' + filters.q + '"';
  } else {
    return 'Søgning';
  }
};

helpers.getDocumentURL = (metadata) => {
  let path = [metadata.collection];
  if(Object.keys(config.types).length > 1) {
    path.push(metadata.type);
  }
  path.push(metadata.id);
  return '/' + path.join('/');
};

helpers.getThumbnailURL = (metadata, size, watermarkPosition) => {
  let path = [
    helpers.getDocumentURL(metadata),
    'thumbnail'
  ];
  if(size) {
    path.push(size);
    if(watermarkPosition) {
      path.push(watermarkPosition);
    }
  }
  return path.join('/');
};

const SOCIAL_THUMBNAIL_SIZE = 500;

helpers.getSocialThumbnailURL = (metadata) => {
  if(config.thumbnailSize >= SOCIAL_THUMBNAIL_SIZE) {
    console.warn('config.thumbnailSize should be < ' + SOCIAL_THUMBNAIL_SIZE);
  }
  return helpers.getThumbnailURL(metadata, SOCIAL_THUMBNAIL_SIZE);
};

helpers.getDownloadURL = (metadata, size) => {
  let path = [
    helpers.getDocumentURL(metadata),
    'download'
  ];
  if(size) {
    path.push(size);
  }
  return path.join('/');
};

helpers.getAbsoluteURL = (req, relativePath) => {
  return req.protocol + '://' + req.get('host') + relativePath;
};

helpers.getDirectDownloadURL = (metadata) => {
  if(!config.cip || !config.cip.baseURL) {
    throw new Error('Expected the baseURL of the CIP to be configered');
  }
  return [
    config.cip.baseURL,
    'asset',
    'download',
    metadata.collection,
    metadata.id
  ].join('/');
};

helpers.getAssetField = (shortName) => {
  if(!config.types || !config.types.asset || !config.types.asset.fields) {
    throw new Error('Cannot get field. Missing config.types.asset.fields');
  }
  return config.types.asset.fields.find((field) => field.short === shortName);
};

helpers.licenseMapped = (metadata) => {
  let license = helpers.documentLicense(metadata);
  if(license) {
    return config.licenseMapping[license];
  } else {
    return null;
  }
};

helpers.licenseLinked = function(license) {
  if (license && license in config.licenseMapping) {
    const licenseOptions = config.licenseMapping[license];
    return helpers.link(licenseOptions.url, license);
  } else {
    return license || 'Ukendt';
  }
};

helpers.link = function(url, text) {
  if(!text) {
    text = url;
  }
  return '' + text + '';
};

// TODO: Consider if a localization function might be easier to use
helpers.thousandsSeparator = (number) => {
  if(number) {
    return number.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.');
  } else {
    return number;
  }
};

helpers.translate = key => {
  if(config.translations[key]) {
    return config.translations[key];
  } else {
    return key;
  }
};

/**
 * Use this method to get all values at the "end of a path" in an object.
 * It traverses the object along the path, if an array is found along the way
 * the result will contain an array of values for that sub-tree of the object.
 *
 * Example:
 *    object = {a: [{b: [{c: 'test'}, {c: 'this'}]}]}
 *    path = 'a.b.c'
 *    returns [[['test', 'this']]]
 *
 * @param {Object} object The object to look for values in.
 * @param {string} path The path used when looking for values.
 */
helpers.getAny = (object, path) => {
  if(typeof(path) === 'string') {
    // If given a string, split on dots and call recursively
    return helpers.getAny(object, path.split('.'));
  } else if(Array.isArray(path)){
    if(path.length === 0) {
      // Throw an error if requested with an empty path
      throw new Error('Expected some path');
    } else if(path.length === 1) {
      // We have arrived at the leaf of the path
      return object[path[0]] || null;
    } else {
      const value = object[path[0]];
      const restOfPath = path.slice(1);
      if(Array.isArray(value)) {
        return value.map(item => {
          return helpers.getAny(item, restOfPath);
        });
      } else if(value) {
        return helpers.getAny(value, restOfPath);
      }
    }
  } else {
    throw new Error('Path had an unexpected type: ' + typeof(path));
  }
};

 /**
  * Use this method to get all values at the "end of a path" in an object,
  * you have multiple such paths and you want a flat array of values.
  * It traverses the object along each of the paths and returns a flattened
  * array of values.
  *
  * Example:
  *    object = {a: {b: [{c: 'test', d: 123}, {c: 'this'}]}}
  *    path = ['a.b.c', 'a.b.d']
  *    returns ['test', 'this', 123]
  *
  * @param {Object} object The object to look for values in.
  * @param {string[]} paths The paths used when looking for values.
  */
helpers.getAnyFlat = (object, paths) => {
  // For every path - getAny values
  const values = paths.map(path => {
    return helpers.getAny(object, path);
  });
  // Flatten them deep and filter out empty values.
  return _.flattenDeep(values).filter(value => value);
};

module.exports = helpers;
<|endoftext|>


<commit_before>/*
  Author: Oliver Steele
  Copyright: Copyright 2006 Oliver Steele.  All rights reserved.
  Download: http://osteele.com/sources/openlaszlo/simple-logging.js
  License: MIT License.

  This file defines +info+, +warn+, +error+, and +debug+ functions
  that are compatible with those defined in
  {readable.js}[http://osteele.com/sources/javascript/readable.js],
  {inline-console.js}[http://osteele.com/sources/javascript/inline-console.js],
  and fvlogger[http://www.alistapart.com/articles/jslogging].  This
  allows libraries that use these functions to be used in both
  OpenLaszlo programs and in DHTML.
*/

function __debug_message(level, args) {
    Debug.write.apply(Debug, [level].concat(args));
}

function info() {__debug_message('info', arguments); return arguments[0]}
function debug() {__debug_message('debug', arguments)}
function warn() {Debug.warn.apply(Debug, arguments)}
function error() {Debug.error.apply(Debug, arguments)}
<commit_msg>simple-logging can log to browser console<commit_after>/*
  Author: Oliver Steele
  Copyright: Copyright 2006 Oliver Steele.  All rights reserved.
  Download: http://osteele.com/sources/openlaszlo/simple-logging.js
  License: MIT License.

  This file defines +info+, +warn+, +error+, and +debug+ functions
  that are compatible with those defined in
  {readable.js}[http://osteele.com/sources/javascript/readable.js],
  {inline-console.js}[http://osteele.com/sources/javascript/inline-console.js],
  and fvlogger[http://www.alistapart.com/articles/jslogging].  This
  allows libraries that use these functions to be used in both
  OpenLaszlo programs and in DHTML.
*/

function __debug_message(level, args) {
    Debug.write.apply(Debug, [level].concat(args));
}

function info() {__debug_message('info', arguments); return arguments[0]}
function debug() {__debug_message('debug', arguments)}
function warn() {Debug.warn.apply(Debug, arguments)}
function error() {Debug.error.apply(Debug, arguments)}

if (false) {
    function info() {
        var expr = ['window.console && console.info && console.info(',
            JSON.stringify(arguments), ')'].join('');
        LzBrowser.loadJS(expr);
    }

    function error() {
        var expr = ['window.console && console.error && console.error(',
            JSON.stringify(arguments), ')'].join('');
        LzBrowser.loadJS(expr);
    }
}<|endoftext|>


<commit_before>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //PLAYER and CAMERA bounds

    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }
  if(PLAYER.position.y < 200) {
    PLAYER.position.y = 200;
  }
  /*

  End of PLAYER/CAMERA bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Player movement | abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;

    if(PLAYER.position.y < 370) {
      PLAYER.position.y = 370;
    }
  }

    //  sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 16;
  } else {
    playerStep = 4;
  }

    //  Player spits fire
  if(keyWentDown(32)) {
    var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
    // fire.addImage(FireImg);
    fire.life = 40;
    if(PLAYER.mirrorX() === -1) {
      fire.setSpeed(15, 0);
      fire.mirrorX(1);
      FIRE.add(fire);
    }
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("camera: " + camera.position.x);
  console.log("player: " + PLAYER.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 4; i++) {
    var posX = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posY = 475;
    createEnemy(posX, posY);

    // if(ENEMIES.get(i).overlap(STRUCTURES)) {
    //   if(ENEMIES.get(i).getDirection == 180) {
    //     ENEMIES.get(i).setSpeed(1, 0);
    //   } else {
    //     ENEMIES.get(i).setSpeed(-1, 0)
    //   }
    // }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

    //  Structures
  if(frameCount % 60 == 0) {

  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);

    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }

    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<commit_msg>0.25 beta<commit_after>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //PLAYER and CAMERA bounds

    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }

  if(PLAYER.position.y < 200) {
    PLAYER.position.y = 200;
  }
  /*

  End of PLAYER/CAMERA bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Player movement | abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;

    if(PLAYER.position.y < 370) {
      PLAYER.position.y = 370;
    }
  }

    //  sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 16;
  } else {
    playerStep = 4;
  }

    //  Player spits fire
  if(keyWentDown(32)) {
      var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
      //fire.addImage(FireImg);
      fire.life = 40;
      fire.setSpeed(-(11 + playerStep) * PLAYER.mirrorX(), 0);
      fire.mirrorX(-1 * PLAYER.mirrorX());
      FIRE.add(fire);
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("camera: " + camera.position.x);
  console.log("player: " + PLAYER.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 4; i++) {
    var posX = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posY = 475;
    createEnemy(posX, posY);

    // if(ENEMIES.get(i).overlap(STRUCTURES)) {
    //   if(ENEMIES.get(i).getDirection == 180) {
    //     ENEMIES.get(i).setSpeed(1, 0);
    //   } else {
    //     ENEMIES.get(i).setSpeed(-1, 0)
    //   }
    // }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

    //  Structures
  if(frameCount % 60 == 0) {

  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);

    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }

    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<|endoftext|>


<commit_before>/* global $ GM_info sidebar relEditor */
'use strict';
// ==UserScript==
// @name         MusicBrainz event editor: Fill event setlist
// @namespace    mbz-loujine
// @author       loujine
// @version      2018.7.16
// @downloadURL  https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/mb-edit-fill_event_setlist.user.js
// @updateURL    https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/mb-edit-fill_event_setlist.user.js
// @supportURL   https://bitbucket.org/loujine/musicbrainz-scripts
// @icon         https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/icon.png
// @description  musicbrainz.org event editor: Fill event setlist
// @compatible   firefox+tampermonkey
// @license      MIT
 // @require      https://greasyfork.org/scripts/13747-mbz-loujine-common/code/mbz-loujine-common.js?version=612784
// @include      http*://*musicbrainz.org/event/*/edit
// @include      https://musicbrainz.org/event/create
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function displayToolbar() {
    document.getElementsByClassName('half-width')[0].insertAdjacentHTML(
        'afterend', '

');
    relEditor.container(document.getElementById('side-col')).insertAdjacentHTML(
        'beforeend', `

Complete entity in setlist

        <input type="button" id="fillArtist" value="Fill artist MBID">
        <input type="button" id="fillWork" value="Fill work MBID">
    `);
    document.getElementById('loujine-menu').style.marginLeft = '550px';
})();

function fillEventSetlist(entityType) {
    const area = document.getElementById("id-edit-event.setlist");
    // document.getSelection() does not work on textarea
    const entity = area.value.substring(area.selectionStart, area.selectionEnd);
    fetch(`/ws/2/${entityType}?query=${entityType}:${entity}&limit=1&fmt=json`).then(
        resp => resp.json()
    ).then(
        resp => {
            const filledEntity = entityType === 'artist' ?
                `@ [${resp.artists[0].id}|${resp.artists[0].name}]` :
                `* [${resp.works[0].id}|${resp.works[0].title}]`;
            area.value = area.value.replace(`/${entity}/g`, filledEntity);
        }
    )
}

$(document).ready(function() {
    let appliedNote = false;
    document.getElementById('fillArtist').addEventListener('click',
        () => {
            fillEventSetlist('work')
            if (!appliedNote) {
                document.getElementById('id-edit-event.edit_note')
                    .value = sidebar.editNote(GM_info.script);
                appliedNote = true;
            }
        }
    );
    document.getElementById('fillWork').addEventListener('click',
        () => {
            fillEventSetlist('work')
            if (!appliedNote) {
                document.getElementById('id-edit-event.edit_note')
                    .value = sidebar.editNote(GM_info.script);
                appliedNote = true;
            }
        }
    );
    return false;
});
<commit_msg>[event setlist] Fix entity type<commit_after>/* global $ GM_info sidebar relEditor */
'use strict';
// ==UserScript==
// @name         MusicBrainz event editor: Fill event setlist
// @namespace    mbz-loujine
// @author       loujine
// @version      2018.7.16
// @downloadURL  https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/mb-edit-fill_event_setlist.user.js
// @updateURL    https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/mb-edit-fill_event_setlist.user.js
// @supportURL   https://bitbucket.org/loujine/musicbrainz-scripts
// @icon         https://bitbucket.org/loujine/musicbrainz-scripts/raw/default/icon.png
// @description  musicbrainz.org event editor: Fill event setlist
// @compatible   firefox+tampermonkey
// @license      MIT
 // @require      https://greasyfork.org/scripts/13747-mbz-loujine-common/code/mbz-loujine-common.js?version=612784
// @include      http*://*musicbrainz.org/event/*/edit
// @include      https://musicbrainz.org/event/create
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function displayToolbar() {
    document.getElementsByClassName('half-width')[0].insertAdjacentHTML(
        'afterend', '

');
    relEditor.container(document.getElementById('side-col')).insertAdjacentHTML(
        'beforeend', `

Complete entity in setlist

Select text in the setlist box and click one of the buttons
           to add the right symbol and MBID

        <input type="button" id="fillArtist" value="Fill artist MBID">
        <input type="button" id="fillWork" value="Fill work MBID">
    `);
    document.getElementById('loujine-menu').style.marginLeft = '550px';
})();

function fillEventSetlist(entityType) {
    const area = document.getElementById("id-edit-event.setlist");
    // document.getSelection() does not work on textarea
    const entity = area.value.substring(area.selectionStart, area.selectionEnd);
    fetch(`/ws/2/${entityType}?query=${entityType}:${entity}&limit=1&fmt=json`).then(
        resp => resp.json()
    ).then(
        resp => {
            const filledEntity = entityType === 'artist' ?
                `@ [${resp.artists[0].id}|${resp.artists[0].name}]` :
                `* [${resp.works[0].id}|${resp.works[0].title}]`;
            area.value = area.value.replace(`/${entity}/g`, filledEntity);
        }
    )
}

$(document).ready(function() {
    let appliedNote = false;
    document.getElementById('fillArtist').addEventListener('click',
        () => {
            fillEventSetlist('artist')
            if (!appliedNote) {
                document.getElementById('id-edit-event.edit_note')
                    .value = sidebar.editNote(GM_info.script);
                appliedNote = true;
            }
        }
    );
    document.getElementById('fillWork').addEventListener('click',
        () => {
            fillEventSetlist('work')
            if (!appliedNote) {
                document.getElementById('id-edit-event.edit_note')
                    .value = sidebar.editNote(GM_info.script);
                appliedNote = true;
            }
        }
    );
    return false;
});
<|endoftext|>


<commit_before>/**
 * JavaScript library written for Kitsune by Mozilla.
 * License: MPL
 * License URL: http://www.mozilla.org/MPL/
 *
 * Contains two jQuery functions: wrapDeleteInput and ajaxSubmitInput.
 * These are helpers for posting data from a <form> to an  in Django.
 * They use and require the csrfmiddlewaretoken (you may remove those lines
 * if you want to avoid that).
 */

/**
 * Wrap an input in its own form and bind delete handlers.
 *
 * Depends on ajaxSubmitInput, which it binds to the click event on the delete
 * <input>.
 * Optionally accepts an error message for invalid JSON and a title for
 * the error message dialog.
 *
 * Uses jQueryUI for the dialog.
 */
jQuery.fn.wrapDeleteInput = function (options) {
    // Only works on <input/>
    if (!this.is('input')) {
        return this;
    }

    options = $.extend({
        error_title_del: 'Error deleting',
        error_json: 'Please check you are logged in, and try again.',
        onComplete: function() {}
    }, options);

    var $that = this,
        $attachment = $that.closest('.attachment'),
        $image = $attachment.find('.image');

    $that.ajaxSubmitInput({
        url: $that.attr('data-url'),
        inputEvent: 'click',
        beforeSubmit: function($input) {
            var $overlay = $input.closest('.overlay', $attachment);
            if ($overlay.length <= 0) {
                $overlay = $('

')
                               .appendTo($attachment);
            }
            $overlay.show();
            $image.fadeTo(500, 0.5);
        },
        onComplete: function($input, iframeContent, $options) {
            if (!iframeContent) {
                $image.css('opacity', 1);
                return;
            }
            var iframeJSON;
            try {
                iframeJSON = $.parseJSON(iframeContent);
            } catch(err) {
                if (err.substr(0, 12)  === 'Invalid JSON') {
                    dialogSet(options.error_json, options.error_title_del);
                    $image.css('opacity', 1);
                    return;
                }
            }
            if (iframeJSON.status !== 'success') {
                dialogSet(iframeJSON.message, options.error_title_del);
                $image.css('opacity', 1);
                return;
            }
            $attachment.remove();
            options.onComplete();
        }
    });

    return this;
};

/**
 * Takes a file input, wraps it in a form, creates an iframe and posts the form
 * to that iframe on submit.
 * Allows for the following options:
 * accept: list of MIME types to accept. See the HTML accept attribute.
 * beforeSubmit: function called on submit, before the form data is POSTed.
 * onComplete: function called when iframe has finished loading and the upload
 *             is complete.
 */
jQuery.fn.ajaxSubmitInput = function (options) {
    // Only works on <input/>
    if (!this.is('input')) {
        return this;
    }

    options = $.extend({
        url: '/upload',
        accept: false,
        inputEvent: 'change',
        beforeSubmit: function() {},
        onComplete: function() {}
    }, options);

    var uniqueID = Math.random() * 100000,
        $input = this,
        $parentForm = $input.closest('form'),
        iframeName = 'upload_' + uniqueID,
        $form = '<form class="upload-input" action="' +
                options.url + '" target="' + iframeName +
                '" method="post" enctype="multipart/form-data"/>',
        $iframe = $('')
                   //'" style="position:fixed;top:0px;width:500px;height:350px" />')
                    .appendTo('body'),
        passJSON;

    if (options.accept) {
        $input.attr('accept', options.accept);
    }

    $input.wrap($form);
    $form = $input.closest('form');
    // add the csrfmiddlewaretoken to the upload form
    $('input[name="csrfmiddlewaretoken"]').first().clone().appendTo($form);

    $iframe.load(function() {
        var iframeContent = $iframe[0].contentWindow.document.body.innerHTML;
        options.onComplete($input, iframeContent, passJSON);
    });

    $input.bind(options.inputEvent, function() {
        passJSON = options.beforeSubmit($input);

        if (false === passJSON) {
            return false;
        }

        $form.submit();
    });

    return this;
};
<commit_msg>[bug 675198] Add a confirmation dialog for deleting image attachments.<commit_after>/**
 * JavaScript library written for Kitsune by Mozilla.
 * License: MPL
 * License URL: http://www.mozilla.org/MPL/
 *
 * Contains two jQuery functions: wrapDeleteInput and ajaxSubmitInput.
 * These are helpers for posting data from a <form> to an  in Django.
 * They use and require the csrfmiddlewaretoken (you may remove those lines
 * if you want to avoid that).
 */

/**
 * Wrap an input in its own form and bind delete handlers.
 *
 * Depends on ajaxSubmitInput, which it binds to the click event on the delete
 * <input>.
 * Optionally accepts an error message for invalid JSON and a title for
 * the error message dialog.
 *
 */
jQuery.fn.wrapDeleteInput = function (options) {
    // Only works on <input/>
    if (!this.is('input')) {
        return this;
    }

    options = $.extend({
        error_title_del: gettext('Error deleting'),
        error_json: gettext('Please check you are logged in, and try again.'),
        onComplete: function() {}
    }, options);

    var $that = this,
        $attachment = $that.closest('.attachment'),
        $image = $attachment.find('.image');

    $that.ajaxSubmitInput({
        url: $that.attr('data-url'),
        inputEvent: 'click',
        beforeSubmit: function($input) {
            if (confirm(gettext('Are you sure you want delete the image?'))) {
                var $overlay = $input.closest('.overlay', $attachment);
                if ($overlay.length <= 0) {
                    $overlay = $('

')
                                   .appendTo($attachment);
                }
                $overlay.show();
                $image.fadeTo(500, 0.5);
            } else {
                return false;
            }
        },
        onComplete: function($input, iframeContent, $options) {
            if (!iframeContent) {
                $image.css('opacity', 1);
                return;
            }
            var iframeJSON;
            try {
                iframeJSON = $.parseJSON(iframeContent);
            } catch(err) {
                if (err.substr(0, 12)  === 'Invalid JSON') {
                    dialogSet(options.error_json, options.error_title_del);
                    $image.css('opacity', 1);
                    return;
                }
            }
            if (iframeJSON.status !== 'success') {
                dialogSet(iframeJSON.message, options.error_title_del);
                $image.css('opacity', 1);
                return;
            }
            $attachment.remove();
            options.onComplete();
        }
    });

    return this;
};

/**
 * Takes a file input, wraps it in a form, creates an iframe and posts the form
 * to that iframe on submit.
 * Allows for the following options:
 * accept: list of MIME types to accept. See the HTML accept attribute.
 * beforeSubmit: function called on submit, before the form data is POSTed.
 * onComplete: function called when iframe has finished loading and the upload
 *             is complete.
 */
jQuery.fn.ajaxSubmitInput = function (options) {
    // Only works on <input/>
    if (!this.is('input')) {
        return this;
    }

    options = $.extend({
        url: '/upload',
        accept: false,
        inputEvent: 'change',
        beforeSubmit: function() {},
        onComplete: function() {}
    }, options);

    var uniqueID = Math.random() * 100000,
        $input = this,
        $parentForm = $input.closest('form'),
        iframeName = 'upload_' + uniqueID,
        $form = '<form class="upload-input" action="' +
                options.url + '" target="' + iframeName +
                '" method="post" enctype="multipart/form-data"/>',
        $iframe = $('')
                   //'" style="position:fixed;top:0px;width:500px;height:350px" />')
                    .appendTo('body'),
        passJSON;

    if (options.accept) {
        $input.attr('accept', options.accept);
    }

    $input.wrap($form);
    $form = $input.closest('form');
    // add the csrfmiddlewaretoken to the upload form
    $('input[name="csrfmiddlewaretoken"]').first().clone().appendTo($form);

    $iframe.load(function() {
        var iframeContent = $iframe[0].contentWindow.document.body.innerHTML;
        options.onComplete($input, iframeContent, passJSON);
    });

    $input.bind(options.inputEvent, function() {
        passJSON = options.beforeSubmit($input);

        if (false === passJSON) {
            return false;
        }

        $form.submit();
    });

    return this;
};
<|endoftext|>


<commit_before>import { Observable } from 'rx';

export default function(Donation) {
  Donation.on('dataSourceAttached', () => {
    Donation.find$ = Observable.fromNodeCallback(Donation.find.bind(Donation));
    Donation.findOne$ = Observable.fromNodeCallback(
      Donation.findOne.bind(Donation)
    );
  });

  function getCurrentActiveDonationCount$() {
    // eslint-disable-next-line no-undefined
    return Donation.find$({ where: { endDate: undefined } }).map(
      instances => instances.length
    );
  }

  Donation.getCurrentActiveDonationCount$ = getCurrentActiveDonationCount$;
}
<commit_msg>feat: Use InMemoryCache to reducve load on db<commit_after>import { Observable } from 'rx';
import debug from 'debug';

import InMemoryCache from '../utils/in-memory-cache';

const log = debug('fcc:boot:donate');
const fiveMinutes = 1000 * 60 * 5;

export default function(Donation) {
  let activeDonationUpdateInterval = null;
  const activeDonationCountCacheTTL = fiveMinutes;
  const activeDonationCountCache = InMemoryCache(0);
  const activeDonationsQuery$ = () =>
    Donation.find$({
      // eslint-disable-next-line no-undefined
      where: { endDate: undefined }
    }).map(instances => instances.length);
  function cleanUp() {
    if (activeDonationUpdateInterval) {
      clearInterval(activeDonationUpdateInterval);
    }
    return;
  }

  process.on('exit', cleanUp);
  Donation.on('dataSourceAttached', () => {
    Donation.find$ = Observable.fromNodeCallback(Donation.find.bind(Donation));
    Donation.findOne$ = Observable.fromNodeCallback(
      Donation.findOne.bind(Donation)
    );
    activeDonationsQuery$().subscribe(count => {
      log('activeDonator count: %d', count);
      return activeDonationCountCache.update(() => count);
    });

    activeDonationUpdateInterval = setInterval(
      () =>
        activeDonationsQuery$().subscribe(count => {
          log('activeDonator count: %d', count);
          return activeDonationCountCache.update(() => count);
        }),
      activeDonationCountCacheTTL
    );
  });

  function getCurrentActiveDonationCount$() {
    return Observable.of(activeDonationCountCache.get());
  }

  Donation.getCurrentActiveDonationCount$ = getCurrentActiveDonationCount$;
}
<|endoftext|>


<commit_before>var pathfindLib = require('../lib/pathfind'),
  errorHandler = require('./errorHandler');

module.exports = function(opts) {

  var remote = opts.remote;

  return {

    getPathFind: function(req, res) {

      var src_address = req.query.src_address,
        dst_address = req.query.dst_address,
        dst_amount_param = req.query.dst_amount,
        dst_amount;

      if (typeof dst_amount_param === 'string') {

        var dst_amount_array = dst_amount_param.split(' ');

        if (dst_amount_array.length === 2 || dst_amount_array.length === 3) {
          dst_amount = {
            value: dst_amount_array[0],
            currency: dst_amount_array[1],
            issuer: (dst_amount_array.length === 3 ?
              dst_amount_array[2] :
              '')
          };
        } else {
          errorHandler(res, new Error('Invalid parameter: dst_amount. Must be astring in the form \'1/USD/r...\' or an object in the form { value: \'1\', currency: \'XRP\', issuer: \' }'));
          return;
        }

      } else if (typeof dst_amount_param === 'object') {

        dst_amount = dst_amount_param;

      } else {
        errorHandler(res, new Error('Invalid parameter: dst_amount. Must be a string in the form \'1/USD/r...\' or an object in the form { value: \'1\', currency: \'XRP\', issuer: \' }'));
        return;
      }

      pathfindLib.getPathFind(remote, {
        src_address: src_address,
        dst_address: dst_address,
        dst_amount: dst_amount
      }, function(err, payments){
        if (err) {
          errorHandler(res, err);
          return;
        }

        res.send({
          success: true,
          payments: payments
        });

      });

    }

  };

};
<commit_msg>[FIX] Fixed error message for payments/options<commit_after>var pathfindLib = require('../lib/pathfind'),
  errorHandler = require('./errorHandler');

module.exports = function(opts) {

  var remote = opts.remote;

  return {

    getPathFind: function(req, res) {

      var src_address = req.query.src_address,
        dst_address = req.query.dst_address,
        dst_amount_param = req.query.dst_amount,
        dst_amount;

      if (typeof dst_amount_param === 'string') {

        var dst_amount_array = dst_amount_param.split(' ');

        if (dst_amount_array.length === 2 || dst_amount_array.length === 3) {
          dst_amount = {
            value: dst_amount_array[0],
            currency: dst_amount_array[1],
            issuer: (dst_amount_array.length === 3 ?
              dst_amount_array[2] :
              '')
          };
        } else {
          errorHandler(res, new Error('Invalid parameter: dst_amount. Must be astring in the form \'1+USD+r...\' or an object in the form { value: \'1\', currency: \'XRP\', issuer: \' }'));
          return;
        }

      } else if (typeof dst_amount_param === 'object') {

        dst_amount = dst_amount_param;

      } else {
        errorHandler(res, new Error('Invalid parameter: dst_amount. Must be a string in the form \'1+USD+r...\' or an object in the form { value: \'1\', currency: \'XRP\', issuer: \' }'));
        return;
      }

      pathfindLib.getPathFind(remote, {
        src_address: src_address,
        dst_address: dst_address,
        dst_amount: dst_amount
      }, function(err, payments){
        if (err) {
          errorHandler(res, err);
          return;
        }

        res.send({
          success: true,
          payments: payments
        });

      });

    }

  };

};
<|endoftext|>