<commit_before>const { join } = require('path')
const gp = require('glob-parent')
const globAll = require('glob-all')
const File = require('./file')
const sourceMapInit = require('./helpers/init')
const sourceMapWrite = require('./helpers/write')

class Assistant {
    constructor () {
        this._loadedProcessors = new Map()
        this._aliasMap = new Map()
    }
    static createFile ({ cwd, path, base, contents }) {
        return new File({
            cwd,
            path,
            base: base || cwd,
            contents
        }, { loadContents: true })
    }
    static createFiles (glob, options = {}) {
        if (!Array.isArray(glob)) {
            glob = [glob]
        }
        const cwd = options.cwd || process.cwd()
        const files = globAll.sync(glob, {
            cwd
        })
        let loadContents = true
        if (options.loadContents === false) {
            loadContents = false
        }
        const base = options.base || join(cwd, gp(glob[0]))
        return files.map(v => new File({
            cwd,
            base,
            path: join(cwd, v)
        }, { loadContents }))
    }
    load (name, fn) {
        if (!name || !fn) {
            throw new Error(`Assistant.load: invalid arguments`)
        }
        this._loadedProcessors.set(name, fn)
    }
    unload (name) {
        return name && this._loadedProcessors.delete(name)
    }
    alias (alias, origin) {
        if (!origin || !alias || alias === origin) {
            return false
        }
        if (this._loadedProcessors.has(origin)) {
            this._aliasMap.set(alias, origin)
            return true
        }
        return false
    }
    unalias (aliasName) {
        return this._aliasMap.delete(aliasName)
    }
    support (name) {
        return this._loadedProcessors.has(name) || this._aliasMap.has(name)
    }
    list (withEntries) {
        return withEntries
            ? this._loadedProcessors.entries()
            : this._loadedProcessors.keys()
    }
    apply (files, loaders, options = {}) {
        if (!Array.isArray(files) || !Array.isArray(loaders)) {
            throw new Error('Assistant.apply: invalid arguments')
        }
        console.log('apply', options)
        const loadersBeforeConcat = []
        const loadersAfterConcat = []
        let hasConcatLoader = false
        loaders.forEach(loader => {
            if (typeof loader === 'string') {
                loader = {
                    name: loader,
                    options: {}
                }
            }
            if (loader.name === 'concat') {
                hasConcatLoader = true
            }
            if (hasConcatLoader) {
                loadersAfterConcat.push(loader)
            } else {
                loadersBeforeConcat.push(loader)
            }
        })
        const promises = files.map(file => {
            let promise = options.map ? sourceMapInit(file) : Promise.resolve(file)
            loadersBeforeConcat.forEach(loader => {
                let loaderFn = this._loadedProcessors.get(loader.name)
                promise = promise.then(file => loaderFn(file, loader.options))
            })
            return promise
        })
        return Promise.all(promises).then(files => {
            const concatLoader = loadersAfterConcat.shift()
            if (!concatLoader) return files
            return this._loadedProcessors.get(concatLoader.name)(
                files,
                concatLoader.options
            ).then(joinedFile => {
                let promise = Promise.resolve(joinedFile)
                loadersAfterConcat.forEach(loader => {
                    let loaderFn = this._loadedProcessors.get(loader.name)
                    promise = promise.then(file => loaderFn(file, loader.options))
                })
                return promise
            })
        })
    }
    process (glob, loaders, options = {}) {
        if (!loaders || !loaders.length || !glob) {
            throw new Error('Assistant.process: invalid arguments.')
        }
        if (options.map !== false) {
            options.map = true
        }
        const files = Assistant.createFiles([].concat(glob), options)
        return this.apply(files, loaders, options)
    }
}

const man = new Assistant()
man.load('css', require('./processors/css'))
man.load('less', require('./processors/less'))
man.load('sass', require('./processors/sass'))
man.load('postcss', require('./processors/postcss'))
man.load('minify', require('./processors/minify'))
man.load('autoprefixer', require('./processors/autoprefixer'))
man.load('concat', require('./processors/concat'))
man.alias('scss', 'sass')

exports = module.exports = man
exports.Assistant = Assistant
exports.writeMap = sourceMapWrite
<commit_msg>remove console.log<commit_after>const { join } = require('path')
const gp = require('glob-parent')
const globAll = require('glob-all')
const File = require('./file')
const sourceMapInit = require('./helpers/init')
const sourceMapWrite = require('./helpers/write')

class Assistant {
    constructor () {
        this._loadedProcessors = new Map()
        this._aliasMap = new Map()
    }
    static createFile ({ cwd, path, base, contents }) {
        return new File({
            cwd,
            path,
            base: base || cwd,
            contents
        }, { loadContents: true })
    }
    static createFiles (glob, options = {}) {
        if (!Array.isArray(glob)) {
            glob = [glob]
        }
        const cwd = options.cwd || process.cwd()
        const files = globAll.sync(glob, {
            cwd
        })
        let loadContents = true
        if (options.loadContents === false) {
            loadContents = false
        }
        const base = options.base || join(cwd, gp(glob[0]))
        return files.map(v => new File({
            cwd,
            base,
            path: join(cwd, v)
        }, { loadContents }))
    }
    load (name, fn) {
        if (!name || !fn) {
            throw new Error(`Assistant.load: invalid arguments`)
        }
        this._loadedProcessors.set(name, fn)
    }
    unload (name) {
        return name && this._loadedProcessors.delete(name)
    }
    alias (alias, origin) {
        if (!origin || !alias || alias === origin) {
            return false
        }
        if (this._loadedProcessors.has(origin)) {
            this._aliasMap.set(alias, origin)
            return true
        }
        return false
    }
    unalias (aliasName) {
        return this._aliasMap.delete(aliasName)
    }
    support (name) {
        return this._loadedProcessors.has(name) || this._aliasMap.has(name)
    }
    list (withEntries) {
        return withEntries
            ? this._loadedProcessors.entries()
            : this._loadedProcessors.keys()
    }
    apply (files, loaders, options = {}) {
        if (!Array.isArray(files) || !Array.isArray(loaders)) {
            throw new Error('Assistant.apply: invalid arguments')
        }
        const loadersBeforeConcat = []
        const loadersAfterConcat = []
        let hasConcatLoader = false
        loaders.forEach(loader => {
            if (typeof loader === 'string') {
                loader = {
                    name: loader,
                    options: {}
                }
            }
            if (loader.name === 'concat') {
                hasConcatLoader = true
            }
            if (hasConcatLoader) {
                loadersAfterConcat.push(loader)
            } else {
                loadersBeforeConcat.push(loader)
            }
        })
        const promises = files.map(file => {
            let promise = options.map ? sourceMapInit(file) : Promise.resolve(file)
            loadersBeforeConcat.forEach(loader => {
                let loaderFn = this._loadedProcessors.get(loader.name)
                promise = promise.then(file => loaderFn(file, loader.options))
            })
            return promise
        })
        return Promise.all(promises).then(files => {
            const concatLoader = loadersAfterConcat.shift()
            if (!concatLoader) return files
            return this._loadedProcessors.get(concatLoader.name)(
                files,
                concatLoader.options
            ).then(joinedFile => {
                let promise = Promise.resolve(joinedFile)
                loadersAfterConcat.forEach(loader => {
                    let loaderFn = this._loadedProcessors.get(loader.name)
                    promise = promise.then(file => loaderFn(file, loader.options))
                })
                return promise
            })
        })
    }
    process (glob, loaders, options = {}) {
        if (!loaders || !loaders.length || !glob) {
            throw new Error('Assistant.process: invalid arguments.')
        }
        if (options.map !== false) {
            options.map = true
        }
        const files = Assistant.createFiles([].concat(glob), options)
        return this.apply(files, loaders, options)
    }
}

const man = new Assistant()
man.load('css', require('./processors/css'))
man.load('less', require('./processors/less'))
man.load('sass', require('./processors/sass'))
man.load('postcss', require('./processors/postcss'))
man.load('minify', require('./processors/minify'))
man.load('autoprefixer', require('./processors/autoprefixer'))
man.load('concat', require('./processors/concat'))
man.alias('scss', 'sass')

exports = module.exports = man
exports.Assistant = Assistant
exports.writeMap = sourceMapWrite
<|endoftext|>


<commit_before>// Load modules

var Http = require('http');
var NodeUtil = require('util');
var Hoek = require('hoek');

// Declare internals

var internals = {};

