<commit_before>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')

//  ---------------------------------------------------------------------------

module.exports = class paymium extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'paymium',
            'name': 'Paymium',
            'countries': [ 'FR', 'EU' ],
            'rateLimit': 2000,
            'version': 'v1',
            'hasCORS': true,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27790564-a945a9d4-5ff9-11e7-9d2d-b635763f2f24.jpg',
                'api': 'https://paymium.com/api',
                'www': 'https://www.paymium.com',
                'doc': [
                    'https://github.com/Paymium/api-documentation',
                    'https://www.paymium.com/page/developers',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'countries',
                        'data/{id}/ticker',
                        'data/{id}/trades',
                        'data/{id}/depth',
                        'bitcoin_charts/{id}/trades',
                        'bitcoin_charts/{id}/depth',
                    ],
                },
                'private': {
                    'get': [
                        'merchant/get_payment/{UUID}',
                        'user',
                        'user/addresses',
                        'user/addresses/{btc_address}',
                        'user/orders',
                        'user/orders/{UUID}',
                        'user/price_alerts',
                    ],
                    'post': [
                        'user/orders',
                        'user/addresses',
                        'user/payment_requests',
                        'user/price_alerts',
                        'merchant/create_payment',
                    ],
                    'delete': [
                        'user/orders/{UUID}/cancel',
                        'user/price_alerts/{id}',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR' },
            },
            'fees': {
                'trading': {
                    'maker': 0.0059,
                    'taker': 0.0059,
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        let balances = await this.privateGetUser ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            let account = this.account ();
            let balance = 'balance_' + lowercase;
            let locked = 'locked_' + lowercase;
            if (balance in balances)
                account['free'] = balances[balance];
            if (locked in balances)
                account['used'] = balances[locked];
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        let orderbook = await this.publicGetDataIdDepth (this.extend ({
            'id': this.marketId (symbol),
        }, params));
        let result = this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
        result['bids'] = this.sortBy (result['bids'], 0, true);
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetDataIdTicker (this.extend ({
            'id': this.marketId (symbol),
        }, params));
        let timestamp = ticker['at'] * 1000;
        let vwap = parseFloat (ticker['vwap']);
        let baseVolume = parseFloat (ticker['volume']);
        let quoteVolume = baseVolume * vwap;
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': safeFloat (ticker, 'high'),
            'low': safeFloat (ticker, 'low'),
            'bid': safeFloat (ticker, 'bid'),
            'ask': safeFloat (ticker, 'ask'),
            'vwap': vwap,
            'open': safeFloat (ticker, 'open'),
            'close': undefined,
            'first': undefined,
            'last': safeFloat (ticker, 'price'),
            'change': undefined,
            'percentage': safeFloat (ticker, 'variation'),
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['created_at_int']) * 1000;
        let volume = 'traded_' + market['base'].toLowerCase ();
        return {
            'info': trade,
            'id': trade['uuid'],
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['side'],
            'price': trade['price'],
            'amount': trade[volume],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetDataIdTrades (this.extend ({
            'id': market['id'],
        }, params));
        return this.parseTrades (response, market);
    }

    async createOrder (market, type, side, amount, price = undefined, params = {}) {
        let order = {
            'type': this.capitalize (type) + 'Order',
            'currency': this.marketId (market),
            'direction': side,
            'amount': amount,
        };
        if (type == 'market')
            order['price'] = price;
        let response = await this.privatePostUserOrders (this.extend (order, params));
        return {
            'info': response,
            'id': response['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder (this.extend ({
            'orderNumber': id,
        }, params));
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api == 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            body = this.json (params);
            let nonce = this.nonce ().toString ();
            let auth = nonce + url + body;
            headers = {
                'Api-Key': this.apiKey,
                'Api-Signature': this.hmac (this.encode (auth), this.secret),
                'Api-Nonce': nonce,
                'Content-Type': 'application/json',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('errors' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<commit_msg>minor typos<commit_after>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')

//  ---------------------------------------------------------------------------

module.exports = class paymium extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'paymium',
            'name': 'Paymium',
            'countries': [ 'FR', 'EU' ],
            'rateLimit': 2000,
            'version': 'v1',
            'hasCORS': true,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27790564-a945a9d4-5ff9-11e7-9d2d-b635763f2f24.jpg',
                'api': 'https://paymium.com/api',
                'www': 'https://www.paymium.com',
                'doc': [
                    'https://github.com/Paymium/api-documentation',
                    'https://www.paymium.com/page/developers',
                ],
            },
            'api': {
                'public': {
                    'get': [
                        'countries',
                        'data/{id}/ticker',
                        'data/{id}/trades',
                        'data/{id}/depth',
                        'bitcoin_charts/{id}/trades',
                        'bitcoin_charts/{id}/depth',
                    ],
                },
                'private': {
                    'get': [
                        'merchant/get_payment/{UUID}',
                        'user',
                        'user/addresses',
                        'user/addresses/{btc_address}',
                        'user/orders',
                        'user/orders/{UUID}',
                        'user/price_alerts',
                    ],
                    'post': [
                        'user/orders',
                        'user/addresses',
                        'user/payment_requests',
                        'user/price_alerts',
                        'merchant/create_payment',
                    ],
                    'delete': [
                        'user/orders/{UUID}/cancel',
                        'user/price_alerts/{id}',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR' },
            },
            'fees': {
                'trading': {
                    'maker': 0.0059,
                    'taker': 0.0059,
                },
            },
        });
    }

    async fetchBalance (params = {}) {
        let balances = await this.privateGetUser ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            let account = this.account ();
            let balance = 'balance_' + lowercase;
            let locked = 'locked_' + lowercase;
            if (balance in balances)
                account['free'] = balances[balance];
            if (locked in balances)
                account['used'] = balances[locked];
            account['total'] = this.sum (account['free'], account['used']);
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        let orderbook = await this.publicGetDataIdDepth (this.extend ({
            'id': this.marketId (symbol),
        }, params));
        let result = this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'amount');
        result['bids'] = this.sortBy (result['bids'], 0, true);
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetDataIdTicker (this.extend ({
            'id': this.marketId (symbol),
        }, params));
        let timestamp = ticker['at'] * 1000;
        let vwap = parseFloat (ticker['vwap']);
        let baseVolume = parseFloat (ticker['volume']);
        let quoteVolume = baseVolume * vwap;
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker, 'high'),
            'low': this.safeFloat (ticker, 'low'),
            'bid': this.safeFloat (ticker, 'bid'),
            'ask': this.safeFloat (ticker, 'ask'),
            'vwap': vwap,
            'open': this.safeFloat (ticker, 'open'),
            'close': undefined,
            'first': undefined,
            'last': this.safeFloat (ticker, 'price'),
            'change': undefined,
            'percentage': this.safeFloat (ticker, 'variation'),
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['created_at_int']) * 1000;
        let volume = 'traded_' + market['base'].toLowerCase ();
        return {
            'info': trade,
            'id': trade['uuid'],
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'type': undefined,
            'side': trade['side'],
            'price': trade['price'],
            'amount': trade[volume],
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetDataIdTrades (this.extend ({
            'id': market['id'],
        }, params));
        return this.parseTrades (response, market);
    }

    async createOrder (market, type, side, amount, price = undefined, params = {}) {
        let order = {
            'type': this.capitalize (type) + 'Order',
            'currency': this.marketId (market),
            'direction': side,
            'amount': amount,
        };
        if (type == 'market')
            order['price'] = price;
        let response = await this.privatePostUserOrders (this.extend (order, params));
        return {
            'info': response,
            'id': response['uuid'],
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder (this.extend ({
            'orderNumber': id,
        }, params));
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (api == 'public') {
            if (Object.keys (query).length)
                url += '?' + this.urlencode (query);
        } else {
            this.checkRequiredCredentials ();
            body = this.json (params);
            let nonce = this.nonce ().toString ();
            let auth = nonce + url + body;
            headers = {
                'Api-Key': this.apiKey,
                'Api-Signature': this.hmac (this.encode (auth), this.secret),
                'Api-Nonce': nonce,
                'Content-Type': 'application/json',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if ('errors' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<|endoftext|>


<commit_before>
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  arguments.callee = arguments.callee.caller;
  if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});

// place any jQuery/helper plugins in here, instead of separate, slower script files.

<commit_msg>don't add the callee - unless you're going to use it<commit_after>
// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
      arguments.callee = arguments.callee.caller;
      console.log( Array.prototype.slice.call(arguments) );
  }
};
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c})(window.console=window.console||{});

// place any jQuery/helper plugins in here, instead of separate, slower script files.
<|endoftext|>


<commit_before>export function ChartInternal(api) {
    var $$ = this;
    $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
    $$.api = api;
    $$.config = $$.getDefaultConfig();
    $$.data = {};
    $$.cache = {};
    $$.axes = {};
}
<commit_msg>docs: add note about $$.d3 =.<commit_after>export function ChartInternal(api) {
    var $$ = this;
    // Note: This part will be replaced by rollup-plugin-modify
    // When bundling esm output. Beware of changing this line.
    // TODO: Maybe we should check that the modification by rollup-plugin-modify
    // is valid during unit tests.
    $$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
    $$.api = api;
    $$.config = $$.getDefaultConfig();
    $$.data = {};
    $$.cache = {};
    $$.axes = {};
}
<|endoftext|>