exports = module.exports = internals.Boom = function (/* (new Error) or (code, message) */) {

    Hoek.assert(this.constructor === internals.Boom, 'Error must be instantiated using new');

    Error.call(this);
    this.isBoom = true;

    this.response = {
        code: 0,
        payload: {},
        headers: {}
        // type: 'content-type'
    };

    if (arguments[0] instanceof Error) {

        // Error

        var error = arguments[0];

        this.data = error;
        this.response.code = error.code || 500;
        if (error.message) {
            this.message = error.message;
        }
    }
    else {
        // code, message

        var code = arguments[0];
        var message = arguments[1];

        Hoek.assert(!isNaN(parseFloat(code)) && isFinite(code) && code >= 400, 'First argument must be a number (400+)');

        this.response.code = code;
        if (message) {
            this.message = message;
        }
    }

    // Response format

    this.reformat();

    return this;
};

NodeUtil.inherits(internals.Boom, Error);

internals.Boom.prototype.reformat = function () {

    this.response.payload.code = this.response.code;
    this.response.payload.error = Http.STATUS_CODES[this.response.code] || 'Unknown';
    if (this.message) {
        this.response.payload.message = Hoek.escapeHtml(this.message);         // Prevent XSS from error message
    }
};

// Return custom keys added to the error root or response.payload

internals.Boom.prototype.decorations = function () {

    var decoration = {};

    var rootKeys = Object.keys(this);
    for (var i = 0, il = rootKeys.length; i < il; ++i) {
        var key = rootKeys[i];
        if (typeof this[key] !== 'function' &&
            key[0] !== '_' &&
            ['isBoom', 'response', 'message'].indexOf(key) === -1) {

            decoration[key] = this[key];
        }
    }

    var responseKeys = Object.keys(this.response.payload);
    for (i = 0, il = responseKeys.length; i < il; ++i) {
        var key = responseKeys[i];
        if (['code', 'error', 'message'].indexOf(key) === -1) {

            decoration.response = decoration.response || {};
            decoration.response[key] = this.response.payload[key];
        }
    }

    return decoration;
};

// 4xx Client Errors

internals.Boom.badRequest = function (message) {

    return new internals.Boom(400, message);
};

internals.Boom.unauthorized = function (message, scheme, attributes) {          // Or function (message, wwwAuthenticate[])

    var err = new internals.Boom(401, message);

    if (!scheme) {
        return err;
    }

    var wwwAuthenticate = '';
    var i = 0;
    var il = 0;

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

        // function (message, scheme, attributes)

        wwwAuthenticate = scheme;
        if (attributes) {
            var names = Object.keys(attributes);
            for (i = 0, il = names.length; i < il; ++i) {
                if (i) {
                    wwwAuthenticate += ',';
                }

                var value = attributes[names[i]];
                if (value === null ||
                    value === undefined) {              // Value can be zero

                    value = '';
                }
                wwwAuthenticate += ' ' + names[i] + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
            }
        }

        if (message) {
            if (attributes) {
                wwwAuthenticate += ',';
            }
            wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
        }
        else {
            err.isMissing = true;
        }
    }
    else {

        // function (message, wwwAuthenticate[])

        var wwwArray = scheme;
        for (i = 0, il = wwwArray.length; i < il; ++i) {
            if (i) {
                wwwAuthenticate += ', ';
            }

            wwwAuthenticate += wwwArray[i];
        }
    }

    err.response.headers['WWW-Authenticate'] = wwwAuthenticate;

    return err;
};

internals.Boom.forbidden = function (message) {

    return new internals.Boom(403, message);
};

internals.Boom.notFound = function (message) {

    return new internals.Boom(404, message);
};

internals.Boom.methodNotAllowed = function (message) {

    return new internals.Boom(405, message);
};

internals.Boom.notAcceptable = function (message) {

    return new internals.Boom(406, message);
};

internals.Boom.proxyAuthRequired = function (message) {

    return new internals.Boom(407, message);
};

internals.Boom.clientTimeout = function (message) {

    return new internals.Boom(408, message);
};

internals.Boom.conflict = function (message) {

    return new internals.Boom(409, message);
};

internals.Boom.resourceGone = function (message) {

    return new internals.Boom(410, message);
};

internals.Boom.lengthRequired = function (message) {

    return new internals.Boom(411, message);
};

internals.Boom.preconditionFailed = function (message) {

    return new internals.Boom(412, message);
};

internals.Boom.entityTooLarge = function (message) {

    return new internals.Boom(413, message);
};

internals.Boom.uriTooLong = function (message) {

    return new internals.Boom(414, message);
};

internals.Boom.unsupportedMediaType = function (message) {

    return new internals.Boom(415, message);
};

internals.Boom.rangeNotSatisfiable = function (message) {

    return new internals.Boom(416, message);
};

internals.Boom.expectationFailed = function (message) {

    return new internals.Boom(417, message);
};

// 5xx Server Errors

internals.Boom.internal = function (message, data) {

    var err = new internals.Boom(500, message);

    if (data && data.stack) {
        err.trace = data.stack.split('\n');
        err.outterTrace = Hoek.displayStack(1);
    }
    else {
        err.trace = Hoek.displayStack(1);
    }

    err.data = data;
    err.response.payload.message = 'An internal server error occurred';                     // Hide actual error from user

    return err;
};

internals.Boom.notImplemented = function (message) {

    return new internals.Boom(501, message);
};

internals.Boom.badGateway = function (message) {

    return new internals.Boom(502, message);
};

internals.Boom.serverTimeout = function (message) {

    return new internals.Boom(503, message);
};

internals.Boom.gatewayTimeout = function (message) {

    return new internals.Boom(504, message);
};

internals.Boom.passThrough = function (code, payload, contentType, headers) {

    var err = new internals.Boom(500, 'Pass-through');                                      // 500 code is only used to initialize

    err.data = {
        code: code,
        payload: payload,
        type: contentType
    };

    err.response.code = code;
    err.response.type = contentType;
    err.response.headers = headers;
    err.response.payload = payload;

    return err;
};

<commit_msg>Fix to allow subclassing of Boom<commit_after>// Load modules

var Http = require('http');
var NodeUtil = require('util');
var Hoek = require('hoek');

// Declare internals

var internals = {};

exports = module.exports = internals.Boom = function (/* (new Error) or (code, message) */) {

    Hoek.assert(this instanceof internals.Boom, 'Error must be instantiated using new');

    Error.call(this);
    this.isBoom = true;

    this.response = {
        code: 0,
        payload: {},
        headers: {}
        // type: 'content-type'
    };

    if (arguments[0] instanceof Error) {

        // Error

        var error = arguments[0];

        this.data = error;
        this.response.code = error.code || 500;
        if (error.message) {
            this.message = error.message;
        }
    }
    else {
        // code, message

        var code = arguments[0];
        var message = arguments[1];

        Hoek.assert(!isNaN(parseFloat(code)) && isFinite(code) && code >= 400, 'First argument must be a number (400+)');

        this.response.code = code;
        if (message) {
            this.message = message;
        }
    }

    // Response format

    this.reformat();

    return this;
};

NodeUtil.inherits(internals.Boom, Error);

internals.Boom.prototype.reformat = function () {

    this.response.payload.code = this.response.code;
    this.response.payload.error = Http.STATUS_CODES[this.response.code] || 'Unknown';
    if (this.message) {
        this.response.payload.message = Hoek.escapeHtml(this.message);         // Prevent XSS from error message
    }
};

// Return custom keys added to the error root or response.payload

internals.Boom.prototype.decorations = function () {

    var decoration = {};

    var rootKeys = Object.keys(this);
    for (var i = 0, il = rootKeys.length; i < il; ++i) {
        var key = rootKeys[i];
        if (typeof this[key] !== 'function' &&
            key[0] !== '_' &&
            ['isBoom', 'response', 'message'].indexOf(key) === -1) {

            decoration[key] = this[key];
        }
    }

    var responseKeys = Object.keys(this.response.payload);
    for (i = 0, il = responseKeys.length; i < il; ++i) {
        var key = responseKeys[i];
        if (['code', 'error', 'message'].indexOf(key) === -1) {

            decoration.response = decoration.response || {};
            decoration.response[key] = this.response.payload[key];
        }
    }

    return decoration;
};

// 4xx Client Errors

internals.Boom.badRequest = function (message) {

    return new internals.Boom(400, message);
};

internals.Boom.unauthorized = function (message, scheme, attributes) {          // Or function (message, wwwAuthenticate[])

    var err = new internals.Boom(401, message);

    if (!scheme) {
        return err;
    }

    var wwwAuthenticate = '';
    var i = 0;
    var il = 0;

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

        // function (message, scheme, attributes)

        wwwAuthenticate = scheme;
        if (attributes) {
            var names = Object.keys(attributes);
            for (i = 0, il = names.length; i < il; ++i) {
                if (i) {
                    wwwAuthenticate += ',';
                }

                var value = attributes[names[i]];
                if (value === null ||
                    value === undefined) {              // Value can be zero

                    value = '';
                }
                wwwAuthenticate += ' ' + names[i] + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
            }
        }

        if (message) {
            if (attributes) {
                wwwAuthenticate += ',';
            }
            wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
        }
        else {
            err.isMissing = true;
        }
    }
    else {

        // function (message, wwwAuthenticate[])

        var wwwArray = scheme;
        for (i = 0, il = wwwArray.length; i < il; ++i) {
            if (i) {
                wwwAuthenticate += ', ';
            }

            wwwAuthenticate += wwwArray[i];
        }
    }

    err.response.headers['WWW-Authenticate'] = wwwAuthenticate;

    return err;
};

internals.Boom.forbidden = function (message) {

    return new internals.Boom(403, message);
};

internals.Boom.notFound = function (message) {

    return new internals.Boom(404, message);
};

internals.Boom.methodNotAllowed = function (message) {

    return new internals.Boom(405, message);
};

internals.Boom.notAcceptable = function (message) {

    return new internals.Boom(406, message);
};

internals.Boom.proxyAuthRequired = function (message) {

    return new internals.Boom(407, message);
};

internals.Boom.clientTimeout = function (message) {

    return new internals.Boom(408, message);
};

internals.Boom.conflict = function (message) {

    return new internals.Boom(409, message);
};

internals.Boom.resourceGone = function (message) {

    return new internals.Boom(410, message);
};

internals.Boom.lengthRequired = function (message) {

    return new internals.Boom(411, message);
};

internals.Boom.preconditionFailed = function (message) {

    return new internals.Boom(412, message);
};

internals.Boom.entityTooLarge = function (message) {

    return new internals.Boom(413, message);
};

internals.Boom.uriTooLong = function (message) {

    return new internals.Boom(414, message);
};

internals.Boom.unsupportedMediaType = function (message) {

    return new internals.Boom(415, message);
};

internals.Boom.rangeNotSatisfiable = function (message) {

    return new internals.Boom(416, message);
};

internals.Boom.expectationFailed = function (message) {

    return new internals.Boom(417, message);
};

// 5xx Server Errors

internals.Boom.internal = function (message, data) {

    var err = new internals.Boom(500, message);

    if (data && data.stack) {
        err.trace = data.stack.split('\n');
        err.outterTrace = Hoek.displayStack(1);
    }
    else {
        err.trace = Hoek.displayStack(1);
    }

    err.data = data;
    err.response.payload.message = 'An internal server error occurred';                     // Hide actual error from user

    return err;
};

internals.Boom.notImplemented = function (message) {

    return new internals.Boom(501, message);
};

internals.Boom.badGateway = function (message) {

    return new internals.Boom(502, message);
};

internals.Boom.serverTimeout = function (message) {

    return new internals.Boom(503, message);
};

internals.Boom.gatewayTimeout = function (message) {

    return new internals.Boom(504, message);
};

internals.Boom.passThrough = function (code, payload, contentType, headers) {

    var err = new internals.Boom(500, 'Pass-through');                                      // 500 code is only used to initialize

    err.data = {
        code: code,
        payload: payload,
        type: contentType
    };

    err.response.code = code;
    err.response.type = contentType;
    err.response.headers = headers;
    err.response.payload = payload;

    return err;
};

<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';
var validator = require('./validator');
var Validator = validator.Validator;
var validationErrors = validator.validationErrors;

function createError(param, msg, value){
	return {
		param: param,
		msg: msg,
		value: value
	};
}

function koaValidator(options){
	return function *(next){
		validator.initialize();
		this.checkQuery = checkQuery;
		this.checkParams = checkParams;
		this.checkBody = checkBody;
		this.validationErrors = validationErrors;

		yield next;
	};
}

function checkQuery(param, msg){
	var check = {
		param: param,
		msg: msg,
		value: this.query[param]
	};
	return new Validator(check);
}

function checkParams(param, msg){
	var urlParam = this.url.split('/').slice(-1)[0];
	var check = {
		param: param,
		msg: msg,
		value: urlParam
	};
	return new Validator(check);
}

function checkBody(param, msg){
	var check = {
		param: param,
		msg: msg,
		value: this.request.body[param]
	};
	return new Validator(check);
}

module.exports = koaValidator;<commit_msg>Dont repeat yourself<commit_after>/*jslint node: true */
'use strict';
var validator = require('./validator');
var Validator = validator.Validator;
var validationErrors = validator.validationErrors;

function createError(param, msg, value){
	return {
		param: param,
		msg: msg,
		value: value
	};
}

function koaValidator(options){
	return function *(next){
		validator.initialize();
		this.checkQuery = checkQuery;
		this.checkParams = checkParams;
		this.checkBody = checkBody;
		this.validationErrors = validationErrors;

		yield next;
	};
}

function createValidator(param, msg, value){
	var check = {
		param: param,
		msg: msg,
		value: value
	};
	return new Validator(check);
}

function checkQuery(param, msg){
	return createValidator(param, msg, this.query[param]);
}

function checkParams(param, msg){
	return createValidator(param, msg, this.url.split('/').slice(-1)[0]);
}

function checkBody(param, msg){
	return createValidator(param, msg, this.request.body[param]);
}

module.exports = koaValidator;<|endoftext|>


<commit_before>//
// The beng-proxy JavaScript library.
//
// Author: Max Kellermann <mk@cm4all.com>
//

function beng_widget_uri(base_uri, session_id, frame, focus, mode, path) {
    var uri = base_uri + ";session=" + escape(session_id);
    if (focus != null) {
        uri += "&focus=" + escape(focus);
        if (mode == "frame" || mode == "proxy" || mode == "save")
            frame = focus;
        if (frame != null)
            uri += "&frame=" + escape(frame);
        if (mode == "proxy")
            uri += "&raw=1";
        if (mode == "save")
            uri += "&save=1";
        if (path != null) {
            var query_string = null;
            var qmark = path.indexOf("?");
            if (qmark >= 0) {
                query_string = path.substring(qmark);
                path = path.substring(0, qmark);
            }
            uri += "&path=" + escape(path);
            if (query_string != null)
                uri += query_string;
        }
    }
    return uri;
}

function beng_proxy_request() {
    var req = null;
    if (window.XMLHttpRequest) {
    	try {
            return new XMLHttpRequest();
        } catch(e) {
            return null;
        }
    } else if(window.ActiveXObject) {
       	try {
            return new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return null;
            }
        }
    } else {
        return null;
    }
}

function beng_proxy_make_uri(focus, path, mode) {
    return beng_widget_uri(this.uri, this.session, null, focus, mode, path);
}