<commit_before>'use strict';
define(
    [
        'three',
        'SpaceShip',
        'Debug'
    ],
    function(THREE, SpaceShip, Debug) {
        return class Player extends SpaceShip {

            // ##############################################
            // # Constructor ################################
            // ##############################################

            constructor(scene, name, options) {
                if(!scene || !name || !options || typeof(options) !== 'object') {
                    throw new Error('Player has not been initialized properly.');
                }

                options.model = 'assets/models/ship.json';

                super(scene, name, options);
                this.positionIndicatorScale = 1;

                this.accelerationChange = new THREE.Vector3(0, 0, 0);
            }

            // ##############################################
            // # Private functions ##########################
            // ##############################################

            _createPositionIndicator() {
                let arrowGeometry = new THREE.Geometry();

                let xOffset = 3;
                let zOffset = 3;

                // Push vertices for the arrow
                arrowGeometry.vertices.push(new THREE.Vector3(0 - xOffset, 0, 6 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(3 - xOffset, 0, 0 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(6 - xOffset, 0, 6 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(3 - xOffset, 0, 4 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(0 - xOffset, 0, 6 - zOffset));

                let arrowMaterial      = new THREE.LineBasicMaterial({ color: 0x7fffd4 });
                this.positionIndicator = new THREE.Line(arrowGeometry, arrowMaterial);
                this.positionIndicator.position.set(this.position.x, this.position.y, this.position.z);
                this.scene.add(this.positionIndicator);
            }

            // ##############################################
            // # Public functions ###########################
            // ##############################################

            accelerate() {
                this.accelerationChange.set(2E-24, 2E-24);
            }

            // ##############################################

            decelerate() {
                this.accelerationChange.set(2E-24, 2E-24);
            }

            // ##############################################

            turnLeft() {
                this.mesh.rotation.y += Math.PI / 60;
            }

            // ##############################################

            turnRight() {
                this.mesh.rotation.y -= Math.PI / 60;
            }

            // ##############################################

            update(deltaT, smoothDeltaT, spaceObjects) {
                super.update(deltaT, smoothDeltaT, spaceObjects);

                Debug.log(this.mesh ? this.mesh.rotation : '');

                if(this.positionIndicator) {

                    this.positionIndicator.rotation.set(
                        this.mesh.rotation.x,
                        this.mesh.rotation.y - Math.PI / 2,
                        this.mesh.rotation.z
                    );
                }
            }

            // ##############################################

            force(position, mass, id, gameObjects) {
                let vec = super.force(position, mass, id, gameObjects);

                let orientation = new THREE.Vector3(
                    Math.cos(this.mesh ? this.mesh.rotation.y : 0),
                    0,
                    Math.sin(this.mesh ? this.mesh.rotation.y : 0)
                );

                vec.add(this.accelerationChange.multiply(orientation));

                this.accelerationChange.set(0, 0, 0);

                return vec;
            }
        }
    }
);<commit_msg>Fixed player movement<commit_after>'use strict';
define(
    [
        'three',
        'SpaceShip',
        'Debug'
    ],
    function(THREE, SpaceShip, Debug) {
        return class Player extends SpaceShip {

            // ##############################################
            // # Constructor ################################
            // ##############################################

            constructor(scene, name, options) {
                if(!scene || !name || !options || typeof(options) !== 'object') {
                    throw new Error('Player has not been initialized properly.');
                }

                options.model = 'assets/models/ship.json';

                super(scene, name, options);
                this.positionIndicatorScale = 1;

                this.accelerationChange = new THREE.Vector3(0, 0, 0);
            }

            // ##############################################
            // # Private functions ##########################
            // ##############################################

            _createPositionIndicator() {
                let arrowGeometry = new THREE.Geometry();

                let xOffset = 3;
                let zOffset = 3;

                // Push vertices for the arrow
                arrowGeometry.vertices.push(new THREE.Vector3(0 - xOffset, 0, 6 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(3 - xOffset, 0, 0 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(6 - xOffset, 0, 6 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(3 - xOffset, 0, 4 - zOffset));
                arrowGeometry.vertices.push(new THREE.Vector3(0 - xOffset, 0, 6 - zOffset));

                let arrowMaterial      = new THREE.LineBasicMaterial({ color: 0x7fffd4 });
                this.positionIndicator = new THREE.Line(arrowGeometry, arrowMaterial);
                this.positionIndicator.position.set(this.position.x, this.position.y, this.position.z);
                this.scene.add(this.positionIndicator);
            }

            // ##############################################
            // # Public functions ###########################
            // ##############################################

            accelerate() {
                this.accelerationChange.set(
                    Math.cos(this.mesh.rotation.y),
                    0,
                    -Math.sin(this.mesh.rotation.y)
                );

                this.accelerationChange.multiplyScalar(2E-24);
            }

            // ##############################################

            decelerate() {
                this.accelerationChange.set(
                    -Math.cos(this.mesh.rotation.y),
                    0,
                    Math.sin(this.mesh.rotation.y)
                );

                this.accelerationChange.multiplyScalar(2E-24);
            }

            // ##############################################

            turnLeft() {
                this.mesh.rotation.y += Math.PI / 60;
            }

            // ##############################################

            turnRight() {
                this.mesh.rotation.y -= Math.PI / 60;
            }

            // ##############################################

            update(deltaT, smoothDeltaT, spaceObjects) {
                super.update(deltaT, smoothDeltaT, spaceObjects);

                Debug.log(this.mesh ? this.mesh.rotation : '');

                if(this.positionIndicator) {

                    this.positionIndicator.rotation.set(
                        this.mesh.rotation.x,
                        this.mesh.rotation.y - Math.PI / 2,
                        this.mesh.rotation.z
                    );
                }
            }

            // ##############################################

            force(position, mass, id, gameObjects) {
                let vec = super.force(position, mass, id, gameObjects);

                vec.add(this.accelerationChange);

                this.accelerationChange.set(0, 0, 0);

                return vec;
            }
        }
    }
);<|endoftext|>


<commit_before>/**
 * Rainbow is a simple code syntax highlighter
 *
 * @author Craig Campbell <iamcraigcampbell@gmail.com>
 */
window.Rainbow = (function() {

    /**
     * array of replacements and positions
     *
     * @var {Object}
     */
    var replacements = {},
        replacement_positions = {},
        language_patterns = {},

        /**
         * an array of languages that should not inherit the defaults
         */
        bypass_defaults = {},

        /**
         * processing level
         *
         * replacements are stored at this level so if there is a sub block of code
         * (for example php inside of html) it runs at a different level
         */
        CURRENT_LEVEL = 0,

        /**
         * constant used to refer to the default language
         */
        DEFAULT_LANGUAGE = 0,

        /**
         * used as counters so we can selectively call setTimeout
         * after processing a certain number of matches/replacements
         */
        match_counter = 0,
        replacement_counter = 0;

    /**
     * cross browser get attribute for an element
     *
     * @see http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method
     *
     * @param {Object} element
     * @param {String} attribute you are trying to get
     * @returns {String}
     */
    function _attr(el, attr) {
        var result = (el.getAttribute && el.getAttribute(attr)) || null;

        if (!result) {
            var attrs = el.attributes,
                length = attrs.length,
                i;

            for(i = 0; i < length; ++i) {
                if (attr[i].nodeName === attr) {
                    result = attr[i].nodeValue;
                }
            }
        }

        return result;
    }

    /**
     * determines if a new match intersects with an existing one
     *
     * @param {number} start1    start position of existing match
     * @param {number} end1      end position of existing match
     * @param {number} start2    start position of new match
     * @param {number} end2      end position of new match
     * @returns {boolean}
     */
    function _intersects(start1, end1, start2, end2) {
        if (start2 >= start1 && start2 < end1) {
            return true;
        }

        return end2 > start1 && end2 < end1;
    }

    /**
     * determines if two different matches have complete overlap with each other
     *
     * @param {number} start1   start position of existing match
     * @param {number} end1     end position of existing match
     * @param {number} start2   start position of new match
     * @param {number} end2     end position of new match
     * @returns {boolean}
     */
    function _hasCompleteOverlap(start1, end1, start2, end2) {
        if (start2 == start1 && end2 == end1) {
            return false;
        }

        return start2 <= start1 && end2 >= end1;
    }

    /**
     * determines if the match passed in falls inside of an existing match
     * this prevents a regex pattern from matching inside of a bigger pattern
     *
     * @param {number} start - start position of new match
     * @param {number} end - end position of new match
     * @returns {boolean}
     */
    function _matchIsInsideOtherMatch(start, end) {
        for (var key in replacement_positions[CURRENT_LEVEL]) {

            // if this block completely overlaps with another block
            // then we should remove the other block and return false
            if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
                delete replacement_positions[CURRENT_LEVEL][key];
                delete replacements[CURRENT_LEVEL][key];
            }

            if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
                return true;
            }
        }

        return false;
    }

    /**
     * takes a string of code and wraps it in a span tag based on the name
     *
     * @param {string} name     name of the pattern (ie keyword.regex)
     * @param {string} code     block of code to wrap
     * @returns {string}
     */
    function _wrapCodeInSpan(name, code) {
        return '' + code + '';
    }

    /**
     * finds out the position of group match for a regular expression
     *
     * @param {RegExp} match
     * @param {number} group_number
     * @returns {number}
     */
    function _indexOfGroup(match, group_number) {
        var index = match.index;
        for (var i = 1; i < group_number; ++i) {
            if (match[i]) {
                index += match[i].length;
            }
        }
        return index;
    }

    /**
     * matches a regex pattern against a block of code
     * finds all matches that should be processed and stores the positions
     * of where they should be replaced within the string
     *
     * this is where pretty much all the work is done but it should not
     * be called directly
     *
     * @param {RegExp} pattern
     * @param {string} code
     * @returns void
     */
    function _processPattern(regex, pattern, code, callback)
    {
        var match = regex.exec(code);

        if (!match) {
            return callback();
        }

        ++match_counter;

        var replacement = match[0],
            start_pos = match.index,
            end_pos = match[0].length + start_pos;

        /**
         * callback to process the next match of this pattern
         */
        var processNext = function() {
            var nextCall = function() {
                _processPattern(regex, pattern, code, callback);
            };

            // every 100 items we process let's call set timeout
            // to let the ui breathe a little
            return match_counter % 100 > 0 ? nextCall() : setTimeout(nextCall, 0);
        };

        // if this is not a child match and it falls inside of another
        // match that already happened we should skip it and continue processing
        if (_matchIsInsideOtherMatch(start_pos, end_pos)) {
            return processNext();
        }

        /**
         * callback for when a match was successfully processed
         */
        var onMatchSuccess = function(replacement) {
            // if this match has a name then wrap it in a span tag
            if (pattern['name']) {
                replacement = _wrapCodeInSpan(pattern['name'], replacement);
            }

            // console.log('LEVEL', CURRENT_LEVEL, 'replace', match[0], 'with', replacement, 'at position', start_pos, 'to', end_pos);

            // store what needs to be replaced with what at this position
            if (!replacements[CURRENT_LEVEL]) {
                replacements[CURRENT_LEVEL] = {};
                replacement_positions[CURRENT_LEVEL] = {};
            }

            replacements[CURRENT_LEVEL][start_pos] = {
                'replace': match[0],
                'with': replacement
            };

            // store the range of this match so we can use it for comparisons
            // with other matches later
            replacement_positions[CURRENT_LEVEL][start_pos] = end_pos;

            // process the next match
            processNext();
        };

        // if this pattern has sub matches for different groups in the regex
        // then we should process them one at a time by rerunning them through
        // this function to generate the new replacement
        var group_keys = keys(pattern['matches']);

        /**
         * callback for processing a sub group
         */
        var processGroup = function(i, group_keys, callback) {
            if (i >= group_keys.length) {
                return callback(replacement);
            }

            var processNextGroup = function() {
                processGroup(++i, group_keys, callback);
            };

            // if there is no match here then move on
            if (!match[group_keys[i]]) {
                return processNextGroup();
            }

            var group = pattern['matches'][group_keys[i]],
                block = match[group_keys[i]];

            // if this is a sublanguage go and process the block using that language
            var language = group['language'];
            if (language) {
                return _highlightBlockForLanguage(block, language, function(code) {
                    replacement = replacement.replace(block, code);
                    processNextGroup();
                });
            }

            // if this is a submatch go and process the block using the specified pattern
            if (group['name']) {
                return _processCodeWithPatterns(block, [group], function(code) {
                    replacement = replacement.replace(block, code);
                    processNextGroup();
                });
            }

            var group_match_position = _indexOfGroup(match, group_keys[i]) - match.index;
            replacement = _replaceAtPosition(group_match_position, match[group_keys[i]], _wrapCodeInSpan(group, match[group_keys[i]]), replacement);
            processNextGroup();
        };

        processGroup(0, group_keys, onMatchSuccess);
    }

    /**
     * should a language bypass the default patterns?
     *
     * if you call Rainbow.extend() and pass true as the third argument
     * it will bypass the defaults
     */
    function _bypassDefaultPatterns(language)
    {
        return bypass_defaults[language] == 1;
    }

    /**
     * returns a list of regex patterns for this language
     *
     * @param {string} language
     * @returns {Array}
     */
    function _getPatternsForLanguage(language) {
        var patterns = language_patterns[language] || [],
            default_patterns = language_patterns[DEFAULT_LANGUAGE];

        if (_bypassDefaultPatterns(language)) {
            return patterns;
        }

        return patterns.concat(default_patterns);
    }

    /**
     * substring replace call to replace part of a string at a certain position
     *
     * @param {number} position         the position where the replacement should happen
     * @param {string} replace          the text we want to replace
     * @param {string} replace_with     the text we want to replace it with
     * @param {string} code             the code we are doing the replacing in
     * @returns {string}
     */
    function _replaceAtPosition(position, replace, replace_with, code) {
        var sub_string = code.substr(position);
        return code.substr(0, position) + sub_string.replace(replace, replace_with);
    }

   /**
     * sorts an object by index descending
     *
     * @param {Object} object
     * @return {array}
     */
    function keys(object) {
        var locations = [],
            replacement,
            pos;

        for(var location in object) {
            if (object.hasOwnProperty(location)) {
                locations.push(location);
            }
        }

        // numeric descending
        return locations.sort(function(a,b) {
            return b - a;
        });
    }

    /**
     * processes a block of code using specified patterns
     *
     * @param {string} code
     * @param {array} patterns
     * @returns {string}
     */
    function _processCodeWithPatterns(code, patterns, callback)
    {
        // we have to increase the level here so that the
        // replacements will not conflict with each other when
        // processing sub blocks of code
        ++CURRENT_LEVEL;

        // patterns are processed one at a time through this function
        function _workOnPatterns(patterns, i)
        {
            // still have patterns to process, keep going
            if (i < patterns.length) {
                return _processPattern(patterns[i]['pattern'], patterns[i], code, function() {
                    _workOnPatterns(patterns, ++i);
                });
            }

            // we are done processing the patterns
            // process the replacements and update the DOM
            _processReplacements(code, function(code) {

                // when we are done processing replacements
                // we are done at this level so we can go back down
                delete replacements[CURRENT_LEVEL];
                delete replacement_positions[CURRENT_LEVEL];
                --CURRENT_LEVEL;
                callback(code);
            });
        }

        _workOnPatterns(patterns, 0);
    }

    /**
     * process replacements in the string of code to actually update the markup
     *
     * @param {string} code         the code to process replacements in
     * @param {function} callback   what to do when we are done processing
     * @returns void
     */
    function _processReplacements(code, callback) {

        /**
         * processes a single replacement
         *
         * @param {string} code
         * @param {Array} positions
         * @param {number} i
         * @param {function} callback
         * @returns void
         */
        function _processReplacement(code, positions, i, callback) {
            if (i < positions.length) {
                ++replacement_counter;
                pos = positions[i];
                replacement = replacements[CURRENT_LEVEL][pos];
                code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code);

                // process next function
                var next = function() {
                    _processReplacement(code, positions, ++i, callback);
                };

                // use a timeout every 250 to not freeze up the UI
                return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0);
            }

            callback(code);
        }

        var string_positions = keys(replacements[CURRENT_LEVEL]);
        _processReplacement(code, string_positions, 0, callback);
    }

    /**
     * takes a string of code and highlights it according to the language specified
     *
     * @param {string} code
     * @param {string} language
     * @param {function} callback
     * @returns void
     */
    function _highlightBlockForLanguage(code, language, callback) {
        var patterns = _getPatternsForLanguage(language);
        _processCodeWithPatterns(code, patterns, function (code) {
            callback(code);
        });
    }

    /**
     * highlight an individual code block
     *
     * @param {Element} code_block
     * @returns void
     */
    function _highlightCodeBlock(code_blocks, i) {
        if (i >= code_blocks.length) {
            return;
        }

        var language = _attr(code_blocks[i], 'data-language').toLowerCase();

        if (language) {
            code_blocks[i].className = language;

            _highlightBlockForLanguage(code_blocks[i].innerHTML, language, function (code) {
                code_blocks[i].innerHTML = code;

                // reset the replacement arrays
                replacements = {};
                replacement_positions = {};

                setTimeout(function() {
                    _highlightCodeBlock(code_blocks, ++i);
                }, 0);
            });
        }
    }

    /**
     * start highlighting all the code blocks
     *
     * @returns void
     */
    function _highlight() {
        var code_blocks = document.getElementsByTagName('code');
        _highlightCodeBlock(code_blocks, 0);
    }

    return {

        /**
         * extends the language pattern matches
         *
         * @param {string} language     name of language
         * @param {Array} patterns      array of patterns to add on
         * @param {boolean} bypass      if true this will bypass the default language patterns
         */
        extend: function(language, patterns, bypass) {

            // if there is only one argument then we assume that we want to
            // extend the default language rules
            if (arguments.length == 1) {
                patterns = language;
                language = DEFAULT_LANGUAGE;
            }

            bypass_defaults[language] = bypass;

            language_patterns[language] = patterns.concat(language_patterns[language] || []);
        },

        /**
         * starts the magic rainbow
         *
         * @returns void
         */
        init: function() {
            _highlight();
        }
    };
}) ();

/**
 * adds event listener to start highlighting
 */
(function (w) {
    if (w.addEventListener) {
        return w.addEventListener('load', Rainbow.init, false);
    }
    w.attachEvent('onload', Rainbow.init);
}) (window);

/**
 * adds the default language patterns
 */
Rainbow.extend([
    {
        'name': 'comment',
        'pattern': /\/\*[\s\S]*?\*\/|\/\/[\s\S]*?$|\#[\s\S]*?$/gm
    },
    {
        'matches': {
            2: 'string'
        },
        'pattern': /(\(|\s|\[)(('|")[\s\S]*?(\3))/gm
    },
    {
        'name': 'integer',
        'pattern': /\b(0x[\da-f]+|\d+)\b/g
    },
    {
        'name': 'constant',
        'pattern': /\b[A-Z0-9_]{2,}\b/g
    },
    {
        'matches': {
            1: 'keyword'
        },
        'pattern': /\b(and|array|as|bool(ean)?|catch|char|class|const|def|delete|die|do(uble)?|echo|else(if)?|exit|extends|finally|float|for(each)?|function|global|if|import|int(eger)?|long|new|object|or|pr(int|ivate|otected)|pub(lic|lished)|re(al|source|turn)|self|short|st(ring|ruct|atic)|switch|th(en|is|row)|try|(un)?signed|var|void|while|xor)(?=\(|\b)/g
    },
    {
        'name': 'constant.language',
        'pattern': /true|false|null/g
    },
    {
        'name': 'keyword.operator',
        'pattern': /\+|\!|\-|>|<|&|\||\*|\=/g
    },
    {
        'matches': {
            1: 'function.call'
        },
        'pattern': /(\w+?)(?=\()/g
    },
    {
        'matches': {
            1: 'keyword',
            2: 'meta.function-call'
        },
        'pattern': /(function)\s(.*?)(?=\()/g
    }
]);
<commit_msg>Shaving ks<commit_after>/**
 * Rainbow is a simple code syntax highlighter
 *
 * @author Craig Campbell <iamcraigcampbell@gmail.com>
 */
window.Rainbow = (function() {

    /**
     * array of replacements and positions
     *
     * @var {Object}
     */
    var replacements = {},
        replacement_positions = {},
        language_patterns = {},

        /**
         * an array of languages that should not inherit the defaults
         */
        bypass_defaults = {},

        /**
         * processing level
         *
         * replacements are stored at this level so if there is a sub block of code
         * (for example php inside of html) it runs at a different level
         */
        CURRENT_LEVEL = 0,

        /**
         * constant used to refer to the default language
         */
        DEFAULT_LANGUAGE = 0,

        /**
         * used as counters so we can selectively call setTimeout
         * after processing a certain number of matches/replacements
         */
        match_counter = 0,
        replacement_counter = 0;

    /**
     * cross browser get attribute for an element
     *
     * @see http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method
     *
     * @param {Object} element
     * @param {String} attribute you are trying to get
     * @returns {String}
     */
    function _attr(el, attr) {
        var result = (el.getAttribute && el.getAttribute(attr)) || null;

        if (!result) {
            var attrs = el.attributes,
                length = attrs.length,
                i;

            for(i = 0; i < length; ++i) {
                if (attr[i].nodeName === attr) {
                    result = attr[i].nodeValue;
                }
            }
        }

        return result;
    }

    /**
     * determines if a new match intersects with an existing one
     *
     * @param {number} start1    start position of existing match
     * @param {number} end1      end position of existing match
     * @param {number} start2    start position of new match
     * @param {number} end2      end position of new match
     * @returns {boolean}
     */
    function _intersects(start1, end1, start2, end2) {
        if (start2 >= start1 && start2 < end1) {
            return true;
        }

        return end2 > start1 && end2 < end1;
    }

    /**
     * determines if two different matches have complete overlap with each other
     *
     * @param {number} start1   start position of existing match
     * @param {number} end1     end position of existing match
     * @param {number} start2   start position of new match
     * @param {number} end2     end position of new match
     * @returns {boolean}
     */
    function _hasCompleteOverlap(start1, end1, start2, end2) {
        if (start2 == start1 && end2 == end1) {
            return false;
        }

        return start2 <= start1 && end2 >= end1;
    }

    /**
     * determines if the match passed in falls inside of an existing match
     * this prevents a regex pattern from matching inside of a bigger pattern
     *
     * @param {number} start - start position of new match
     * @param {number} end - end position of new match
     * @returns {boolean}
     */
    function _matchIsInsideOtherMatch(start, end) {
        for (var key in replacement_positions[CURRENT_LEVEL]) {

            // if this block completely overlaps with another block
            // then we should remove the other block and return false
            if (_hasCompleteOverlap(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
                delete replacement_positions[CURRENT_LEVEL][key];
                delete replacements[CURRENT_LEVEL][key];
            }

            if (_intersects(key, replacement_positions[CURRENT_LEVEL][key], start, end)) {
                return true;
            }
        }

        return false;
    }

    /**
     * takes a string of code and wraps it in a span tag based on the name
     *
     * @param {string} name     name of the pattern (ie keyword.regex)
     * @param {string} code     block of code to wrap
     * @returns {string}
     */
    function _wrapCodeInSpan(name, code) {
        return '' + code + '';
    }

    /**
     * finds out the position of group match for a regular expression
     *
     * @param {RegExp} match
     * @param {number} group_number
     * @returns {number}
     */
    function _indexOfGroup(match, group_number) {
        var index = match.index;
        for (var i = 1; i < group_number; ++i) {
            if (match[i]) {
                index += match[i].length;
            }
        }
        return index;
    }

    /**
     * matches a regex pattern against a block of code
     * finds all matches that should be processed and stores the positions
     * of where they should be replaced within the string
     *
     * this is where pretty much all the work is done but it should not
     * be called directly
     *
     * @param {RegExp} pattern
     * @param {string} code
     * @returns void
     */
    function _processPattern(regex, pattern, code, callback)
    {
        var match = regex.exec(code);

        if (!match) {
            return callback();
        }

        ++match_counter;

        var replacement = match[0],
            start_pos = match.index,
            end_pos = match[0].length + start_pos;

        /**
         * callback to process the next match of this pattern
         */
        var processNext = function() {
            var nextCall = function() {
                _processPattern(regex, pattern, code, callback);
            };

            // every 100 items we process let's call set timeout
            // to let the ui breathe a little
            return match_counter % 100 > 0 ? nextCall() : setTimeout(nextCall, 0);
        };

        // if this is not a child match and it falls inside of another
        // match that already happened we should skip it and continue processing
        if (_matchIsInsideOtherMatch(start_pos, end_pos)) {
            return processNext();
        }

        /**
         * callback for when a match was successfully processed
         */
        var onMatchSuccess = function(replacement) {
            // if this match has a name then wrap it in a span tag
            if (pattern['name']) {
                replacement = _wrapCodeInSpan(pattern['name'], replacement);
            }

            // console.log('LEVEL', CURRENT_LEVEL, 'replace', match[0], 'with', replacement, 'at position', start_pos, 'to', end_pos);

            // store what needs to be replaced with what at this position
            if (!replacements[CURRENT_LEVEL]) {
                replacements[CURRENT_LEVEL] = {};
                replacement_positions[CURRENT_LEVEL] = {};
            }

            replacements[CURRENT_LEVEL][start_pos] = {
                'replace': match[0],
                'with': replacement
            };

            // store the range of this match so we can use it for comparisons
            // with other matches later
            replacement_positions[CURRENT_LEVEL][start_pos] = end_pos;

            // process the next match
            processNext();
        };

        // if this pattern has sub matches for different groups in the regex
        // then we should process them one at a time by rerunning them through
        // this function to generate the new replacement
        var group_keys = keys(pattern['matches']);

        /**
         * callback for processing a sub group
         */
        var processGroup = function(i, group_keys, callback) {
            if (i >= group_keys.length) {
                return callback(replacement);
            }

            var processNextGroup = function() {
                processGroup(++i, group_keys, callback);
            },
                block = match[group_keys[i]];

            // if there is no match here then move on
            if (!block) {
                return processNextGroup();
            }

            var group = pattern['matches'][group_keys[i]],
                language = group['language'];

            // if this is a sublanguage go and process the block using that language
            if (language) {
                return _highlightBlockForLanguage(block, language, function(code) {
                    replacement = replacement.replace(block, code);
                    processNextGroup();
                });
            }

            // @todo add support for passing an array of patterns to match a subgroup against
            // if this is a submatch go and process the block using the specified pattern
            if (group['name']) {
                return _processCodeWithPatterns(block, [group], function(code) {
                    replacement = replacement.replace(block, code);
                    processNextGroup();
                });
            }

            var group_match_position = _indexOfGroup(match, group_keys[i]) - match.index;
            replacement = _replaceAtPosition(group_match_position, block, _wrapCodeInSpan(group, block), replacement);
            processNextGroup();
        };

        processGroup(0, group_keys, onMatchSuccess);
    }

    /**
     * should a language bypass the default patterns?
     *
     * if you call Rainbow.extend() and pass true as the third argument
     * it will bypass the defaults
     */
    function _bypassDefaultPatterns(language)
    {
        return bypass_defaults[language] == 1;
    }

    /**
     * returns a list of regex patterns for this language
     *
     * @param {string} language
     * @returns {Array}
     */
    function _getPatternsForLanguage(language) {
        var patterns = language_patterns[language] || [],
            default_patterns = language_patterns[DEFAULT_LANGUAGE];

        if (_bypassDefaultPatterns(language)) {
            return patterns;
        }

        return patterns.concat(default_patterns);
    }

    /**
     * substring replace call to replace part of a string at a certain position
     *
     * @param {number} position         the position where the replacement should happen
     * @param {string} replace          the text we want to replace
     * @param {string} replace_with     the text we want to replace it with
     * @param {string} code             the code we are doing the replacing in
     * @returns {string}
     */
    function _replaceAtPosition(position, replace, replace_with, code) {
        var sub_string = code.substr(position);
        return code.substr(0, position) + sub_string.replace(replace, replace_with);
    }

   /**
     * sorts an object by index descending
     *
     * @param {Object} object
     * @return {array}
     */
    function keys(object) {
        var locations = [],
            replacement,
            pos;

        for(var location in object) {
            if (object.hasOwnProperty(location)) {
                locations.push(location);
            }
        }

        // numeric descending
        return locations.sort(function(a,b) {
            return b - a;
        });
    }

    /**
     * processes a block of code using specified patterns
     *
     * @param {string} code
     * @param {array} patterns
     * @returns {string}
     */
    function _processCodeWithPatterns(code, patterns, callback)
    {
        // we have to increase the level here so that the
        // replacements will not conflict with each other when
        // processing sub blocks of code
        ++CURRENT_LEVEL;

        // patterns are processed one at a time through this function
        function _workOnPatterns(patterns, i)
        {
            // still have patterns to process, keep going
            if (i < patterns.length) {
                return _processPattern(patterns[i]['pattern'], patterns[i], code, function() {
                    _workOnPatterns(patterns, ++i);
                });
            }

            // we are done processing the patterns
            // process the replacements and update the DOM
            _processReplacements(code, function(code) {

                // when we are done processing replacements
                // we are done at this level so we can go back down
                delete replacements[CURRENT_LEVEL];
                delete replacement_positions[CURRENT_LEVEL];
                --CURRENT_LEVEL;
                callback(code);
            });
        }

        _workOnPatterns(patterns, 0);
    }

    /**
     * process replacements in the string of code to actually update the markup
     *
     * @param {string} code         the code to process replacements in
     * @param {function} callback   what to do when we are done processing
     * @returns void
     */
    function _processReplacements(code, callback) {

        /**
         * processes a single replacement
         *
         * @param {string} code
         * @param {Array} positions
         * @param {number} i
         * @param {function} callback
         * @returns void
         */
        function _processReplacement(code, positions, i, callback) {
            if (i < positions.length) {
                ++replacement_counter;
                pos = positions[i];
                replacement = replacements[CURRENT_LEVEL][pos];
                code = _replaceAtPosition(pos, replacement['replace'], replacement['with'], code);

                // process next function
                var next = function() {
                    _processReplacement(code, positions, ++i, callback);
                };

                // use a timeout every 250 to not freeze up the UI
                return replacement_counter % 250 > 0 ? next() : setTimeout(next, 0);
            }

            callback(code);
        }

        var string_positions = keys(replacements[CURRENT_LEVEL]);
        _processReplacement(code, string_positions, 0, callback);
    }

    /**
     * takes a string of code and highlights it according to the language specified
     *
     * @param {string} code
     * @param {string} language
     * @param {function} callback
     * @returns void
     */
    function _highlightBlockForLanguage(code, language, callback) {
        var patterns = _getPatternsForLanguage(language);
        _processCodeWithPatterns(code, patterns, function (code) {
            callback(code);
        });
    }

    /**
     * highlight an individual code block
     *
     * @param {Element} code_block
     * @returns void
     */
    function _highlightCodeBlock(code_blocks, i) {
        if (i >= code_blocks.length) {
            return;
        }

        var language = _attr(code_blocks[i], 'data-language').toLowerCase();

        if (language) {
            code_blocks[i].className = language;

            _highlightBlockForLanguage(code_blocks[i].innerHTML, language, function (code) {
                code_blocks[i].innerHTML = code;

                // reset the replacement arrays
                replacements = {};
                replacement_positions = {};

                setTimeout(function() {
                    _highlightCodeBlock(code_blocks, ++i);
                }, 0);
            });
        }
    }

    /**
     * start highlighting all the code blocks
     *
     * @returns void
     */
    function _highlight() {
        var code_blocks = document.getElementsByTagName('code');
        _highlightCodeBlock(code_blocks, 0);
    }

    return {

        /**
         * extends the language pattern matches
         *
         * @param {string} language     name of language
         * @param {Array} patterns      array of patterns to add on
         * @param {boolean} bypass      if true this will bypass the default language patterns
         */
        extend: function(language, patterns, bypass) {

            // if there is only one argument then we assume that we want to
            // extend the default language rules
            if (arguments.length == 1) {
                patterns = language;
                language = DEFAULT_LANGUAGE;
            }

            bypass_defaults[language] = bypass;

            language_patterns[language] = patterns.concat(language_patterns[language] || []);
        },

        /**
         * starts the magic rainbow
         *
         * @returns void
         */
        init: function() {
            _highlight();
        }
    };
}) ();

/**
 * adds event listener to start highlighting
 */
(function (w) {
    if (w.addEventListener) {
        return w.addEventListener('load', Rainbow.init, false);
    }
    w.attachEvent('onload', Rainbow.init);
}) (window);

/**
 * adds the default language patterns
 */
Rainbow.extend([
    {
        'name': 'comment',
        'pattern': /\/\*[\s\S]*?\*\/|\/\/[\s\S]*?$|\#[\s\S]*?$/gm
    },
    {
        'matches': {
            2: 'string'
        },
        'pattern': /(\(|\s|\[)(('|")[\s\S]*?(\3))/gm
    },
    {
        'name': 'integer',
        'pattern': /\b(0x[\da-f]+|\d+)\b/g
    },
    {
        'name': 'constant',
        'pattern': /\b[A-Z0-9_]{2,}\b/g
    },
    {
        'matches': {
            1: 'keyword'
        },
        'pattern': /\b(and|array|as|bool(ean)?|catch|char|class|const|def|delete|die|do(uble)?|echo|else(if)?|exit|extends|finally|float|for(each)?|function|global|if|import|int(eger)?|long|new|object|or|pr(int|ivate|otected)|pub(lic|lished)|re(al|source|turn)|self|short|st(ring|ruct|atic)|switch|th(en|is|row)|try|(un)?signed|var|void|while|xor)(?=\(|\b)/g
    },
    {
        'name': 'constant.language',
        'pattern': /true|false|null/g
    },
    {
        'name': 'keyword.operator',
        'pattern': /\+|\!|\-|>|<|&|\||\*|\=/g
    },
    {
        'matches': {
            1: 'function.call'
        },
        'pattern': /(\w+?)(?=\()/g
    },
    {
        'matches': {
            1: 'keyword',
            2: 'meta.function-call'
        },
        'pattern': /(function)\s(.*?)(?=\()/g
    }
]);
<|endoftext|>


<commit_before>/*globals require, $, console, angular*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

var DEBUG = false,
    _jqueryVersion = '2.1.0',
    _jqueryUIVersion = '1.10.4',
    _bootsrapVersion = '3.1.1';

// configure require path and modules
require.config({
    baseUrl: '/',

    map: {
         '*': {
            'css': 'lib/require/require-css/css',
            'text': 'lib/require/require-text/text'
        }
    },

    paths: {

        'domReady':	'lib/require/require-domready/domReady',

        //jQuery and stuff
        'jquery': 'lib/jquery/jquery-' + _jqueryVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui': 'lib/jquery/jquery-ui-' + _jqueryUIVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui-iPad': 'lib/jquery/jquery.ui.ipad',
        'jquery-WebGME': 'js/jquery.WebGME',
        'jquery-dataTables': 'lib/jquery/jquery.dataTables.min',
        'jquery-dataTables-bootstrapped': 'lib/jquery/jquery.dataTables.bootstrapped',
        'jquery-spectrum': 'lib/jquery/jquery.spectrum',

        //Bootsrap stuff
        'bootstrap': 'lib/bootstrap/' + _bootsrapVersion + '/js/bootstrap' + ( DEBUG ? '.min' : '' ),

        //Other modules
        'underscore': 'lib/underscore/underscore-min',
        'backbone': 'lib/backbone/backbone.min',
        'd3': 'lib/d3/d3.v3.min',
        'jscolor': 'lib/jscolor/jscolor',
        'superagent': 'lib/superagent/superagent',

        //RaphaelJS family
        'eve': 'lib/raphael/eve',   //needed because of raphael.core.js uses require with 'eve'
        'raphaeljs': 'lib/raphael/raphael.amd',
        'raphael_core': 'lib/raphael/raphael.core',
        'raphael_svg': 'lib/raphael/raphael.svg_fixed',
        'raphael_vml': 'lib/raphael/raphael.vml',

        //WebGME custom modules
        'logManager': 'common/LogManager',
        'eventDispatcher': 'common/EventDispatcher',

        'util': 'common/util',
        'core': 'common/core',
        'coreclient': 'common/core/users',
        'storage': 'common/storage',
        'blob': 'middleware/blob',

        'notificationManager': 'js/NotificationManager',
        'clientUtil': 'js/util',
        'loaderCircles': 'js/Loader/LoaderCircles',
        'loaderProgressBar': 'js/Loader/LoaderProgressBar',

        'codemirror': 'lib/codemirror/codemirror.amd',
        'jquery-csszoom': 'lib/jquery/jquery.csszoom',

        'jszip': 'lib/jszip/jszip',

        'moment': 'lib/moment/moment.min',

        // Angular and modules
        'angular': 'lib/angular/angular-1.2.19/angular' + ( DEBUG ? '.min' : '' ),
        'angular-route': 'lib/angular/angular-1.2.19/angular-route' + ( DEBUG ? '.min' : '' ),
        'angular-route-styles': 'lib/angular/angular-route-styles/route-styles',
        'angular-ui-bootstrap': 'lib/angular/ui-bootstrap/ui-bootstrap-tpls-0.11.0.min'
    },

    shim: {

        'angular-route': ['angular'],
        'angular-route-styles': ['angular'],
        'angular-ui-bootstrap': ['angular'],

        'jquery-ui': ['jquery'],
        'jquery-ui-iPad': ['jquery','jquery-ui'],

        'bootstrap': [
            'jquery',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap.min.css',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap-theme.min.css'
        ],

        'backbone': ['underscore'],
        'clientUtil': ['jquery'],
        'jquery-WebGME': ['bootstrap'],
        'jquery-dataTables': ['jquery'],
        'jquery-dataTables-bootstrapped': ['jquery-dataTables'],
        'js/WebGME': [
            'jquery-WebGME',
            'css!/css/main.css',
            'css!/css/themes/dawn.css',
            //'css!/fonts/font-awesome/css/font-awesome.min.css',
            'css!/fonts/webgme-icons/style.css'
        ],
        'jquery-csszoom': ['jquery-ui'],
        'jquery-spectrum': ['jquery'],
        'raphael_svg': ['raphael_core'],
        'raphael_vml': ['raphael_core']
    }
});

require(
    [
        'domReady',
        'jquery',
        'jquery-ui',
        'jquery-ui-iPad',
        'jquery-WebGME',
        'jquery-dataTables-bootstrapped',
        'bootstrap',
        'underscore',
        'backbone',
        'js/WebGME',
        'clientUtil',
        'bin/getconfig',

        'angular',
        'angular-route',
        'angular-route-styles',
        'angular-ui-bootstrap',

        'js/services/DataStoreService'

    ],
    function (domReady, jQuery, jQueryUi, jQueryUiiPad, jqueryWebGME, jqueryDataTables, bootstrap, underscore,
              backbone, webGME, util, CONFIG) {

        'use strict';

        domReady(function () {

            if (CONFIG.hasOwnProperty('debug')) {
                DEBUG = CONFIG.debug;
            }

            var d = util.getURLParameterByName('debug').toLowerCase();
            if (d === 'true') {
                DEBUG = true;
            }

            if (CONFIG.paths) {

                // attach external libraries to extlib/*

                var keys = Object.keys(CONFIG.paths);
                for (var i = 0; i < keys.length; i += 1) {

                    // assume this is a relative path from the current working directory
                    CONFIG.paths[keys[i]] = 'extlib/' + CONFIG.paths[keys[i]];
                }

                // update client config to route the external lib requests

                require.config({
                    paths: CONFIG.paths
                });

            }

            // Extended disable function
            jQuery.fn.extend({
                disable: function(state) {
                    return this.each(function() {
                        var $this = $(this);
                        if($this.is('input, button')) {
                          this.disabled = state;
                        } else {
                          $this.toggleClass('disabled', state);
                        }
                    });
                }
            });

            // Initialize Angular. For this time no better place.
            // has to be initialized as early as possible
            var gmeApp = angular.module(
                'gmeApp', [
                    'ngRoute',
                    'routeStyles',
                    'ui.bootstrap',
                    'gme.ui.projectsDialog',
                    'gme.ui.headerPanel',

                    'gme.services'
                ]);

            // TODO: REMOVE - ONLY FOR TESTING
            WebGMEGlobal.gmeApp = gmeApp;
            gmeApp.controller('TestController', function ($scope, DataStoreService) {

                DataStoreService.connectToDatabase()
                    .then(function(db) {
                        console.log('opened database');

                        db.openProject('myproject')
                            .then(function (data) {
                                 console.log('opened project', data);
                            });
                    });
            });

            webGME.start( function(client) {

                gmeApp.value('gmeClient', client);
//                gmeApp.value('gmeClient', null);

                angular.bootstrap(document, [ 'gmeApp']);

            });

        });
    }
);
<commit_msg>Update usage of service<commit_after>/*globals require, $, console, angular*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

var DEBUG = false,
    _jqueryVersion = '2.1.0',
    _jqueryUIVersion = '1.10.4',
    _bootsrapVersion = '3.1.1';

// configure require path and modules
require.config({
    baseUrl: '/',

    map: {
         '*': {
            'css': 'lib/require/require-css/css',
            'text': 'lib/require/require-text/text'
        }
    },

    paths: {

        'domReady':	'lib/require/require-domready/domReady',

        //jQuery and stuff
        'jquery': 'lib/jquery/jquery-' + _jqueryVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui': 'lib/jquery/jquery-ui-' + _jqueryUIVersion + ( DEBUG ? '.min' : '' ),
        'jquery-ui-iPad': 'lib/jquery/jquery.ui.ipad',
        'jquery-WebGME': 'js/jquery.WebGME',
        'jquery-dataTables': 'lib/jquery/jquery.dataTables.min',
        'jquery-dataTables-bootstrapped': 'lib/jquery/jquery.dataTables.bootstrapped',
        'jquery-spectrum': 'lib/jquery/jquery.spectrum',

        //Bootsrap stuff
        'bootstrap': 'lib/bootstrap/' + _bootsrapVersion + '/js/bootstrap' + ( DEBUG ? '.min' : '' ),

        //Other modules
        'underscore': 'lib/underscore/underscore-min',
        'backbone': 'lib/backbone/backbone.min',
        'd3': 'lib/d3/d3.v3.min',
        'jscolor': 'lib/jscolor/jscolor',
        'superagent': 'lib/superagent/superagent',

        //RaphaelJS family
        'eve': 'lib/raphael/eve',   //needed because of raphael.core.js uses require with 'eve'
        'raphaeljs': 'lib/raphael/raphael.amd',
        'raphael_core': 'lib/raphael/raphael.core',
        'raphael_svg': 'lib/raphael/raphael.svg_fixed',
        'raphael_vml': 'lib/raphael/raphael.vml',

        //WebGME custom modules
        'logManager': 'common/LogManager',
        'eventDispatcher': 'common/EventDispatcher',

        'util': 'common/util',
        'core': 'common/core',
        'coreclient': 'common/core/users',
        'storage': 'common/storage',
        'blob': 'middleware/blob',

        'notificationManager': 'js/NotificationManager',
        'clientUtil': 'js/util',
        'loaderCircles': 'js/Loader/LoaderCircles',
        'loaderProgressBar': 'js/Loader/LoaderProgressBar',

        'codemirror': 'lib/codemirror/codemirror.amd',
        'jquery-csszoom': 'lib/jquery/jquery.csszoom',

        'jszip': 'lib/jszip/jszip',

        'moment': 'lib/moment/moment.min',

        // Angular and modules
        'angular': 'lib/angular/angular-1.2.19/angular' + ( DEBUG ? '.min' : '' ),
        'angular-route': 'lib/angular/angular-1.2.19/angular-route' + ( DEBUG ? '.min' : '' ),
        'angular-route-styles': 'lib/angular/angular-route-styles/route-styles',
        'angular-ui-bootstrap': 'lib/angular/ui-bootstrap/ui-bootstrap-tpls-0.11.0.min'
    },

    shim: {

        'angular-route': ['angular'],
        'angular-route-styles': ['angular'],
        'angular-ui-bootstrap': ['angular'],

        'jquery-ui': ['jquery'],
        'jquery-ui-iPad': ['jquery','jquery-ui'],

        'bootstrap': [
            'jquery',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap.min.css',
            'css!lib/bootstrap/' + _bootsrapVersion + '/css/bootstrap-theme.min.css'
        ],

        'backbone': ['underscore'],
        'clientUtil': ['jquery'],
        'jquery-WebGME': ['bootstrap'],
        'jquery-dataTables': ['jquery'],
        'jquery-dataTables-bootstrapped': ['jquery-dataTables'],
        'js/WebGME': [
            'jquery-WebGME',
            'css!/css/main.css',
            'css!/css/themes/dawn.css',
            //'css!/fonts/font-awesome/css/font-awesome.min.css',
            'css!/fonts/webgme-icons/style.css'
        ],
        'jquery-csszoom': ['jquery-ui'],
        'jquery-spectrum': ['jquery'],
        'raphael_svg': ['raphael_core'],
        'raphael_vml': ['raphael_core']
    }
});

require(
    [
        'domReady',
        'jquery',
        'jquery-ui',
        'jquery-ui-iPad',
        'jquery-WebGME',
        'jquery-dataTables-bootstrapped',
        'bootstrap',
        'underscore',
        'backbone',
        'js/WebGME',
        'clientUtil',
        'bin/getconfig',

        'angular',
        'angular-route',
        'angular-route-styles',
        'angular-ui-bootstrap',

        'js/services/DataStoreService'

    ],
    function (domReady, jQuery, jQueryUi, jQueryUiiPad, jqueryWebGME, jqueryDataTables, bootstrap, underscore,
              backbone, webGME, util, CONFIG) {

        'use strict';

        domReady(function () {

            if (CONFIG.hasOwnProperty('debug')) {
                DEBUG = CONFIG.debug;
            }

            var d = util.getURLParameterByName('debug').toLowerCase();
            if (d === 'true') {
                DEBUG = true;
            }

            if (CONFIG.paths) {

                // attach external libraries to extlib/*

                var keys = Object.keys(CONFIG.paths);
                for (var i = 0; i < keys.length; i += 1) {

                    // assume this is a relative path from the current working directory
                    CONFIG.paths[keys[i]] = 'extlib/' + CONFIG.paths[keys[i]];
                }

                // update client config to route the external lib requests

                require.config({
                    paths: CONFIG.paths
                });

            }

            // Extended disable function
            jQuery.fn.extend({
                disable: function(state) {
                    return this.each(function() {
                        var $this = $(this);
                        if($this.is('input, button')) {
                          this.disabled = state;
                        } else {
                          $this.toggleClass('disabled', state);
                        }
                    });
                }
            });

            // Initialize Angular. For this time no better place.
            // has to be initialized as early as possible
            var gmeApp = angular.module(
                'gmeApp', [
                    'ngRoute',
                    'routeStyles',
                    'ui.bootstrap',
                    'gme.ui.projectsDialog',
                    'gme.ui.headerPanel',

                    'gme.services'
                ]);

            // TODO: REMOVE - ONLY FOR TESTING
            WebGMEGlobal.gmeApp = gmeApp;
            gmeApp.controller('TestController', function ($scope, DataStoreService) {

                DataStoreService.connectToDatabase()
                    .then(function(db) {
                        console.log('opened database');
                        return db.openProject('myproject');
                    })
                    .then(function (data) {
                        console.log('opened project', data);
                    });
            });

            webGME.start( function(client) {

                gmeApp.value('gmeClient', client);
//                gmeApp.value('gmeClient', null);

                angular.bootstrap(document, [ 'gmeApp']);

            });

        });
    }
);
<|endoftext|>


<commit_before>// expand THREE.js Sphere to support collision tests versus Box3
// we are creating a vector outside the method scope to avoid spawning a new
// instance of Vector3 in every check
THREE.Sphere.__closest = new THREE.Vector3();
THREE.Sphere.prototype.intersectsBox = function (box) {
    // get box closest point to sphere center by clamping
    THREE.Sphere.__closest.set(this.center.x, this.center.y, this.center.z);
    THREE.Sphere.__closest.clamp(box.min, box.max);

    var distance =  this.center.distanceToSquared(THREE.Sphere.__closest);
    return distance < (this.radius * this.radius);
};

Game.init = function () {
    this.debug = false;

    this.knot = new THREE.Mesh(
        new THREE.TorusKnotGeometry(0.5, 0.1), this.materials.solid);
    this.knot.position.set(-3, 2, 1);
    this.knotBBox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());

    this.sphere = new THREE.Mesh(
        new THREE.SphereGeometry(1), this.materials.solid);
    this.sphere.position.set(2, 2, 0);
    // No need to call this:
    // this.sphere.geometry.computeBoundingSphere();
    // because it is done automatically by Three.js since it is needed for
    // frustrum culling
    this.sphereBBox = new THREE.Sphere(
        this.sphere.position,
        this.sphere.geometry.boundingSphere.radius);
    this.sphereShadow = Utils.createShadow(this.sphere, this.materials.shadow);

    // the object the user can control to check for collisions
    this.cube = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.75, 0.5),
        this.materials.solid);
    this.cube.position.set(2, 2, 2);
    this.cubeShadow = Utils.createShadow(this.cube, this.materials.shadow);
    this.cubeBBox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());

    // add objects to the scene
    this.scene.add(this.cube);
    this.scene.add(this.knot);
    this.scene.add(this.sphere);

    // add fake shadows to the scene
    this.scene.add(Utils.createShadow(this.knot, this.materials.shadow));
    this.scene.add(this.sphereShadow);
    this.scene.add(this.cubeShadow);

    this.controls = new THREE.TransformControls(
        this.camera, this.renderer.domElement);
    this.controls.space = 'world';
    this.controls.attach(this.cube);
    this.scene.add(this.controls);

    this.timestamp = 0;
};

Game.update = function (delta) {
    this.timestamp += delta;

    this.controls.update();

    // rotate the knot
    this.knot.rotation.x += (Math.PI / 4) * delta;
    this.knotBBox.setFromObject(this.knot); // re-calculate AABB

    // change sphere size
    var scale = 0.25 + Math.abs(Math.sin(this.timestamp));
    // this.sphere.scale.set(scale, scale, scale);
    // re-calculate bounding sphere
    // this.sphereBBox.radius = this.sphere.geometry.boundingSphere.radius * scale;
    // update shadow size
    // Utils.updateShadow(this.sphereShadow, this.sphere);

    // update the cube AABB and shadow
    this.cubeBBox.setFromObject(this.cube);
    Utils.updateShadow(this.cubeShadow, this.cube);

    this.sphere.material =
        this.sphereBBox.intersectsBox(this.cubeBBox)
        ? this.materials.colliding
        : this.materials.solid;

    this.knot.material = this.knotBBox.isIntersectionBox(this.cubeBBox)
        ? this.materials.colliding
        : this.materials.solid;
};

Game.toggleDebug = function () {
    this.debug = !this.debug;
    this.knotBBox.visible = !!this.debug;
    this.sphereBBox.visible = !!this.debug;
};
<commit_msg>re-enable sphere scaling in box vs others raw demo<commit_after>// expand THREE.js Sphere to support collision tests versus Box3
// we are creating a vector outside the method scope to avoid spawning a new
// instance of Vector3 in every check
THREE.Sphere.__closest = new THREE.Vector3();
THREE.Sphere.prototype.intersectsBox = function (box) {
    // get box closest point to sphere center by clamping
    THREE.Sphere.__closest.set(this.center.x, this.center.y, this.center.z);
    THREE.Sphere.__closest.clamp(box.min, box.max);

    var distance =  this.center.distanceToSquared(THREE.Sphere.__closest);
    return distance < (this.radius * this.radius);
};

Game.init = function () {
    this.debug = false;

    this.knot = new THREE.Mesh(
        new THREE.TorusKnotGeometry(0.5, 0.1), this.materials.solid);
    this.knot.position.set(-3, 2, 1);
    this.knotBBox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());

    this.sphere = new THREE.Mesh(
        new THREE.SphereGeometry(1), this.materials.solid);
    this.sphere.position.set(2, 2, 0);
    // No need to call this:
    // this.sphere.geometry.computeBoundingSphere();
    // because it is done automatically by Three.js since it is needed for
    // frustrum culling
    this.sphereBBox = new THREE.Sphere(
        this.sphere.position,
        this.sphere.geometry.boundingSphere.radius);
    this.sphereShadow = Utils.createShadow(this.sphere, this.materials.shadow);

    // the object the user can control to check for collisions
    this.cube = new THREE.Mesh(new THREE.BoxGeometry(0.75, 0.75, 0.5),
        this.materials.solid);
    this.cube.position.set(2, 2, 2);
    this.cubeShadow = Utils.createShadow(this.cube, this.materials.shadow);
    this.cubeBBox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());

    // add objects to the scene
    this.scene.add(this.cube);
    this.scene.add(this.knot);
    this.scene.add(this.sphere);

    // add fake shadows to the scene
    this.scene.add(Utils.createShadow(this.knot, this.materials.shadow));
    this.scene.add(this.sphereShadow);
    this.scene.add(this.cubeShadow);

    this.controls = new THREE.TransformControls(
        this.camera, this.renderer.domElement);
    this.controls.space = 'world';
    this.controls.attach(this.cube);
    this.scene.add(this.controls);

    this.timestamp = 0;
};

Game.update = function (delta) {
    this.timestamp += delta;

    this.controls.update();

    // rotate the knot
    this.knot.rotation.x += (Math.PI / 4) * delta;
    this.knotBBox.setFromObject(this.knot); // re-calculate AABB

    // change sphere size
    var scale = 0.25 + Math.abs(Math.sin(this.timestamp));
    this.sphere.scale.set(scale, scale, scale);
    // re-calculate bounding sphere
    this.sphereBBox.radius = this.sphere.geometry.boundingSphere.radius * scale;
    // update shadow size
    Utils.updateShadow(this.sphereShadow, this.sphere);

    // update the cube AABB and shadow
    this.cubeBBox.setFromObject(this.cube);
    Utils.updateShadow(this.cubeShadow, this.cube);

    this.sphere.material =
        this.sphereBBox.intersectsBox(this.cubeBBox)
        ? this.materials.colliding
        : this.materials.solid;

    this.knot.material = this.knotBBox.isIntersectionBox(this.cubeBBox)
        ? this.materials.colliding
        : this.materials.solid;
};

Game.toggleDebug = function () {
    this.debug = !this.debug;
    this.knotBBox.visible = !!this.debug;
    this.sphereBBox.visible = !!this.debug;
};
<|endoftext|>


<commit_before>

/** */
var Util = module.exports = function() {};

$.fn.extend({
  insertAtCaret: function(myValue) {
    var obj;
    console.log(this);
    if (typeof this[0].name != 'undefined') obj = this[0];
    else obj = this;

    var startPos = obj.selectionStart;
    var endPos = obj.selectionEnd;
    var scrollTop = obj.scrollTop;
    obj.value = obj.value.substring(0, startPos) + myValue + obj.value.substring(endPos, obj.value.length);
    obj.focus();
    obj.selectionStart = startPos + myValue.length;
    obj.selectionEnd = startPos + myValue.length;
    obj.scrollTop = scrollTop;
  }
});

/**
 * Resolves an issue with jQuery UI's autocomplete not resizing the DDL properly.
 * http://stackoverflow.com/questions/5643767/jquery-ui-autocomplete-width-not-set-correctly
 */
$.ui.autocomplete.prototype._resizeMenu = function() {
  var ul = this.menu.element;
  ul.outerWidth(this.element.outerWidth());
};

/**
 * Reverses the properties in a JavaScript object.
 * Found here:
 *http://stackoverflow.com/questions/10974493/javascript-quickly-lookup-value-in-object-like-we-can-with-properties
 *
 * @param {object} map The object that we are interested in flipping.
 * @return {object} An object with all keys and values swapped.
 */
Util.reverseObject = function(map) {
  var reverseMap = {};

  for (j in map) {
    if (Object.prototype.hasOwnProperty.call(map, j)) {
      reverseMap[map[j]] = j;
    }
  }

  return reverseMap;
};

/**
 * A generic UI element hider. Removes the object from the flow of the document.
 *
 * @param {jquery} object The object to apply the change to.
 * @param {boolean} state True for display:none, false for default.
 */
Util.setHidden = function(object, state) {
  if (state) {
    object.addClass('hidden');
  }
  else {
    object.removeClass('hidden');
  }
};

/**
 * A generic UI element hider. Doesn't remove the object from the flow of the document.
 *
 * @param {jquery} object The object to apply the change to.
 * @param {boolean} state True for visible, false for invisible.
 */
Util.setVisibility = function(object, state) {
  if (state) {
    object.removeClass('invisible');
  }
  else {
    object.addClass('invisible');
  }
};
<commit_msg>Added a new jquery function for determining object height.<commit_after>

/** */
var Util = module.exports = function() {};

$.fn.extend({
  insertAtCaret: function(myValue) {
    var obj;
    if (typeof this[0].name != 'undefined') {
      obj = this[0];
    }
    else {
      obj = this;
    }

    var startPos = obj.selectionStart;
    var endPos = obj.selectionEnd;
    var scrollTop = obj.scrollTop;
    obj.value = obj.value.substring(0, startPos) + myValue + obj.value.substring(endPos, obj.value.length);
    obj.focus();
    obj.selectionStart = startPos + myValue.length;
    obj.selectionEnd = startPos + myValue.length;
    obj.scrollTop = scrollTop;
  },
  actual : function ( method, options ){
    // From https://github.com/dreamerslab/jquery.actual/blob/master/jquery.actual.js
    // check if the jQuery method exist
    if (!this[method]) {
      throw '$.actual => The jQuery method "' + method + '" you called does not exist';
    }

    var defaults = {
      absolute      : false,
      clone         : false,
      includeMargin : false,
      display       : 'block'
    };

    var configs = $.extend(defaults, options);

    var $target = this.eq(0);
    var fix, restore;

    if (configs.clone === true) {
      fix = function() {
        var style = 'position: absolute !important; top: -1000 !important; ';

        // this is useful with css3pie
        $target = $target
        .clone()
        .attr('style', style)
        .appendTo('body');
      };

      restore = function() {
        // remove DOM element after getting the width
        $target.remove();
      };
    }
    else {
      var tmp = [];
      var style = '';
      var $hidden;

      fix = function() {
        // get all hidden parents
        $hidden = $target.parents().addBack().filter(':hidden');
        style += 'visibility: hidden !important; display: ' + configs.display + ' !important; ';

        if (configs.absolute === true) {
          style += 'position: absolute !important; ';
        }

        // save the origin style props
        // set the hidden el css to be got the actual value later
        $hidden.each(function() {
          // Save original style. If no style was set, attr() returns undefined
          var $this = $(this);
          var thisStyle = $this.attr('style');

          tmp.push(thisStyle);
          // Retain as much of the original style as possible, if there is one
          $this.attr('style', thisStyle ? thisStyle + ';' + style : style);
        });
      };

      restore = function() {
        // restore origin style values
        $hidden.each(function(i) {
          var $this = $(this);
          var _tmp = tmp[i];

          if(_tmp === undefined) {
            $this.removeAttr('style');
          }
          else {
            $this.attr('style', _tmp);
          }
        });
      };
    }

    fix();
    // get the actual value with user specific methed
    // it can be 'width', 'height', 'outerWidth', 'innerWidth'... etc
    // configs.includeMargin only works for 'outerWidth' and 'outerHeight'
    var actual = /(outer)/.test(method) ?
    $target[method](configs.includeMargin) :
    $target[method]();

    restore();
    // IMPORTANT, this plugin only return the value of the first element
    return actual;
  }
});

/**
* Resolves an issue with jQuery UI's autocomplete not resizing the DDL properly.
* http://stackoverflow.com/questions/5643767/jquery-ui-autocomplete-width-not-set-correctly
*/
$.ui.autocomplete.prototype._resizeMenu = function() {
  var ul = this.menu.element;
  ul.outerWidth(this.element.outerWidth());
};

/**
* Reverses the properties in a JavaScript object.
* Found here:
*http://stackoverflow.com/questions/10974493/javascript-quickly-lookup-value-in-object-like-we-can-with-properties
*
* @param {object} map The object that we are interested in flipping.
* @return {object} An object with all keys and values swapped.
*/
Util.reverseObject = function(map) {
  var reverseMap = {};

  for (j in map) {
    if (Object.prototype.hasOwnProperty.call(map, j)) {
      reverseMap[map[j]] = j;
    }
  }

  return reverseMap;
};

/**
* A generic UI element hider. Removes the object from the flow of the document.
*
* @param {jquery} object The object to apply the change to.
* @param {boolean} state True for display:none, false for default.
*/
Util.setHidden = function(object, state) {
  if (state) {
    object.addClass('hidden');
  }
  else {
    object.removeClass('hidden');
  }
};

/**
* A generic UI element hider. Doesn't remove the object from the flow of the document.
*
* @param {jquery} object The object to apply the change to.
* @param {boolean} state True for visible, false for invisible.
*/
Util.setVisibility = function(object, state) {
  if (state) {
    object.removeClass('invisible');
  }
  else {
    object.addClass('invisible');
  }
};
<|endoftext|>


<commit_before>//Set the regions
jviz.modules.ideogram.prototype.regions = function(data)
{
  //Check for undefined data
  if(typeof data === 'undefined'){ return this._regions.list; }

  //Set loading as true
  this.loading(true);

  //Reset the regions list
  this.regions.list = {};

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

    //Check if chromosome exists
    if(typeof this.regions.list[region.chromosome] === 'undefined')
    {
      //Create the chromosome
      this.regions.list[region.chromosome] = [];
    }

    //Check the region name or label
    region.name = (typeof region.name === 'undefined') ? 'Region ' + i : region.name;

    //Check the region label
    region.label = (typeof region.label === 'undefined') ? region.name : region.label;

    //Parse the start position
    region.start = parseInt(region.start);

    //Parse the end position
    region.end = parseInt(region.end);

    //Save the region
    this.regions.list[region.chromosome].push(region);
  }

  //Draw the preview
  this.draw(-1);

  //Return this
  return this;
};

//Get the regions by ajax connection
jviz.modules.ideogram.prototype.regionsAjax = function(opt)
{
  //Check the options
  if(typeof opt === 'undefined'){ return this; }
};

//Check over region
jviz.modules.ideogram.prototype.regionOver = function(x, y)
{
  //Check if user is hover the chromosome
  if(this.chromosomeOver(x, y) === false){ return -1; }

  //Save the margin
  var margin = this._chromosome.regions.click;

  //Find the region
  for(var i = 0; i < this._chromosome.regions.list.length; i++)
  {
    //Get the region
    var region = this._chromosome.regions.list[i];

    //Check the left position
    if(x < region.pstart - margin){ return -1; }

    //Check the right position
    if(region.pend + margin < x){ continue; }

    //Return the region index
    return i;
  }

  //Default, return -1
  return -1;
};

//Draw the region label
jviz.modules.ideogram.prototype.regionsDrawLabel = function(layer, index, opacity)
{
  //Check the opacity
  if(typeof opacity === 'undefined'){ var opacity = 1.0; }

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

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

  //Get the rectangle position x
  var rect_x = region.pmiddle - this._chromosome.regions.label.width / 2;

  //Get the rectangle position y
  var rect_y = this._chromosome.regions.label.posy;

  //Get the rectangle width
  var rect_width = this._chromosome.regions.label.width;

  //Get the rectangle height
  var rect_height = this._chromosome.regions.label.height;

  //Get the rectangle radius
  var rect_radius = this._chromosome.regions.label.radius;

  //Draw the rectangle
  canvas.Rect({ x: rect_x, y: rect_y, width: rect_width, height: rect_height, radius: rect_radius });

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

  //Create the label triangle
  var tri = [];

  //Add the start point
  tri.push([ region.pmiddle - this._chromosome.regions.label.triangle, rect_y ]);

  //Add the middle point
  tri.push([ region.pmiddle, rect_y - this._chromosome.regions.label.triangle ]);

  //Add the end point
  tri.push([ region.pmiddle + this._chromosome.regions.label.triangle, rect_y ]);

  //Draw the lines
  canvas.Line(tri);

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

  //Get the text
  var text_text = region.name;

  //Get the text position x
  var text_x = region.pmiddle;

  //Get the text position y
  var text_y = this._chromosome.regions.label.posy + this._chromosome.regions.label.text.margin;

  //Get the text font
  var text_font = this._chromosome.regions.label.text.font;

  //Get the text size
  var text_size = this._chromosome.regions.label.text.size;

  //Get the text align
  var text_align = this._chromosome.regions.label.text.align;

  //Get the text color
  var text_color = this._chromosome.regions.label.text.color;

  //Draw the text
  canvas.Text({ text: text_text, x: text_x, y: text_y, font: text_font, color: text_color, size: text_size, align: text_align });
};
<commit_msg>js/regions.js: fixed bug<commit_after>//Set the regions
jviz.modules.ideogram.prototype.regions = function(data)
{
  //Check for undefined data
  if(typeof data === 'undefined'){ return this._regions.list; }

  //Set loading as true
  this.loading(true);

  //Reset the regions list
  this._regions.list = {};

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

    //Check if chromosome exists
    if(typeof this._regions.list[region.chromosome] === 'undefined')
    {
      //Create the chromosome
      this._regions.list[region.chromosome] = [];
    }

    //Check the region name or label
    region.name = (typeof region.name === 'undefined') ? 'Region ' + i : region.name;

    //Check the region label
    region.label = (typeof region.label === 'undefined') ? region.name : region.label;

    //Parse the start position
    region.start = parseInt(region.start);

    //Parse the end position
    region.end = parseInt(region.end);

    //Save the region
    this._regions.list[region.chromosome].push(region);
  }

  //Draw the preview
  this.draw(-1);

  //Return this
  return this;
};

//Get the regions by ajax connection
jviz.modules.ideogram.prototype.regionsAjax = function(opt)
{
  //Check the options
  if(typeof opt === 'undefined'){ return this; }
};

//Check over region
jviz.modules.ideogram.prototype.regionOver = function(x, y)
{
  //Check if user is hover the chromosome
  if(this.chromosomeOver(x, y) === false){ return -1; }

  //Save the margin
  var margin = this._chromosome.regions.click;

  //Find the region
  for(var i = 0; i < this._chromosome.regions.list.length; i++)
  {
    //Get the region
    var region = this._chromosome.regions.list[i];

    //Check the left position
    if(x < region.pstart - margin){ return -1; }

    //Check the right position
    if(region.pend + margin < x){ continue; }

    //Return the region index
    return i;
  }

  //Default, return -1
  return -1;
};

//Draw the region label
jviz.modules.ideogram.prototype.regionsDrawLabel = function(layer, index, opacity)
{
  //Check the opacity
  if(typeof opacity === 'undefined'){ var opacity = 1.0; }

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

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

  //Get the rectangle position x
  var rect_x = region.pmiddle - this._chromosome.regions.label.width / 2;

  //Get the rectangle position y
  var rect_y = this._chromosome.regions.label.posy;

  //Get the rectangle width
  var rect_width = this._chromosome.regions.label.width;

  //Get the rectangle height
  var rect_height = this._chromosome.regions.label.height;

  //Get the rectangle radius
  var rect_radius = this._chromosome.regions.label.radius;

  //Draw the rectangle
  canvas.Rect({ x: rect_x, y: rect_y, width: rect_width, height: rect_height, radius: rect_radius });

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

  //Create the label triangle
  var tri = [];

  //Add the start point
  tri.push([ region.pmiddle - this._chromosome.regions.label.triangle, rect_y ]);

  //Add the middle point
  tri.push([ region.pmiddle, rect_y - this._chromosome.regions.label.triangle ]);

  //Add the end point
  tri.push([ region.pmiddle + this._chromosome.regions.label.triangle, rect_y ]);

  //Draw the lines
  canvas.Line(tri);

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

  //Get the text
  var text_text = region.name;

  //Get the text position x
  var text_x = region.pmiddle;

  //Get the text position y
  var text_y = this._chromosome.regions.label.posy + this._chromosome.regions.label.text.margin;

  //Get the text font
  var text_font = this._chromosome.regions.label.text.font;

  //Get the text size
  var text_size = this._chromosome.regions.label.text.size;

  //Get the text align
  var text_align = this._chromosome.regions.label.text.align;

  //Get the text color
  var text_color = this._chromosome.regions.label.text.color;

  //Draw the text
  canvas.Text({ text: text_text, x: text_x, y: text_y, font: text_font, color: text_color, size: text_size, align: text_align });
};
<|endoftext|>