function beng_proxy(session) {
    this.uri = window.location.href.replace(/[;?#].*/, "");
    this.session = session;

    this.make_uri = beng_proxy_make_uri;

    return this;
}

function beng_widget_get_widget(id) {
    var slash = id.indexOf("/");
    if (slash == -1)
        return this.widgets[id];
    var widget = this.widgets[id.substring(0, slash)];
    if (widget == null)
        return null;
    return widget.getWidget(id.substring(slash + 1));
}

function beng_root_widget(proxy) {
    this.parent = null;
    this.proxy = proxy;
    this.id = null;
    this.path = null;
    this.widgets = Array();

    this.getWidget = beng_widget_get_widget;

    return this;
}

function beng_widget_translate_uri(uri, mode) {
    if (this.path == null)
        return null;

    return this.proxy.make_uri(this.path, uri, mode);
}

function beng_widget_get(uri, onreadystatechange, mode) {
    if (mode == null)
        mode = "proxy";
    var url = this.translateURI(uri, mode);
    if (url == null)
        return null;
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = onreadystatechange;
    req.open("GET", url, onreadystatechange != null);
    req.send(null);
    return req;
}

function _beng_widget_post(uri, content_type, request_body,
                           onreadystatechange) {
    if (content_type == null || request_body == null)
        return null;
    var url = this.translateURI(uri, "proxy");
    if (url == null)
        return null;
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.setRequestHeader("Content-Type", content_type);
    req.onreadystatechange = onreadystatechange;
    req.open("POST", url, onreadystatechange != null);
    req.send(request_body);
    return req;
}

function beng_widget_reload_inline(widget, uri) {
    var req = widget.get(uri, function() {
            if (req == null)
                return;
            if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
                var element = widget.getElement();
                if (element != null)
                    element.innerHTML = req.responseText;
            }
        }, "frame");
    return req;
}

function beng_widget_reload_iframe(widget, iframe, uri) {
    var url = widget.translateURI(uri, true);
    if (url == null)
        return null;

    iframe.src = url;
    return null;
}

function beng_widget_reload(uri) {
    if (this.path == null)
        return null;

    var iframe_id = "beng_iframe___" + this.path.replace(/\//g, "__") + "__";
    var iframe = document.getElementById(iframe_id);
    if (iframe != null)
        return beng_widget_reload_iframe(this, iframe, uri);

    return beng_widget_reload_inline(this, uri);
}

function beng_widget(parent, id) {
    if (parent.parent == null)
        this.path = id;
    else if (parent.path == null)
        this.path = null;
    else
        this.path = parent.path + "/" + id;

    if (id != null)
        parent.widgets[id] = this;
    this.parent = parent;
    this.proxy = parent.proxy;
    this.id = id;
    this.widgets = Array();

    this.getWidget = beng_widget_get_widget;
    this.translateURI = beng_widget_translate_uri;
    this.get = beng_widget_get;
    this.post = _beng_widget_post;
    this.reload = beng_widget_reload;
    this.getElement = function() {
        if (this.path == null)
            return null;
        var id = "beng_widget___" + this.path.replace(/\//g, "__") + "__";
        return document.getElementById(id);
    };

    return this;
}

var _beng_onload_list = Array();

function _beng_onload() {
    var x;
    for (var x = 0; x < _beng_onload_list.length; ++x) {
        _beng_onload_list[x]();
    }
}

function beng_register_onload(onload) {
    _beng_onload_list.push(onload);
}
<commit_msg>check arguments<commit_after>//
// The beng-proxy JavaScript library.
//
// Author: Max Kellermann <mk@cm4all.com>
//

function beng_widget_uri(base_uri, session_id, frame, focus, mode, path) {
    if (base_uri == null ||
        (mode != null && mode != "focus" && mode != "frame" &&
         mode != "proxy" && mode != "save"))
        return null;

    var uri = base_uri + ";session=" + escape(session_id);
    if (focus != null) {
        uri += "&focus=" + escape(focus);
        if (mode == "frame" || mode == "proxy" || mode == "save")
            frame = focus;
        if (frame != null)
            uri += "&frame=" + escape(frame);
        if (mode == "proxy")
            uri += "&raw=1";
        if (mode == "save")
            uri += "&save=1";
        if (path != null) {
            var query_string = null;
            var qmark = path.indexOf("?");
            if (qmark >= 0) {
                query_string = path.substring(qmark);
                path = path.substring(0, qmark);
            }
            uri += "&path=" + escape(path);
            if (query_string != null)
                uri += query_string;
        }
    }
    return uri;
}

function beng_proxy_request() {
    var req = null;
    if (window.XMLHttpRequest) {
    	try {
            return new XMLHttpRequest();
        } catch(e) {
            return null;
        }
    } else if(window.ActiveXObject) {
       	try {
            return new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return null;
            }
        }
    } else {
        return null;
    }
}

function beng_proxy_make_uri(focus, path, mode) {
    return beng_widget_uri(this.uri, this.session, null, focus, mode, path);
}

function beng_proxy(session) {
    this.uri = window.location.href.replace(/[;?#].*/, "");
    this.session = session;

    this.make_uri = beng_proxy_make_uri;

    return this;
}

function beng_widget_get_widget(id) {
    var slash = id.indexOf("/");
    if (slash == -1)
        return this.widgets[id];
    var widget = this.widgets[id.substring(0, slash)];
    if (widget == null)
        return null;
    return widget.getWidget(id.substring(slash + 1));
}

function beng_root_widget(proxy) {
    this.parent = null;
    this.proxy = proxy;
    this.id = null;
    this.path = null;
    this.widgets = Array();

    this.getWidget = beng_widget_get_widget;

    return this;
}

function beng_widget_translate_uri(uri, mode) {
    if (this.path == null)
        return null;

    return this.proxy.make_uri(this.path, uri, mode);
}

function beng_widget_get(uri, onreadystatechange, mode) {
    if (mode == null)
        mode = "proxy";
    var url = this.translateURI(uri, mode);
    if (url == null)
        return null;
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = onreadystatechange;
    req.open("GET", url, onreadystatechange != null);
    req.send(null);
    return req;
}

function _beng_widget_post(uri, content_type, request_body,
                           onreadystatechange) {
    if (content_type == null || request_body == null)
        return null;
    var url = this.translateURI(uri, "proxy");
    if (url == null)
        return null;
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.setRequestHeader("Content-Type", content_type);
    req.onreadystatechange = onreadystatechange;
    req.open("POST", url, onreadystatechange != null);
    req.send(request_body);
    return req;
}

function beng_widget_reload_inline(widget, uri) {
    var req = widget.get(uri, function() {
            if (req == null)
                return;
            if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
                var element = widget.getElement();
                if (element != null)
                    element.innerHTML = req.responseText;
            }
        }, "frame");
    return req;
}

function beng_widget_reload_iframe(widget, iframe, uri) {
    var url = widget.translateURI(uri, true);
    if (url == null)
        return null;

    iframe.src = url;
    return null;
}

function beng_widget_reload(uri) {
    if (this.path == null)
        return null;

    var iframe_id = "beng_iframe___" + this.path.replace(/\//g, "__") + "__";
    var iframe = document.getElementById(iframe_id);
    if (iframe != null)
        return beng_widget_reload_iframe(this, iframe, uri);

    return beng_widget_reload_inline(this, uri);
}

function beng_widget(parent, id) {
    if (parent.parent == null)
        this.path = id;
    else if (parent.path == null)
        this.path = null;
    else
        this.path = parent.path + "/" + id;

    if (id != null)
        parent.widgets[id] = this;
    this.parent = parent;
    this.proxy = parent.proxy;
    this.id = id;
    this.widgets = Array();

    this.getWidget = beng_widget_get_widget;
    this.translateURI = beng_widget_translate_uri;
    this.get = beng_widget_get;
    this.post = _beng_widget_post;
    this.reload = beng_widget_reload;
    this.getElement = function() {
        if (this.path == null)
            return null;
        var id = "beng_widget___" + this.path.replace(/\//g, "__") + "__";
        return document.getElementById(id);
    };

    return this;
}

var _beng_onload_list = Array();

function _beng_onload() {
    var x;
    for (var x = 0; x < _beng_onload_list.length; ++x) {
        _beng_onload_list[x]();
    }
}

function beng_register_onload(onload) {
    _beng_onload_list.push(onload);
}
<|endoftext|>


<commit_before>define(function(require, exports) {
    'use strict';

    var _ = require('lodash');
    // var _ = require('underscore');

    //
    // Utility library shim (Underscore or Lodash)
    //
    if (typeof (_.flow) !== 'function') {
        if (typeof (_.mixin) === 'function') {// Underscore
            _.mixin({
                complement: _.negate
            });
        }
    } else {// Lodash
        _.any = _.some;
        _.complement = _.negate;
        _.compose = _.flowRight;
    }
    //
    // Polyfills
    //
    // Math.sign = Math.sign || function(x) {
    //     x = +x;
    //     if (x === 0 || isNaN(x)) {
    //         return x;
    //     }
    //     return x > 0 ? 1 : -1;
    // };
    // Math.trunc = Math.trunc || function(x) {
    //     return Math.sign(x) * _.compose(Math.floor, Math.abs)(x);
    // };
    // if (!Array.prototype.findIndex) {
    //     Array.prototype.findIndex = function(predicate) {
    //         if (this === null) {
    //             throw new TypeError('Array.prototype.findIndex called on null or undefined');
    //         }
    //         if (typeof predicate !== 'function') {
    //             throw new TypeError('predicate must be a function');
    //         }
    //         var list = Object(this);
    //         var length = list.length;
    //         var thisArg = arguments[1];
    //         var value;
    //         for (var i = 0; i < length; i++) {
    //             value = list[i];
    //             if (predicate.call(thisArg, value, i, list)) {
    //                 return i;
    //             }
    //         }
    //         return -1;
    //     };
    // }

    exports.common = require('./common');
    exports.geodetic = require('./geodetic');
});
<commit_msg>Un-commented polyfills and added istanbul ignore to index.js<commit_after>/* istanbul ignore next */
define(function(require, exports) {
    'use strict';

    var _ = require('lodash');
    // var _ = require('underscore');

    //
    // Utility library shim (Underscore or Lodash)
    //
    if (typeof (_.flow) !== 'function') {
        if (typeof (_.mixin) === 'function') {// Underscore
            _.mixin({
                complement: _.negate
            });
        }
    } else {// Lodash
        _.any = _.some;
        _.complement = _.negate;
        _.compose = _.flowRight;
    }
    //
    // Polyfills
    //
    Math.sign = Math.sign || function(x) {
        x = +x;
        if (x === 0 || isNaN(x)) {
            return x;
        }
        return x > 0 ? 1 : -1;
    };
    Math.trunc = Math.trunc || function(x) {
        return Math.sign(x) * _.compose(Math.floor, Math.abs)(x);
    };
    if (!Array.prototype.findIndex) {
        Array.prototype.findIndex = function(predicate) {
            if (this === null) {
                throw new TypeError('Array.prototype.findIndex called on null or undefined');
            }
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }
            var list = Object(this);
            var length = list.length;
            var thisArg = arguments[1];
            var value;
            for (var i = 0; i < length; i++) {
                value = list[i];
                if (predicate.call(thisArg, value, i, list)) {
                    return i;
                }
            }
            return -1;
        };
    }

    exports.common = require('./common');
    exports.geodetic = require('./geodetic');
});
<|endoftext|>


<commit_before>import { NativeModules, View } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const TrackPlayer = NativeModules.TrackPlayerModule;

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function updateOptions(data) {
    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    // Resolve the URL for each track
    for(let i = 0; i < tracks.length; i++) {
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// Cast States
module.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE;
module.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED;
module.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING;
module.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED;

// Basics
module.exports.onReady = TrackPlayer.onReady;
module.exports.updateOptions = updateOptions;

// Player Basics
module.exports.setupPlayer = TrackPlayer.setupPlayer;
module.exports.destroy = TrackPlayer.destroy;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;

// Cast Getters
module.exports.getCastState = TrackPlayer.getCastState;

// Components
if(TrackPlayer.CAST_SUPPORT_AVAILABLE) {
    module.exports.CastButton = require('./CastButton.js');
} else {
    module.exports.CastButton = View; // Cast Unavailable
}
<commit_msg>Fixed CastButton not being found<commit_after>import { NativeModules, View } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const TrackPlayer = NativeModules.TrackPlayerModule;

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function updateOptions(data) {
    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    // Resolve the URL for each track
    for(let i = 0; i < tracks.length; i++) {
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// Cast States
module.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE;
module.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED;
module.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING;
module.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED;

// Basics
module.exports.onReady = TrackPlayer.onReady;
module.exports.updateOptions = updateOptions;

// Player Basics
module.exports.setupPlayer = TrackPlayer.setupPlayer;
module.exports.destroy = TrackPlayer.destroy;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;

// Cast Getters
module.exports.getCastState = TrackPlayer.getCastState;

// Components
if(TrackPlayer.CAST_SUPPORT_AVAILABLE) {
    module.exports.CastButton = require('./CastButton');
} else {
    module.exports.CastButton = View; // Cast Unavailable
}
<|endoftext|>


<commit_before>var bb = bb || {};

bb.BudgetApp = function(pageDom) {
  this.budget = new bb.Budget();
  this.dataManager = new bb.DataManager(new bb.DataStore());

  this.expense = new bb.Transaction();
  this.income = new bb.Transaction();

  this.page = new bb.Page(pageDom);
  this.routes = {
    'accounts': {
      'tagName': 'bb-page-accounts'
    },
    'account/new': {
      'tagName': 'bb-page-account-new'
    },
    'budget/view': {
      'tagName': 'bb-page-budget'
    },
    'category/new': {
      'tagName': 'bb-page-category-new'
    },
    'expense/account': {
      'tagName': 'bb-page-expense-account',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/amount': {
      'tagName': 'bb-page-expense-amount',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/category': {
      'tagName': 'bb-page-expense-category',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/summary': {
      'tagName': 'bb-page-expense-summary',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/when': {
      'tagName': 'bb-page-expense-when',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/who': {
      'tagName': 'bb-page-expense-who',
      'opts': {
        'transaction': this.expense
      }
    },
    'history/account': {
      'tagName': 'bb-page-history-account'
    },
    'history/all': {
      'tagName': 'bb-page-history-all'
    },
    'history/category': {
      'tagName': 'bb-page-history-category'
    },
    'history/search': {
      'tagName': 'bb-page-history-search'
    },
    'income/account': {
      'tagName': 'bb-page-income-account',
      'opts': {
        'transaction': this.income
      }
    },
    'income/amount': {
      'tagName': 'bb-page-income-amount',
      'opts': {
        'transaction': this.income
      }
    },
    'income/category': {
      'tagName': 'bb-page-income-category',
      'opts': {
        'transaction': this.income
      }
    },
    'income/summary': {
      'tagName': 'bb-page-income-summary',
      'opts': {
        'transaction': this.income
      }
    },
    'income/when': {
      'tagName': 'bb-page-income-when',
      'opts': {
        'transaction': this.income
      }
    },
    'income/who': {
      'tagName': 'bb-page-income-who',
      'opts': {
        'transaction': this.income
      }
    }
  };
  route(this.route.bind(this));
};

bb.BudgetApp.prototype.route = function(page, subPage, id) {
  if ( ! page) {
    route('budget');
    return;
  }

  if ((page === 'budget') && ! subPage) {
    subPage = 'view';
  }

  var path = (subPage ? page + '/' + subPage : page);

  var routeData = this.routes[path];
  if (routeData != undefined) {
    routeData.opts = routeData.opts || {};
    routeData.opts.id = id;
    routeData.opts.dm = this.dataManager;
    try {

      console.log(routeData); // TEMP

      this.page.showTag(routeData.tagName, routeData.opts);
    } catch (e) {
      console.log(e);
      this.page.showTag('bb-page-error', { 'error': e });
    }
  } else {
    this.page.showTag('bb-page-not-found', { 'route': path });
  }
};
<commit_msg>Remove debug code.<commit_after>var bb = bb || {};

bb.BudgetApp = function(pageDom) {
  this.budget = new bb.Budget();
  this.dataManager = new bb.DataManager(new bb.DataStore());

  this.expense = new bb.Transaction();
  this.income = new bb.Transaction();

  this.page = new bb.Page(pageDom);
  this.routes = {
    'accounts': {
      'tagName': 'bb-page-accounts'
    },
    'account/new': {
      'tagName': 'bb-page-account-new'
    },
    'budget/view': {
      'tagName': 'bb-page-budget'
    },
    'category/new': {
      'tagName': 'bb-page-category-new'
    },
    'expense/account': {
      'tagName': 'bb-page-expense-account',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/amount': {
      'tagName': 'bb-page-expense-amount',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/category': {
      'tagName': 'bb-page-expense-category',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/summary': {
      'tagName': 'bb-page-expense-summary',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/when': {
      'tagName': 'bb-page-expense-when',
      'opts': {
        'transaction': this.expense
      }
    },
    'expense/who': {
      'tagName': 'bb-page-expense-who',
      'opts': {
        'transaction': this.expense
      }
    },
    'history/account': {
      'tagName': 'bb-page-history-account'
    },
    'history/all': {
      'tagName': 'bb-page-history-all'
    },
    'history/category': {
      'tagName': 'bb-page-history-category'
    },
    'history/search': {
      'tagName': 'bb-page-history-search'
    },
    'income/account': {
      'tagName': 'bb-page-income-account',
      'opts': {
        'transaction': this.income
      }
    },
    'income/amount': {
      'tagName': 'bb-page-income-amount',
      'opts': {
        'transaction': this.income
      }
    },
    'income/category': {
      'tagName': 'bb-page-income-category',
      'opts': {
        'transaction': this.income
      }
    },
    'income/summary': {
      'tagName': 'bb-page-income-summary',
      'opts': {
        'transaction': this.income
      }
    },
    'income/when': {
      'tagName': 'bb-page-income-when',
      'opts': {
        'transaction': this.income
      }
    },
    'income/who': {
      'tagName': 'bb-page-income-who',
      'opts': {
        'transaction': this.income
      }
    }
  };
  route(this.route.bind(this));
};

bb.BudgetApp.prototype.route = function(page, subPage, id) {
  if ( ! page) {
    route('budget');
    return;
  }

  if ((page === 'budget') && ! subPage) {
    subPage = 'view';
  }

  var path = (subPage ? page + '/' + subPage : page);

  var routeData = this.routes[path];
  if (routeData != undefined) {
    routeData.opts = routeData.opts || {};
    routeData.opts.id = id;
    routeData.opts.dm = this.dataManager;
    try {
      this.page.showTag(routeData.tagName, routeData.opts);
    } catch (e) {
      console.log(e);
      this.page.showTag('bb-page-error', { 'error': e });
    }
  } else {
    this.page.showTag('bb-page-not-found', { 'route': path });
  }
};
<|endoftext|>


<commit_before>var xtend = require('xtend');
var jwt = require('jsonwebtoken');
var UnauthorizedError = require('./UnauthorizedError');

function noQsMethod(options) {
  return function (socket) {
    var server = this;

    if (!server.$emit) {
      //then is socket.io 1.0
      var Namespace = Object.getPrototypeOf(server.server.sockets).constructor;
      if (!~Namespace.events.indexOf('authenticated')) {
        Namespace.events.push('authenticated');
      }
    }

    var auth_timeout = setTimeout(function () {
      socket.emit('error', new UnauthorizedError('request_expiration', 'Token wasn\'t received on time'));
      socket.disconnect('unauthorized');
    }, options.timeout || 5000);

    socket.on('authenticate', function (data) {
      clearTimeout(auth_timeout);
      jwt.verify(data.token, options.secret, options, function(err, decoded) {
        if (err) {
          socket.emit('error', new UnauthorizedError('invalid_token', err));
          return socket.disconnect('unauthorized');
        }

        socket.decoded_token = decoded;
        socket.emit('authenticated');
        if (server.$emit) {
          server.$emit('authenticated', socket);
        } else {
          server.server.sockets.emit('authenticated', socket);
        }
      });
    });

  };
}

function authorize(options, onConnection) {
  var defaults = {
    success: function(data, accept){
      if (data.request) {
        accept();
      } else {
        accept(null, true);
      }
    },
    fail: function(error, data, accept){
      if (data.request) {
        accept(error);
      } else {
        accept(null, false);
      }
    }
  };

  var auth = xtend(defaults, options);

  if (!options.handshake) {
    return noQsMethod(options);
  }

  return function(data, accept){
    var token, error;
    var req = data.request || data;
    var authorization_header = (req.headers || {}).authorization;

    if (authorization_header) {
      var parts = authorization_header.split(' ');
      if (parts.length == 2) {
        var scheme = parts[0],
          credentials = parts[1];

        if (/^Bearer$/i.test(scheme)) {
          token = credentials;
        }
      } else {
        error = new UnauthorizedError('credentials_bad_format', {
          message: 'Format is Authorization: Bearer [token]'
        });
        return auth.fail(error, data, accept);
      }
    }

    //get the token from query string
    if (req._query && req._query.token) {
      token = req._query.token;
    }
    else if (req.query && req.query.token) {
      token = req.query.token;
    }

    if (!token) {
      error = new UnauthorizedError('credentials_required', {
        message: 'No Authorization header was found'
      });
      return auth.fail(error, data, accept);
    }

    jwt.verify(token, options.secret, options, function(err, decoded) {

      if (err) {
        error = new UnauthorizedError('invalid_token', err);
        return auth.fail(error, data, accept);
      }

      data.decoded_token = decoded;

      auth.success(data, accept);
    });
  };
}

exports.authorize = authorize;
<commit_msg>Make .disconnect() call asynchronous to allow client to receive error message.<commit_after>var xtend = require('xtend');
var jwt = require('jsonwebtoken');
var UnauthorizedError = require('./UnauthorizedError');

function noQsMethod(options) {
  return function (socket) {
    var server = this;

    if (!server.$emit) {
      //then is socket.io 1.0
      var Namespace = Object.getPrototypeOf(server.server.sockets).constructor;
      if (!~Namespace.events.indexOf('authenticated')) {
        Namespace.events.push('authenticated');
      }
    }

    var auth_timeout = setTimeout(function () {
      socket.disconnect('unauthorized');
    }, options.timeout || 5000);

    socket.on('authenticate', function (data) {
      clearTimeout(auth_timeout);
      jwt.verify(data.token, options.secret, options, function(err, decoded) {
        if (err) {
          socket.emit('unauthorized', err, function() {
            socket.disconnect('unauthorized');
          });
          return; // stop logic, socket will be close on next tick
        }

        socket.decoded_token = decoded;
        socket.emit('authenticated');
        if (server.$emit) {
          server.$emit('authenticated', socket);
        } else {
          server.server.sockets.emit('authenticated', socket);
        }
      });
    });

  };
}

function authorize(options, onConnection) {
  var defaults = {
    success: function(data, accept){
      if (data.request) {
        accept();
      } else {
        accept(null, true);
      }
    },
    fail: function(error, data, accept){
      if (data.request) {
        accept(error);
      } else {
        accept(null, false);
      }
    }
  };

  var auth = xtend(defaults, options);

  if (!options.handshake) {
    return noQsMethod(options);
  }

  return function(data, accept){
    var token, error;
    var req = data.request || data;
    var authorization_header = (req.headers || {}).authorization;

    if (authorization_header) {
      var parts = authorization_header.split(' ');
      if (parts.length == 2) {
        var scheme = parts[0],
          credentials = parts[1];

        if (/^Bearer$/i.test(scheme)) {
          token = credentials;
        }
      } else {
        error = new UnauthorizedError('credentials_bad_format', {
          message: 'Format is Authorization: Bearer [token]'
        });
        return auth.fail(error, data, accept);
      }
    }

    //get the token from query string
    if (req._query && req._query.token) {
      token = req._query.token;
    }
    else if (req.query && req.query.token) {
      token = req.query.token;
    }

    if (!token) {
      error = new UnauthorizedError('credentials_required', {
        message: 'No Authorization header was found'
      });
      return auth.fail(error, data, accept);
    }

    jwt.verify(token, options.secret, options, function(err, decoded) {

      if (err) {
        error = new UnauthorizedError('invalid_token', err);
        return auth.fail(error, data, accept);
      }

      data.decoded_token = decoded;

      auth.success(data, accept);
    });
  };
}

exports.authorize = authorize;
<|endoftext|>


<commit_before>//Open a chromosome
jviz.modules.ideogram.prototype.chromosome = function(id)
{
  //Check for undefined
  if(typeof id === 'undefined'){ return this; }

  //Check for integer
  if(typeof id === 'number')
  {
    //Save the chromosome
    this._chromosome.now = id;

    //Draw and exit
    return this.draw();
  }

  //Find the chromosome name
  for(var i = 0; i < this._genome.chromosomes.length; i++)
  {
    //Get the chromosome
    var chr = this._genome.chromosomes[i];

    //Check the chromosome name
    if(chr.name !== id){ continue; }

    //Save the actual chromosome
    this._chromosome.now = i;

    //Draw the chromosome
    return this.draw();
  }

  //Display error
  jviz.console.error('Chromosome ' + id + ' not found', null);

  //Exit
  return this;
};

//Draw a chromosome
jviz.modules.ideogram.prototype.chromosomeDraw = function()
{
  //Show loading
  this.loading(true);

  //Display in console
  console.log('Draw chromosome ' + this._chromosome.now);

  //Check the actual chromosome
  if(this._chromosome.now < 0){ return this.chromosomeEmpty(); }

  //Clear the chromosome view
  this.chromosomeClear();

  //Get the draw zone
  var draw = this._chromosome.draw;

  //Get the middle canvas
  var canvas = this._canvas.el.layer(this._chromosome.draw.layer);

  //Get the chromosome info
  var chr = this._genome.chromosomes[this._chromosome.now];

  //Save the chromosome scale
  this._chromosome.scale = draw.width / chr.length;

  //Save the chromosome width
  this._chromosome.width = draw.width;

  //Calculate the chromosome position x
  this._chromosome.posx = draw.margin.left;

  //Calculate the chromosome position y
  this._chromosome.posy = draw.top + draw.margin.top + (draw.height - this._chromosome.height) / 2;

  //Get the chromosome x point
  var chr_x = this._chromosome.posx;

  //Get the chromosome y point
  var chr_y = this._chromosome.posy;

  //Get the chromosome width
  var chr_width = this._chromosome.width;

  //Get the chromosome height
  var chr_height = this._chromosome.height;

  //Get the chromosome radius
  var chr_radius = this._chromosome.radius;

  //Draw the chromosome rectangle
  canvas.Rect({ x: chr_x, y: chr_y, width: chr_width, height: chr_height, radius: chr_radius });

  //Chromosome rectangle fill
  canvas.Fill({ color: this._fill.chromosome.color, opacity: this._fill.chromosome.opacity });

  //Check for draw the centromere
  if(typeof chr.centromere !== 'undefined')
  {
    //Calculate the centromere start point
    var cent_start = Math.floor(chr.centromere[0] * this._chromosome.scale);

    //Calculate the centromere end
    var cent_end = Math.floor(chr.centromere[1] * this._chromosome.scale);

    //Calculate the centromere width
    var cent_width = Math.abs(cent_end - cent_start);

    //Clear the centromere rectangle
    canvas.Clear({ x: cent_start, y: chr_y, width: cent_width, height: chr_height });

    //Create the centromere points
    var p = [];

    //Add the centromere top start
    p.push([ cent_start, chr_y ]);

    //Add the centromere top middle
    p.push([ cent_start + cent_width/2, chr_y + chr_height/2 ]);

    //Add the centromere top end
    p.push([ cent_end, chr_y ]);

    //Add the centromere bottom end
    p.push([ cent_end, chr_y + chr_height ]);

    //Add the centromere bottom middle
    p.push([ cent_start + cent_width/2, chr_y + chr_height/2 ]);

    //Add the centromere bottom start
    p.push([ cent_start, chr_y + chr_height ]);

    //Add the lines
    canvas.Line(p);

    //Add the fill
    canvas.Fill({ color: this._fill.centromere.color, opacity: this._fill.centromere.opacity });
  }

  //Calculate the regions label position y
  this._chromosome.regions.label.posy = this._chromosome.posy + this._chromosome.height + this._chromosome.regions.label.margin;

  //Get the regions for this chromosome
  var regions = (typeof this._regions.list[chr.name] === 'undefined') ? [] : this._regions.list[chr.name];

  //Initialize the chromosome regions positions list
  this._chromosome.regions.list = [];

  //Read all the regions
  for(var i = 0; i < regions.length; i++)
  {
    //Get the region
    var region = regions[i];

    //Calculate the start position
    var rect_start = this._chromosome.posx + region.start * this._chromosome.scale;

    //Calculate the end position
    var rect_end = this._chromosome.posx + region.end * this._chromosome.scale;

    //Calculate the width
    var rect_width = Math.max(1, rect_end - rect_start);

    //Save the rectangle height
    var rect_height = this._chromosome.height;

    //Save the Y position
    var rect_y = this._chromosome.posy;

    //Draw the region
    canvas.Rect({ x: rect_start, y: rect_y, width: rect_width, height: rect_height });

    //Fill the region
    canvas.Fill({ color: this._chromosome.regions.fill, opacity: this._chromosome.regions.opacity });

    //Save the region start coordinate
    region.pstart = rect_start;

    //Save the region end coordinate
    region.pend = rect_end;

    //Save the middle point
    region.pmiddle = (region.pstart + region.pend) / 2;

    //Save the region position
    this._chromosome.regions.list.push(region);

    //Check for add the preview label
    if(this._chromosome.regions.preview.active === true)
    {
      //Add the preview label
      this.regionsDrawLabel(this._chromosome.regions.preview.layer, i, this._chromosome.regions.preview.opacity);
    }

    //Check for draw the marks preview
    if(this._marks.chromosomes.preview.active === true)
    {
      //Draw the mark this.marks.chromosomes.opacity
      //this.ChromosomeDrawMarksIndex(canvas_down, i, this._marks.chromosomes.preview.opacity);
    }
  }

  //Calculate the utils position y start
  this._chromosome.utils.posy_start = this._chromosome.posy;

  //Calculate the utils position y end
  this._chromosome.utils.posy_end = this._chromosome.posy + this._chromosome.height;

  //Calculate the up zone
  this._chromosome.utils.up = this._chromosome.posy;

  //Calculate the down zone
  this._chromosome.utils.down = this._height - this._chromosome.utils.posy_end;

  //Calculate the position coordinate y
  this._chromosome.position.posy = this._chromosome.posy - this._chromosome.position.margin;

  //Reset the hover region
  this._chromosome.regions.label.hover = -1;

  //Hide the loading
  this.loading(false);

  //Update the foot content
  this._panel.el.footContent(this._chromosome.foot.replace('{c}', chr.name).replace('{r}', regions.length));

  //Exit
  return this;
};

//Check over chromosome zone
jviz.modules.ideogram.prototype.chromosomeOver = function(x, y)
{
  //Check the x coordinate
  if(x < this._chromosome.posx || this._chromosome.posx + this._chromosome.width < x){ return false; }

  //Check the y coordinate
  //if(y < this._chromosome.posy || this._chromosome.posy + this._chromosome.height < y){ return false; }

  //Return true
  return true;
};

//Chromosome click
jviz.modules.ideogram.prototype.chromosomeClick = function(x, y)
{
  //Check for click over the zone
  if(this.chromosomeOver(x, y) === false){ return; }

  //Find the region
  var index = this.regionOver(x, y);

  //Check for undefined region
  if(index === -1){ return; }

  //Get the chromosome info
  var chr = this._genome.chromosomes[this._chromosome.now];

  //Get the region info
  var region = this._chromosome.regions.list[index];

  //Call the event
  this._events.emit('click:region', region.name, chr.name, region.start, region.end, index);
};

//Chromosome move
jviz.modules.ideogram.prototype.chromosomeMove = function(x, y)
{
  //Check if is over the zone
  if(this.chromosomeOver(x, y) === false){ return; }

  //Draw the position
  this.positionDraw(x, y);

  //Check the region
  var index = this.regionOver(x, y);

  //Check for different index
  if(index === this._chromosome.regions.label.hover){ return; }

  //Update the index
  this._chromosome.regions.label.hover = index;

  //Clear the canvas
  //canvas.Clear({ x: 0, y: this.chromosome.utils.posy_end, width: this.width, height: this.chromosome.utils.down });
  this._canvas.el.layer(this._chromosome.regions.label.layer).Clear();

  //Check for null index
  if(index < 0)
  {
    //Remove the pointer cursor
    jviz.cursor.remove('pointer');

    //Exit
    return;
  }

  //Draw the region
  this.regionsDrawLabel(this._chromosome.regions.label.layer, index, this._chromosome.regions.label.opacity);

  //Draw the marks
  //this.ChromosomeDrawMarksIndex(canvas, index, this.marks.chromosomes.opacity);

  //Add the pointer cursor
  jviz.cursor.set('pointer');
};

//Chromosome leave
jviz.modules.ideogram.prototype.chromosomeLeave = function()
{

};

//Draw an empty chromosome
jviz.modules.ideogram.prototype.chromosomeEmpty = function()
{
  //Clear the chromosome view
  this.chromosomeClear();

  //Continue
  return this;
};

//Clear the chromosome panel
jviz.modules.ideogram.prototype.chromosomeClear = function()
{
  //Get the draw
  var draw = this._chromosome.draw;

  //Read all layers
  for(var i = 0; i < this._canvas.layers; i++)
  {
    //Get the canvas layer
    var canvas = this._canvas.el.layer(i);

    //Clear the canvas
    canvas.Clear({ x: 0, y: draw.top, width: draw.real_width, height: draw.real_height });
  }

  //Exit
  return this;
};
<commit_msg>js/chromosome.js: minor update<commit_after>//Open a chromosome
jviz.modules.ideogram.prototype.chromosome = function(id)
{
  //Check for undefined
  if(typeof id === 'undefined'){ return this; }

  //Check for integer
  if(typeof id === 'number')
  {
    //Save the chromosome
    this._chromosome.now = id;

    //Draw and exit
    return this.draw();
  }

  //Find the chromosome name
  for(var i = 0; i < this._genome.chromosomes.length; i++)
  {
    //Get the chromosome
    var chr = this._genome.chromosomes[i];

    //Check the chromosome name
    if(chr.name !== id){ continue; }

    //Save the actual chromosome
    this._chromosome.now = i;

    //Draw the chromosome
    return this.draw();
  }

  //Display error
  jviz.console.error('Chromosome ' + id + ' not found', null);

  //Exit
  return this;
};

//Draw a chromosome
jviz.modules.ideogram.prototype.chromosomeDraw = function()
{
  //Show loading
  this.loading(true);

  //Display in console
  console.log('Draw chromosome ' + this._chromosome.now);

  //Check the actual chromosome
  if(this._chromosome.now < 0){ return this.chromosomeEmpty(); }

  //Get the draw zone
  var draw = this._chromosome.draw;

  //Get the middle canvas
  var canvas = this._canvas.el.layer(this._chromosome.draw.layer);

  //Clear the chromosome view
  this.chromosomeClear(this._chromosome.draw.layer);

  //Get the chromosome info
  var chr = this._genome.chromosomes[this._chromosome.now];

  //Save the chromosome scale
  this._chromosome.scale = draw.width / chr.length;

  //Save the chromosome width
  this._chromosome.width = draw.width;

  //Calculate the chromosome position x
  this._chromosome.posx = draw.margin.left;

  //Calculate the chromosome position y
  this._chromosome.posy = draw.top + draw.margin.top + (draw.height - this._chromosome.height) / 2;

  //Get the chromosome x point
  var chr_x = this._chromosome.posx;

  //Get the chromosome y point
  var chr_y = this._chromosome.posy;

  //Get the chromosome width
  var chr_width = this._chromosome.width;

  //Get the chromosome height
  var chr_height = this._chromosome.height;

  //Get the chromosome radius
  var chr_radius = this._chromosome.radius;

  //Draw the chromosome rectangle
  canvas.Rect({ x: chr_x, y: chr_y, width: chr_width, height: chr_height, radius: chr_radius });

  //Chromosome rectangle fill
  canvas.Fill({ color: this._fill.chromosome.color, opacity: this._fill.chromosome.opacity });

  //Check for draw the centromere
  if(typeof chr.centromere !== 'undefined')
  {
    //Calculate the centromere start point
    var cent_start = Math.floor(chr.centromere[0] * this._chromosome.scale);

    //Calculate the centromere end
    var cent_end = Math.floor(chr.centromere[1] * this._chromosome.scale);

    //Calculate the centromere width
    var cent_width = Math.abs(cent_end - cent_start);

    //Clear the centromere rectangle
    canvas.Clear({ x: cent_start, y: chr_y, width: cent_width, height: chr_height });

    //Create the centromere points
    var p = [];

    //Add the centromere top start
    p.push([ cent_start, chr_y ]);

    //Add the centromere top middle
    p.push([ cent_start + cent_width/2, chr_y + chr_height/2 ]);

    //Add the centromere top end
    p.push([ cent_end, chr_y ]);

    //Add the centromere bottom end
    p.push([ cent_end, chr_y + chr_height ]);

    //Add the centromere bottom middle
    p.push([ cent_start + cent_width/2, chr_y + chr_height/2 ]);

    //Add the centromere bottom start
    p.push([ cent_start, chr_y + chr_height ]);

    //Add the lines
    canvas.Line(p);

    //Add the fill
    canvas.Fill({ color: this._fill.centromere.color, opacity: this._fill.centromere.opacity });
  }

  //Calculate the regions label position y
  this._chromosome.regions.label.posy = this._chromosome.posy + this._chromosome.height + this._chromosome.regions.label.margin;

  //Get the regions for this chromosome
  var regions = (typeof this._regions.list[chr.name] === 'undefined') ? [] : this._regions.list[chr.name];

  //Initialize the chromosome regions positions list
  this._chromosome.regions.list = [];

  //Read all the regions
  for(var i = 0; i < regions.length; i++)
  {
    //Get the region
    var region = regions[i];

    //Calculate the start position
    var rect_start = this._chromosome.posx + region.start * this._chromosome.scale;

    //Calculate the end position
    var rect_end = this._chromosome.posx + region.end * this._chromosome.scale;

    //Calculate the width
    var rect_width = Math.max(1, rect_end - rect_start);

    //Save the rectangle height
    var rect_height = this._chromosome.height;

    //Save the Y position
    var rect_y = this._chromosome.posy;

    //Draw the region
    canvas.Rect({ x: rect_start, y: rect_y, width: rect_width, height: rect_height });

    //Fill the region
    canvas.Fill({ color: this._chromosome.regions.fill, opacity: this._chromosome.regions.opacity });

    //Save the region start coordinate
    region.pstart = rect_start;

    //Save the region end coordinate
    region.pend = rect_end;

    //Save the middle point
    region.pmiddle = (region.pstart + region.pend) / 2;

    //Save the region position
    this._chromosome.regions.list.push(region);

    //Check for add the preview label
    if(this._chromosome.regions.preview.active === true)
    {
      //Add the preview label
      this.regionsDrawLabel(this._chromosome.regions.preview.layer, i, this._chromosome.regions.preview.opacity);
    }

    //Check for draw the marks preview
    if(this._marks.chromosomes.preview.active === true)
    {
      //Draw the mark this.marks.chromosomes.opacity
      //this.ChromosomeDrawMarksIndex(canvas_down, i, this._marks.chromosomes.preview.opacity);
    }
  }

  //Calculate the utils position y start
  this._chromosome.utils.posy_start = this._chromosome.posy;

  //Calculate the utils position y end
  this._chromosome.utils.posy_end = this._chromosome.posy + this._chromosome.height;

  //Calculate the up zone
  this._chromosome.utils.up = this._chromosome.posy;

  //Calculate the down zone
  this._chromosome.utils.down = this._height - this._chromosome.utils.posy_end;

  //Calculate the position coordinate y
  this._chromosome.position.posy = this._chromosome.posy - this._chromosome.position.margin;

  //Reset the hover region
  this._chromosome.regions.label.hover = -1;

  //Hide the loading
  this.loading(false);

  //Update the foot content
  this._panel.el.footContent(this._chromosome.foot.replace('{c}', chr.name).replace('{r}', regions.length));

  //Exit
  return this;
};

//Check over chromosome zone
jviz.modules.ideogram.prototype.chromosomeOver = function(x, y)
{
  //Check the x coordinate
  if(x < this._chromosome.posx || this._chromosome.posx + this._chromosome.width < x){ return false; }

  //Check the y coordinate
  //if(y < this._chromosome.posy || this._chromosome.posy + this._chromosome.height < y){ return false; }

  //Return true
  return true;
};

//Chromosome click
jviz.modules.ideogram.prototype.chromosomeClick = function(x, y)
{
  //Check for click over the zone
  if(this.chromosomeOver(x, y) === false){ return; }

  //Find the region
  var index = this.regionOver(x, y);

  //Check for undefined region
  if(index === -1){ return; }

  //Get the chromosome info
  var chr = this._genome.chromosomes[this._chromosome.now];

  //Get the region info
  var region = this._chromosome.regions.list[index];

  //Call the event
  this._events.emit('click:region', region.name, chr.name, region.start, region.end, index);
};

//Chromosome move
jviz.modules.ideogram.prototype.chromosomeMove = function(x, y)
{
  //Check if is over the zone
  if(this.chromosomeOver(x, y) === false){ return; }

  //Draw the position
  this.positionDraw(x, y);

  //Check the region
  var index = this.regionOver(x, y);

  //Check for different index
  if(index === this._chromosome.regions.label.hover){ return; }

  //Update the index
  this._chromosome.regions.label.hover = index;

  //Clear the canvas
  //canvas.Clear({ x: 0, y: this.chromosome.utils.posy_end, width: this.width, height: this.chromosome.utils.down });
  this._canvas.el.layer(this._chromosome.regions.label.layer).Clear();

  //Check for null index
  if(index < 0)
  {
    //Remove the pointer cursor
    jviz.cursor.remove('pointer');

    //Exit
    return;
  }

  //Draw the region
  this.regionsDrawLabel(this._chromosome.regions.label.layer, index, this._chromosome.regions.label.opacity);

  //Draw the marks
  //this.ChromosomeDrawMarksIndex(canvas, index, this.marks.chromosomes.opacity);

  //Add the pointer cursor
  jviz.cursor.set('pointer');
};

//Chromosome leave
jviz.modules.ideogram.prototype.chromosomeLeave = function()
{

};

//Draw an empty chromosome
jviz.modules.ideogram.prototype.chromosomeEmpty = function()
{
  //Clear the chromosome view
  this.chromosomeClear(this._chromosome.draw.layer);

  //Continue
  return this;
};

//Clear the chromosome panel
jviz.modules.ideogram.prototype.chromosomeClear = function(id)
{
  //Get the draw
  var draw = this._chromosome.draw;

  //Get the canvas layer
  var canvas = this._canvas.el.layer(id);

  //Clear the canvas
  canvas.Clear({ x: 0, y: draw.top, width: draw.real_width, height: draw.real_height });

  //Exit
  return this;
};
<|endoftext|>