<commit_before>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ArgumentsRequired, ExchangeError, OrderNotFound } = require ('./base/errors');

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

module.exports = class bkex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bkex',
            'name': 'BKEX',
            'countries': ['BVI'],
            'version': 'v2',
            'rateLimit': 1000,
            'has': {
                'createMarketOrder': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchCurrencies': false,
                'fetchTicker': true,
                'fetchTickers': false,
                'fetchOHLCV': true,
                'fetchOrderBook': true,
                'fetchTrades': false,
            },
            'urls': {
                'api': {
                    'public': 'https://api.bkex.io/v2',
                    'private': 'https://api.bkex.io/v2/u',
                },
                'www': 'https://www.bkex.com',
                'doc': [
                    'https://bkexapi.github.io/docs/api_en.htm',
                ],
                'fees': 'https://www.bkex.com/help/instruction/33',
            },
            'api': {
                'public': {
                    'get': [
                        'common/symbols',
                        'common/currencys',
                        'exchangeInfo',
                        'q/depth',
                        'q/deals',
                        'q/tickers',
                        'q/ticker/price',
                        'q/kline',
                    ],
                },
                'private': {
                    'get': [
                        'account/balance',
                        'order/openOrders',
                        'order/openOrder/detail',
                        'order/historyOrders',
                    ],
                    'post': [
                        'order/create',
                        'order/cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.09,
                    'taker': 0.12,
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        const response = await this.publicGetCommonSymbols (params);
        const data = this.safeValue (response, 'data');
        const numMarkets = data.length;
        if (numMarkets < 1) {
            throw new ExchangeError (this.id + ' publicGetExchangeInfo returned empty response: ' + this.json (data));
        }
        const result = [];
        for (let i = 0; i < data.length; i++) {
            const market = data[i];
            const id = this.safeString (market, 'symbol');
            const baseId = id.split ('_')[0];
            const quoteId = id.split ('_')[1];
            const base = this.safeCurrencyCode (baseId);
            const quote = this.safeCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const precision = {
                'amount': undefined,
                'price': this.safeInteger (market, 'pricePrecision'),
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const timestamp = this.milliseconds ();
        const request = this.extend ({
            'symbol': symbol,
        }, params);
        const response = await this.publicGetQTickers (request);
        const ticker = this.safeValue (response, 'data');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker[0], 'high'),
            'low': this.safeFloat (ticker[0], 'low'),
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'previousClose': undefined,
            'open': this.safeFloat (ticker[0], 'open'),
            'close': this.safeFloat (ticker[0], 'close'),
            'last': undefined,
            'percentage': undefined,
            'change': this.safeFloat (ticker[0], 'change'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker[0], 'volume'),
            'quoteVolume': this.safeFloat (ticker[0], 'quoteVolume'),
            'info': ticker[0],
        };
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'symbol': symbol,
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.publicGetQDepth (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        return this.parseOrderBook (data, undefined, 'bid', 'ask');
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '5m', since = undefined, limit = undefined) {
        return [
            this.timeInSeconds (ohlcv[0]),
            this.safeFloat (ohlcv, 1),
            this.safeFloat (ohlcv, 2),
            this.safeFloat (ohlcv, 3),
            this.safeFloat (ohlcv, 4),
            this.safeFloat (ohlcv, 5),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 1, params = {}) {
        const request = {
            'symbol': symbol,
            'size': limit,
        };
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        const duration = this.parseTimeframe (timeframe);
        const timerange = limit * duration * 1000;
        if (since === undefined) {
            if (limit === undefined) {
                throw new ArgumentsRequired (this.id + ' fetchOHLCV requires a since argument or a limit argument');
            } else {
                request['to'] = this.milliseconds ();
                request['from'] = request['to'] - timerange;
            }
        } else {
            request['from'] = parseInt (since);
            request['to'] = this.sum (request['from'], timerange);
        }
        const response = await this.publicGetQKline (request);
        // {
        //     "symbol": "BTC_USDT",
        //     "volume": 12321.1234,
        //     "open": 4124.3,
        //     "close": 3873.213,
        //     "low": 3521.1,
        //     "high": 4521.5,
        //     "quoteVolume": 71031537.978665,
        //     "ts": 1529739295000
        // }
        const data = this.safeValue (response, 'data', []);
        return this.parseOHLCVs (data, undefined, timeframe, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const query = this.omit (params, 'type');
        const response = await this.privateGetAccountBalance (query);
        const balances = this.safeValue (response, 'data');
        const wallets = this.safeValue (balances, 'WALLET');
        const result = { 'info': wallets };
        for (let i = 0; i < wallets.length; i++) {
            const wallet = wallets[i];
            const currencyId = wallet['currency'];
            const code = this.safeCurrencyCode (currencyId);
            const account = this.account ();
            account['free'] = this.safeFloat (wallet, 'available');
            account['total'] = this.safeFloat (wallet, 'total');
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const method = 'privatePostOrderCreate';
        const direction = side === 'buy' ? 'BID' : 'ASK';
        const request = {
            'volume': amount,
            'direction': direction,
            'symbol': symbol,
            'price': price,
            'type': type,
        };
        const response = await this[method] (this.extend (request, params));
        return {
            'id': this.safeValue (response, 'data'),
            'info': response,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderId': id,
        };
        return await this.privatePostOrderCancel (this.extend (request, params));
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOrders requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': this.safeString (market, 'id'),
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.privateGetOrderOpenOrders (this.extend (request, params));
        const result = this.safeValue (response, 'data');
        return this.parseOrders (this.safeValue (result, 'data'), market, since, limit);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        const request = {
            'orderId': id,
        };
        const response = await this.privateGetOrderOpenOrderDetail (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        if (!data) {
            throw new OrderNotFound (this.id + ' order ' + id + ' not found');
        }
        return this.parseOrder (data);
    }

    parseTrade (trade, market = undefined) {
        const timestamp = this.safeTimestamp (trade, 'createdTime');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const id = this.safeString (trade, 'id');
        const price = this.safeFloat (trade, 'price');
        const amount = this.safeFloat (trade, 'totalVolume');
        let cost = undefined;
        if (amount !== undefined) {
            if (price !== undefined) {
                cost = price * amount;
            }
        }
        const type = undefined;
        const side = this.safeString (trade, 'type');
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {};
        if (symbol !== undefined) {
            const market = this.market (symbol);
            request['symbol'] = market['id'];
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        const trades = await this.privateGetOrderHistoryOrders (this.extend (request, params));
        return this.parseTrades (trades, undefined, since, limit);
    }

    parseOrder (order, market = undefined) {
        const marketName = this.safeString (order, 'pair');
        market = market || this.findMarket (marketName);
        let timestamp = this.safeString (order, 'createdTime');
        if (timestamp !== undefined) {
            timestamp = Math.round (parseFloat (timestamp) * 1000);
        }
        const direction = this.safeValue (order, 'direction');
        const side = direction === 'BID' ? 'BUY' : 'SELL';
        const amount = this.safeFloat (order, 'totalAmount');
        const fillAmount = this.safeFloat (order, 'dealAmount', amount);
        const remaining = amount - fillAmount;
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': undefined,
            'status': undefined,
            'symbol': this.safeString (market, 'symbol'),
            'side': side,
            'type': this.safeString (order, 'orderType'),
            'price': this.safeFloat (order, 'price'),
            'cost': undefined,
            'amount': amount,
            'filled': fillAmount,
            'remaining': remaining,
            'fee': undefined,
            'info': order,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (method === 'GET') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        }
        if (api === 'private') {
            this.checkRequiredCredentials ();
            query = this.urlencode (query);
            if (method === 'POST') {
                body = query;
            }
            const queryArray = query.split ('&');
            const sortedQuery = this.sortBy (queryArray, 0).join ('&');
            const secret = this.encode (this.secret);
            const signature = this.hmac (sortedQuery, secret, 'sha256');
            headers = {
                'Cache-Control': 'no-cache',
                'Content-type': 'application/x-www-form-urlencoded',
                'X_ACCESS_KEY': this.apiKey,
                'X_SIGNATURE': signature,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        const httpCode = this.safeInteger (response, 'code', 200);
        if (response === undefined) {
            return;
        }
        if (code >= 400) {
            throw new ExchangeError (this.id + ' HTTP Error ' + code + ' reason: ' + reason);
        }
        if (httpCode >= 400) {
            const message = this.safeValue (response, 'msg', '');
            throw new ExchangeError (this.id + ' HTTP Error ' + httpCode + ' message: ' + message);
        }
    }
};
<commit_msg>fix fetchTicker function<commit_after>'use strict';

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

const Exchange = require ('./base/Exchange');
const { ArgumentsRequired, ExchangeError, OrderNotFound } = require ('./base/errors');

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

module.exports = class bkex extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'bkex',
            'name': 'BKEX',
            'countries': ['BVI'],
            'version': 'v2',
            'rateLimit': 1000,
            'has': {
                'createMarketOrder': false,
                'fetchOrder': true,
                'fetchOrders': true,
                'fetchOpenOrders': true,
                'fetchCurrencies': false,
                'fetchTickers': false,
                'fetchTicker': true,
                'fetchOHLCV': true,
                'fetchOrderBook': true,
                'fetchTrades': false,
            },
            'urls': {
                'api': {
                    'public': 'https://api.bkex.io/v2',
                    'private': 'https://api.bkex.io/v2/u',
                },
                'www': 'https://www.bkex.com',
                'doc': [
                    'https://bkexapi.github.io/docs/api_en.htm',
                ],
                'fees': 'https://www.bkex.com/help/instruction/33',
            },
            'api': {
                'public': {
                    'get': [
                        'common/symbols',
                        'common/currencys',
                        'exchangeInfo',
                        'q/depth',
                        'q/deals',
                        'q/tickers',
                        'q/ticker/price',
                        'q/kline',
                    ],
                },
                'private': {
                    'get': [
                        'account/balance',
                        'order/openOrders',
                        'order/openOrder/detail',
                        'order/historyOrders',
                    ],
                    'post': [
                        'order/create',
                        'order/cancel',
                    ],
                },
            },
            'fees': {
                'trading': {
                    'maker': 0.09,
                    'taker': 0.12,
                },
            },
        });
    }

    async fetchMarkets (params = {}) {
        const response = await this.publicGetCommonSymbols (params);
        const data = this.safeValue (response, 'data');
        const numMarkets = data.length;
        if (numMarkets < 1) {
            throw new ExchangeError (this.id + ' publicGetExchangeInfo returned empty response: ' + this.json (data));
        }
        const result = [];
        for (let i = 0; i < data.length; i++) {
            const market = data[i];
            const id = this.safeString (market, 'symbol');
            const baseId = id.split ('_')[0];
            const quoteId = id.split ('_')[1];
            const base = this.safeCurrencyCode (baseId);
            const quote = this.safeCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const precision = {
                'amount': undefined,
                'price': this.safeInteger (market, 'pricePrecision'),
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': undefined,
                        'max': undefined,
                    },
                    'price': {
                        'min': Math.pow (10, -precision['price']),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const timestamp = this.milliseconds ();
        const market = this.market (symbol);
        const request = this.extend ({
            'symbol': market['id'],
        }, params);
        const response = await this.publicGetQTickers (request);
        const ticker = this.safeValue (response, 'data');
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeFloat (ticker[0], 'high'),
            'low': this.safeFloat (ticker[0], 'low'),
            'bid': undefined,
            'bidVolume': undefined,
            'ask': undefined,
            'askVolume': undefined,
            'vwap': undefined,
            'previousClose': undefined,
            'open': this.safeFloat (ticker[0], 'open'),
            'close': this.safeFloat (ticker[0], 'close'),
            'last': undefined,
            'percentage': undefined,
            'change': this.safeFloat (ticker[0], 'change'),
            'average': undefined,
            'baseVolume': this.safeFloat (ticker[0], 'volume'),
            'quoteVolume': this.safeFloat (ticker[0], 'quoteVolume'),
            'info': ticker[0],
        };
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'symbol': symbol,
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.publicGetQDepth (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        return this.parseOrderBook (data, undefined, 'bid', 'ask');
    }

    parseOHLCV (ohlcv, market = undefined, timeframe = '5m', since = undefined, limit = undefined) {
        return [
            this.timeInSeconds (ohlcv[0]),
            this.safeFloat (ohlcv, 1),
            this.safeFloat (ohlcv, 2),
            this.safeFloat (ohlcv, 3),
            this.safeFloat (ohlcv, 4),
            this.safeFloat (ohlcv, 5),
        ];
    }

    async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 1, params = {}) {
        const request = {
            'symbol': symbol,
            'size': limit,
        };
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        if (since !== undefined) {
            request['since'] = parseInt (since / 1000);
        }
        const duration = this.parseTimeframe (timeframe);
        const timerange = limit * duration * 1000;
        if (since === undefined) {
            if (limit === undefined) {
                throw new ArgumentsRequired (this.id + ' fetchOHLCV requires a since argument or a limit argument');
            } else {
                request['to'] = this.milliseconds ();
                request['from'] = request['to'] - timerange;
            }
        } else {
            request['from'] = parseInt (since);
            request['to'] = this.sum (request['from'], timerange);
        }
        const response = await this.publicGetQKline (request);
        // {
        //     "symbol": "BTC_USDT",
        //     "volume": 12321.1234,
        //     "open": 4124.3,
        //     "close": 3873.213,
        //     "low": 3521.1,
        //     "high": 4521.5,
        //     "quoteVolume": 71031537.978665,
        //     "ts": 1529739295000
        // }
        const data = this.safeValue (response, 'data', []);
        return this.parseOHLCVs (data, undefined, timeframe, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const query = this.omit (params, 'type');
        const response = await this.privateGetAccountBalance (query);
        const balances = this.safeValue (response, 'data');
        const wallets = this.safeValue (balances, 'WALLET');
        const result = { 'info': wallets };
        for (let i = 0; i < wallets.length; i++) {
            const wallet = wallets[i];
            const currencyId = wallet['currency'];
            const code = this.safeCurrencyCode (currencyId);
            const account = this.account ();
            account['free'] = this.safeFloat (wallet, 'available');
            account['total'] = this.safeFloat (wallet, 'total');
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const method = 'privatePostOrderCreate';
        const direction = side === 'buy' ? 'BID' : 'ASK';
        const request = {
            'volume': amount,
            'direction': direction,
            'symbol': symbol,
            'price': price,
            'type': type,
        };
        const response = await this[method] (this.extend (request, params));
        return {
            'id': this.safeValue (response, 'data'),
            'info': response,
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'orderId': id,
        };
        return await this.privatePostOrderCancel (this.extend (request, params));
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOrders requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'symbol': this.safeString (market, 'id'),
        };
        if (limit !== undefined) {
            request['size'] = limit;
        }
        const response = await this.privateGetOrderOpenOrders (this.extend (request, params));
        const result = this.safeValue (response, 'data');
        return this.parseOrders (this.safeValue (result, 'data'), market, since, limit);
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        const request = {
            'orderId': id,
        };
        const response = await this.privateGetOrderOpenOrderDetail (this.extend (request, params));
        const data = this.safeValue (response, 'data');
        if (!data) {
            throw new OrderNotFound (this.id + ' order ' + id + ' not found');
        }
        return this.parseOrder (data);
    }

    parseTrade (trade, market = undefined) {
        const timestamp = this.safeTimestamp (trade, 'createdTime');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const id = this.safeString (trade, 'id');
        const price = this.safeFloat (trade, 'price');
        const amount = this.safeFloat (trade, 'totalVolume');
        let cost = undefined;
        if (amount !== undefined) {
            if (price !== undefined) {
                cost = price * amount;
            }
        }
        const type = undefined;
        const side = this.safeString (trade, 'type');
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': type,
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {};
        if (symbol !== undefined) {
            const market = this.market (symbol);
            request['symbol'] = market['id'];
        }
        if (limit !== undefined) {
            request['limit'] = limit;
        }
        const trades = await this.privateGetOrderHistoryOrders (this.extend (request, params));
        return this.parseTrades (trades, undefined, since, limit);
    }

    parseOrder (order, market = undefined) {
        const marketName = this.safeString (order, 'pair');
        market = market || this.findMarket (marketName);
        let timestamp = this.safeString (order, 'createdTime');
        if (timestamp !== undefined) {
            timestamp = Math.round (parseFloat (timestamp) * 1000);
        }
        const direction = this.safeValue (order, 'direction');
        const side = direction === 'BID' ? 'BUY' : 'SELL';
        const amount = this.safeFloat (order, 'totalAmount');
        const fillAmount = this.safeFloat (order, 'dealAmount', amount);
        const remaining = amount - fillAmount;
        return {
            'id': this.safeString (order, 'id'),
            'datetime': this.iso8601 (timestamp),
            'timestamp': timestamp,
            'lastTradeTimestamp': undefined,
            'status': undefined,
            'symbol': this.safeString (market, 'symbol'),
            'side': side,
            'type': this.safeString (order, 'orderType'),
            'price': this.safeFloat (order, 'price'),
            'cost': undefined,
            'amount': amount,
            'filled': fillAmount,
            'remaining': remaining,
            'fee': undefined,
            'info': order,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'][api] + '/' + this.implodeParams (path, params);
        let query = this.omit (params, this.extractParams (path));
        if (method === 'GET') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        }
        if (api === 'private') {
            this.checkRequiredCredentials ();
            query = this.urlencode (query);
            if (method === 'POST') {
                body = query;
            }
            const queryArray = query.split ('&');
            const sortedQuery = this.sortBy (queryArray, 0).join ('&');
            const secret = this.encode (this.secret);
            const signature = this.hmac (sortedQuery, secret, 'sha256');
            headers = {
                'Cache-Control': 'no-cache',
                'Content-type': 'application/x-www-form-urlencoded',
                'X_ACCESS_KEY': this.apiKey,
                'X_SIGNATURE': signature,
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        const httpCode = this.safeInteger (response, 'code', 200);
        if (response === undefined) {
            return;
        }
        if (code >= 400) {
            throw new ExchangeError (this.id + ' HTTP Error ' + code + ' reason: ' + reason);
        }
        if (httpCode >= 400) {
            const message = this.safeValue (response, 'msg', '');
            throw new ExchangeError (this.id + ' HTTP Error ' + httpCode + ' message: ' + message);
        }
    }
};
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

angular.module('codingBarrierApp')
        .controller('blogController', function ($rootScope, $sce, BloggerApi) {

            $rootScope.header = 'Code Barrier Blog';
            $rootScope.message = '';
            var blogPage = this;

            getBlog();

            function getBlog() {
                BloggerApi.getBlog()
                        .then(blogRetrievedSuccess, blogRetrievedFail);
            }

            function blogRetrievedSuccess(response) {
                blogPage.blog = response.data.items;
                console.log(response.data.items);
            }

            function blogRetrievedFail(response) {

            }

            blogPage.jumpBreak = function (post) {
                var postBreak = post.split("")[0];

                window.Prism.highlightAll();
                var jText = $('
').html(postBreak);
                jText.find("iframe").wrap('
');
                jText.find("iframe").addClass('embed-responsive-item');
                jText.find("img").addClass('img-responsive');
                return $sce.trustAsHtml(jText.html());

            };

            blogPage.extractPath = function (urlString) {
                var postUrl = new URL(urlString);
                return postUrl.pathname;
            };
        });
<commit_msg>Blog title changed to just Blog.<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

angular.module('codingBarrierApp')
        .controller('blogController', function ($rootScope, $sce, BloggerApi) {

            $rootScope.header = 'Blog';
            $rootScope.message = '';
            var blogPage = this;

            getBlog();

            function getBlog() {
                BloggerApi.getBlog()
                        .then(blogRetrievedSuccess, blogRetrievedFail);
            }

            function blogRetrievedSuccess(response) {
                blogPage.blog = response.data.items;
                console.log(response.data.items);
            }

            function blogRetrievedFail(response) {

            }

            blogPage.jumpBreak = function (post) {
                var postBreak = post.split("")[0];

                window.Prism.highlightAll();
                var jText = $('
').html(postBreak);
                jText.find("iframe").wrap('
');
                jText.find("iframe").addClass('embed-responsive-item');
                jText.find("img").addClass('img-responsive');
                return $sce.trustAsHtml(jText.html());

            };

            blogPage.extractPath = function (urlString) {
                var postUrl = new URL(urlString);
                return postUrl.pathname;
            };
        });
<|endoftext|>


<commit_before>describe('Links', function () {

    beforeEach(function () {
        angular.mock.module('formsAngular');
    });

    describe('simple subkey', function () {

        var $httpBackend, scope, ctrl, elm,
            subkeySchema = {
                "surname":{"enumValues":[],"regExp":null,"path":"surname","instance":"String","validators":[],"setters":[],"getters":[],"options":{"index":true,"list":{}},"_index":true,"$conditionalHandlers":{}},
                "forename":{"enumValues":[],"regExp":null,"path":"forename","instance":"String","validators":[],"setters":[],"getters":[],"options":{"index":true,"list":true},"_index":true,"$conditionalHandlers":{}},
                "exams":{
                    "schema":{
                        "subject":{"enumValues":[],"regExp":null,"path":"subject","instance":"String","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}},
                        "score":{"path":"score","instance":"Number","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}},
                        "examDate":{"path":"examDate","instance":"Date","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}}
                    },
                    "options":{
                        "form":{
                            "formStyle":"inline",
                            "subkey":{
                                "keyList":[{"subject":"English"}],
                                "container":"fieldset",
                                "title":"English Exam"
                            }
                        }
                    }
                }
            };

        afterEach(function () {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        describe('existing data with selected data present in first position',function() {

            beforeEach(inject(function (_$httpBackend_, $rootScope, $location, $controller, $compile) {
                $httpBackend = _$httpBackend_;
                $httpBackend.whenGET('api/schema/f_nested_schema/English').respond(subkeySchema);
                $httpBackend.whenGET('api/f_nested_schema/51c583d5b5c51226db418f16').respond({
                    "_id":"51c583d5b5c51226db418f16",
                    "surname":"Smith",
                    "forename":"Anne",
                    "exams":[
                        {
                            "subject":"English",
                            "examDate":"2013-05-12T23:00:00.000Z",
                            "score":83,
                            "result":"pass"
                        },
                        {
                            "subject":"Maths",
                            "examDate":"2013-05-11T23:00:00.000Z",
                            "score":97,
                            "result":"distinction"
                        }
                    ]
                });
                $location.$$path = '/f_nested_schema/English/51c583d5b5c51226db418f16/edit';
                elm = angular.element(
                    '<form name="myForm" class="form-horizontal compact">' +
                        '<form-input schema="formSchema"></form-input>' +
                        '</form>');
                scope = $rootScope.$new();
                ctrl = $controller("BaseCtrl", {$scope: scope});
                $httpBackend.flush();
                $compile(elm)(scope);
                scope.$digest();
            }));

            it('generates correct fields', function () {
                // correct number of fields - excluding subkey
                var input = elm.find('input');
                expect(input.length).toBe(4);

                // correct labels
                // correct ids
                // correct models
                // correct values
            });

        });

    });

});

<commit_msg>label tests added<commit_after>describe('Links', function () {

    beforeEach(function () {
        angular.mock.module('formsAngular');
    });

    describe('simple subkey', function () {

        var $httpBackend, scope, ctrl, elm,
            subkeySchema = {
                "surname":{"enumValues":[],"regExp":null,"path":"surname","instance":"String","validators":[],"setters":[],"getters":[],"options":{"index":true,"list":{}},"_index":true,"$conditionalHandlers":{}},
                "forename":{"enumValues":[],"regExp":null,"path":"forename","instance":"String","validators":[],"setters":[],"getters":[],"options":{"index":true,"list":true},"_index":true,"$conditionalHandlers":{}},
                "exams":{
                    "schema":{
                        "subject":{"enumValues":[],"regExp":null,"path":"subject","instance":"String","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}},
                        "score":{"path":"score","instance":"Number","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}},
                        "examDate":{"path":"examDate","instance":"Date","validators":[],"setters":[],"getters":[],"options":{},"_index":null,"$conditionalHandlers":{}}
                    },
                    "options":{
                        "form":{
                            "formStyle":"inline",
                            "subkey":{
                                "keyList":[{"subject":"English"}],
                                "container":"fieldset",
                                "title":"English Exam"
                            }
                        }
                    }
                }
            };

        afterEach(function () {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        ddescribe('existing data with selected data present in first position',function() {

            beforeEach(inject(function (_$httpBackend_, $rootScope, $location, $controller, $compile) {
                $httpBackend = _$httpBackend_;
                $httpBackend.whenGET('api/schema/f_nested_schema/English').respond(subkeySchema);
                $httpBackend.whenGET('api/f_nested_schema/51c583d5b5c51226db418f16').respond({
                    "_id":"51c583d5b5c51226db418f16",
                    "surname":"Smith",
                    "forename":"Anne",
                    "exams":[
                        {
                            "subject":"English",
                            "examDate":"2013-05-12T23:00:00.000Z",
                            "score":83,
                            "result":"pass"
                        },
                        {
                            "subject":"Maths",
                            "examDate":"2013-05-11T23:00:00.000Z",
                            "score":97,
                            "result":"distinction"
                        }
                    ]
                });
                $location.$$path = '/f_nested_schema/English/51c583d5b5c51226db418f16/edit';
                elm = angular.element(
                    '<form name="myForm" class="form-horizontal compact">' +
                        '<form-input schema="formSchema"></form-input>' +
                        '</form>');
                scope = $rootScope.$new();
                ctrl = $controller("BaseCtrl", {$scope: scope});
                $httpBackend.flush();
                $compile(elm)(scope);
                scope.$digest();
            }));

            it('generates correct fields', function () {
                // correct number of fields - excluding subkey
                var input = elm.find('input');
                expect(input.length).toBe(4);

                var label = angular.element(elm.find('label')[0]);
                expect(label.text()).toBe('Surname');
                var label = angular.element(elm.find('label')[1]);
                expect(label.text()).toBe('Forename');
                var label = angular.element(elm.find('label')[2]);
                expect(label.text()).toBe('Score');
                var label = angular.element(elm.find('label')[3]);
                expect(label.text()).toBe('Exam Date');

                // correct ids
                // correct models
                // correct values
            });

        });

    });

});

<|endoftext|>


<commit_before>/**
 * Creates a DOM input element of type submit, and attaches event listener to
 * it.
 * @param {string} action - The action for the post form.
 * @param {string} value - The value of the button.
 * @return An input DOM element.
 */
function createInputSubmit(action, value) {
  let input = document.createElement('input');
  input.type = 'submit';
  input.formAction = action;
  input.value = value;
  addEvent(input, 'click', function(e) {
    let el = e.currentTarget;
    el.form.action = el.formAction;
  });
  return input;
}

function createCommentForm(commentNode) {
  let form = document.createElement('form');
  form.id = commentNode.id + '-edit';
  form.dataset.id = commentNode.id;
  form.classList.add('row');
  form.method = 'post';
  form.action = commentNode.querySelector('.edit-comment').href;

  let div = document.createElement('div');
  div.classList.add('col-md-8', 'col-centered');

  let textArea = document.createElement('textarea');
  textArea.classList.add('form-control', 'input-lg');
  textArea.name = 'text';
  textArea.value = commentNode.querySelector('p').innerHTML;

  div.appendChild(textArea);
  div.appendChild(createInputSubmit('cancel', 'Cancel'));
  div.appendChild(createInputSubmit('save', 'Save'));
  form.appendChild(div);

  return form;
}

// Hides a comment and displays a form to edit a given comment, bringing focus
// to the form.
function tryEditComment(e) {
  e.preventDefault();
  let comment = document.getElementById(e.currentTarget.dataset.id);
  let form = createCommentForm(comment);
  addEvent(form, 'submit', editComment);
  comment.style.display = 'none';
  comment.insertAdjacentElement('afterend', form);
  form.focus();
}

// Removes the form to edit a comment, the old comment, and adds the modified
// comment.
function refreshComment(data) {
  let form = document.getElementById(data.id + '-edit');
  let oldComment = form.previousElementSibling;
  let comments = oldComment.parentNode;
  comments.removeChild(form);
  if (!oldComment.previousElementSibling) {
    // This comment is first comment
    comments.removeChild(oldComment);
    comments.insertAdjacentHTML('afterbegin', data.comment);
  } else {
    // This is not the first comment
    let sibling = oldComment.previousElementSibling;
    comments.removeChild(oldComment);
    sibling.insertAdjacentHTML('afterend', data.comment);
  }
  let comment = comments.querySelector('#' + data.id);
  addEvent(comment.querySelector('.delete-comment'), 'click', deleteComment);
  addEvent(comment.querySelector('.edit-comment'), 'click', tryEditComment);
}

// Removes the form to edit a comment and re-displays the original comment.
function putCommentBack(form) {
  form.previousElementSibling.style.display = 'block';
  form.parentNode.removeChild(form);
}

function editComment(e) {
  e.preventDefault();
  let form = e.currentTarget;
  if (form.action.includes('cancel')) {
    putCommentBack(form);
    return;
  }
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.responseText);
      refreshComment(data);
    }
    // TODO: need to revert changes if there is an error
  };
  xhr.open('POST', '/edit-comment', true);
  let msg = JSON.stringify({
    'id': form.dataset.id,
    'text': form.elements.text.value
  });
  xhr.send(msg);
}

function deleteComment(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.responseText);
      if (data.id) {
        var el = document.getElementById(data.id);
        el.parentNode.removeChild(el);
      }
    }
  };
  xhr.open('POST', '/delete-comment', true);
  xhr.send(JSON.stringify({'id': e.currentTarget.dataset.id}));
}

function createComment(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      let data = JSON.parse(this.responseText);
      let comments = document.querySelector('.blog-comments');
      comments.insertAdjacentHTML('beforeend', data.comment);
      document.querySelector('form').reset();
      let lc = comments.lastChild;
      lc.scrollIntoView();
      addEvent(lc.querySelector('.edit-comment'), 'click', tryEditComment);
      addEvent(lc.querySelector('.delete-comment'), 'click', deleteComment);
    }
  };
  let form = document.querySelector('form');
  xhr.open('POST', form.action, true);
  let msg = JSON.stringify({'text': form.elements.text.value});
  xhr.send(msg);
}

function clickLike(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      let response = JSON.parse(this.responseText);
      if (response.add) {
        // Enable red heart and increase likes count
        let cl = document.getElementById('likes-heart').classList;
        cl.add('red-heart');
        cl.remove('normal');
        let el = document.querySelector('.likes-number');
        el.innerText = parseInt(el.innerText, 10) + 1;
      } else if (response.remove) {
        // Disable red heart and decrease likes count
        let cl = document.getElementById('likes-heart').classList;
        cl.remove('red-heart');
        cl.add('normal');
        let el = document.querySelector('.likes-number');
        let count = parseInt(el.innerText, 10);
        // double check that we are not taking number below zero
        if (count) {
          el.innerText = count - 1;
        }
      }
    }
  };
  let href = document.getElementById('like-button').href;
  xhr.open('GET', href, true);
  xhr.send();
}

(function() {
  let delLinks = document.querySelectorAll('.delete-comment');
  for (let i = 0; i < delLinks.length; i++) {
    addEvent(delLinks[i], 'click', deleteComment);
  }

  let editLinks = document.querySelectorAll('.edit-comment');
  for (let i = 0; i < editLinks.length; i++) {
    addEvent(editLinks[i], 'click', tryEditComment);
  }

  let form = document.querySelector('form');
  if (form.action.includes('create-comment')) {
    addEvent(form, 'submit', createComment);
  }

  addEvent(document.getElementById('like-button'), 'click', clickLike);
})();
<commit_msg>Create doc for createCommentForm()<commit_after>/**
 * Creates a DOM input element of type submit, and attaches event listener to
 * it.
 * @param {string} action - The action for the post form.
 * @param {string} value - The value of the button.
 * @return {Node} An input DOM element.
 */
function createInputSubmit(action, value) {
  let input = document.createElement('input');
  input.type = 'submit';
  input.formAction = action;
  input.value = value;
  addEvent(input, 'click', function(e) {
    let el = e.currentTarget;
    el.form.action = el.formAction;
  });
  return input;
}

/**
 * Creates a form with a textarea for users to edit a comment.
 * @param {Node} commentNode - A node containing a comment.
 * @return {Node} A DOM form node.
 */
function createCommentForm(commentNode) {
  let form = document.createElement('form');
  form.id = commentNode.id + '-edit';
  form.dataset.id = commentNode.id;
  form.classList.add('row');
  form.method = 'post';
  form.action = commentNode.querySelector('.edit-comment').href;

  let div = document.createElement('div');
  div.classList.add('col-md-8', 'col-centered');

  let textArea = document.createElement('textarea');
  textArea.classList.add('form-control', 'input-lg');
  textArea.name = 'text';
  textArea.value = commentNode.querySelector('p').innerHTML;

  div.appendChild(textArea);
  div.appendChild(createInputSubmit('cancel', 'Cancel'));
  div.appendChild(createInputSubmit('save', 'Save'));
  form.appendChild(div);

  return form;
}

// Hides a comment and displays a form to edit a given comment, bringing focus
// to the form.
function tryEditComment(e) {
  e.preventDefault();
  let comment = document.getElementById(e.currentTarget.dataset.id);
  let form = createCommentForm(comment);
  addEvent(form, 'submit', editComment);
  comment.style.display = 'none';
  comment.insertAdjacentElement('afterend', form);
  form.focus();
}

// Removes the form to edit a comment, the old comment, and adds the modified
// comment.
function refreshComment(data) {
  let form = document.getElementById(data.id + '-edit');
  let oldComment = form.previousElementSibling;
  let comments = oldComment.parentNode;
  comments.removeChild(form);
  if (!oldComment.previousElementSibling) {
    // This comment is first comment
    comments.removeChild(oldComment);
    comments.insertAdjacentHTML('afterbegin', data.comment);
  } else {
    // This is not the first comment
    let sibling = oldComment.previousElementSibling;
    comments.removeChild(oldComment);
    sibling.insertAdjacentHTML('afterend', data.comment);
  }
  let comment = comments.querySelector('#' + data.id);
  addEvent(comment.querySelector('.delete-comment'), 'click', deleteComment);
  addEvent(comment.querySelector('.edit-comment'), 'click', tryEditComment);
}

// Removes the form to edit a comment and re-displays the original comment.
function putCommentBack(form) {
  form.previousElementSibling.style.display = 'block';
  form.parentNode.removeChild(form);
}

function editComment(e) {
  e.preventDefault();
  let form = e.currentTarget;
  if (form.action.includes('cancel')) {
    putCommentBack(form);
    return;
  }
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.responseText);
      refreshComment(data);
    }
    // TODO: need to revert changes if there is an error
  };
  xhr.open('POST', '/edit-comment', true);
  let msg = JSON.stringify({
    'id': form.dataset.id,
    'text': form.elements.text.value
  });
  xhr.send(msg);
}

function deleteComment(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var data = JSON.parse(this.responseText);
      if (data.id) {
        var el = document.getElementById(data.id);
        el.parentNode.removeChild(el);
      }
    }
  };
  xhr.open('POST', '/delete-comment', true);
  xhr.send(JSON.stringify({'id': e.currentTarget.dataset.id}));
}

function createComment(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      let data = JSON.parse(this.responseText);
      let comments = document.querySelector('.blog-comments');
      comments.insertAdjacentHTML('beforeend', data.comment);
      document.querySelector('form').reset();
      let lc = comments.lastChild;
      lc.scrollIntoView();
      addEvent(lc.querySelector('.edit-comment'), 'click', tryEditComment);
      addEvent(lc.querySelector('.delete-comment'), 'click', deleteComment);
    }
  };
  let form = document.querySelector('form');
  xhr.open('POST', form.action, true);
  let msg = JSON.stringify({'text': form.elements.text.value});
  xhr.send(msg);
}

function clickLike(e) {
  e.preventDefault();
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      let response = JSON.parse(this.responseText);
      if (response.add) {
        // Enable red heart and increase likes count
        let cl = document.getElementById('likes-heart').classList;
        cl.add('red-heart');
        cl.remove('normal');
        let el = document.querySelector('.likes-number');
        el.innerText = parseInt(el.innerText, 10) + 1;
      } else if (response.remove) {
        // Disable red heart and decrease likes count
        let cl = document.getElementById('likes-heart').classList;
        cl.remove('red-heart');
        cl.add('normal');
        let el = document.querySelector('.likes-number');
        let count = parseInt(el.innerText, 10);
        // double check that we are not taking number below zero
        if (count) {
          el.innerText = count - 1;
        }
      }
    }
  };
  let href = document.getElementById('like-button').href;
  xhr.open('GET', href, true);
  xhr.send();
}

(function() {
  let delLinks = document.querySelectorAll('.delete-comment');
  for (let i = 0; i < delLinks.length; i++) {
    addEvent(delLinks[i], 'click', deleteComment);
  }

  let editLinks = document.querySelectorAll('.edit-comment');
  for (let i = 0; i < editLinks.length; i++) {
    addEvent(editLinks[i], 'click', tryEditComment);
  }

  let form = document.querySelector('form');
  if (form.action.includes('create-comment')) {
    addEvent(form, 'submit', createComment);
  }

  addEvent(document.getElementById('like-button'), 'click', clickLike);
})();
<|endoftext|>


<commit_before>$(function(){
$normal = $('.bg-normal');
$blur = $('.bg-blur');
$(window).on('scroll', function() {
   $st = $(this).scrollTop();
   if((0 + $st/150) > 1) $blur.css({ 'opacity' : 1 });
   else {
   $blur.css({ 'opacity' : (0 + $st/150) });
}
});});
<commit_msg>delete useless js file<commit_after><|endoftext|>


<commit_before>var max_cookie = 4096;

function init_chat() {
    $(window).bind("resize", function () {
	    adjust_panel($(".roompanel"));
	});

    $(".roomname").bind("click", onroomclick);

    $(document).bind("click", function() {
	    $(".roompanel").hide();
	    $(".roomname").removeClass("active");
	});
    $(".roompanel ul").bind("click", stop_propagation);
    $(".roompanel textarea").bind("click", stop_propagation);

    $(".roompanel textarea").autoResize({extraSpace: 0, animateDuration: 100, limit: 100})
	.bind("keypress", onenter);
    $("#global").data("wid", "global");
    $("#users").data("wid", "users");

    $("#users div textarea").jsonSuggest(function(text, wildCard, caseSensitive, notCharacter, cb){
	    username_typeahead(text, cb);
	}, {"ajaxResults": true, minCharacters: 3, "onSelect": typeahead_select}).unbind("keypress");

    var rooms = JSON.parse($.cookie("we-chat-rooms"));
    if (rooms == null || rooms.length == 0) {
	rooms = $(".room").map(function() {return {"wid": $(this).data("wid")
						   , "title": $(this).find("div h3").text()}}).toArray();
	$.cookie("we-chat-rooms", JSON.stringify(rooms))
    }
    var messages = JSON.parse($.cookie("we-chat"), rooms);
    $(".user").bind("dblclick", onuserclick);
    if (messages == null) {
	return;
    }
    messages.reverse();
    var newrooms = $(".room").map(function() {return {"wid": $(this).data("wid")
						      , "title": $(this).find("div h3").text()}}).toArray();
    var newmessages = [];
    var roomidxmap = {};
    for (var i = 0; i < newrooms.length; i += 1) {
	roomidxmap[i] = i;
    }
    for (var i = 0; i < messages.length; i += 1) {
	var m = messages[i];
	var idx = m.substr(0, m.indexOf("."));
	var rest = m.substr(m.indexOf(".") + 1);
	var sender = rest.substr(0, rest.indexOf(":"));
	var msg = rest.substr(rest.indexOf(":") + 1);
	var r = rooms[idx];
	if (r != null) {
	    var chatw = $(".room").filter(function(idx){return $(this).data("wid") == r.wid});
	    if (chatw.length == 0) {
		chatw = add_chat(r.wid, r.title, false);
		roomidxmap[idx] = newrooms.length;
		newrooms.push(r);
	    }
	    show_message({"wid": r.wid, "sender": sender, "message": msg}, chatw);
	    newmessages.push("" + roomidxmap[idx] + "." + sender + ":" + msg);
	}
    }
    newmessages.reverse();
    $.cookie("we-chat-rooms", JSON.stringify(newrooms));
    $.cookie("we-chat", JSON.stringify(newmessages));
}

function username_typeahead(text, callback) {
    $.getJSON("action.json?usernames/" + text,
	      function(data){
		  callback(
			   $.map(data,
				 function(e, i){return {"text": e};}));
		      });
}

function typeahead_select(selected) {
    $("#users div textarea").val("");
    var url = "action.json?chat/users/" + selected.text;
    $.post(url);
}

function adjust_panel(panel){
    var height = $(window).height();
    var max = height - 100;
    panel.css("max-height", max);
    panel.find("ul").css("max-height", max - 22);
}

function onenter(e){
    if (e.keyCode != "13"){
	return;
    }
    e.preventDefault();
    var text = $(this).val();
    if (!text.match(/\S+/g)) {
	return;
    }
    $(this).val("");
    var target = $(this).parent().parent().data("wid");
    var url = "action.json?chat/" + target + "/" + text;
    $.post(url);
}

function add_chat(wid, title, open){
    var room = $(".room").filter(function(idx){return $(this).data("wid") == wid});
    if (room.length > 0) {
	if (!room.find("div").is(":visible") && open) {
	    room.find("a").click();
	}
	return;
    }
    var ta = $("<textarea></textarea>").attr("rows", "1").bind("keypress", onenter)
	.bind("click", stop_propagation);
    var d = $("

").addClass("roompanel")
	.append($("

").html(title)
		.append($("")
			.bind("click", function(){remove_chat(wid)})))
	.append($("

").bind("click", stop_propagation))
	.append(ta);
    var res = $("").data("wid", wid).addClass("room")
	.append($("").addClass("roomname").bind("click", onroomclick).text(title))
	.append(d);
    $("#footpanel").append(res);
    adjust_panel(d);
    ta.autoResize({extraSpace: 0, animateDuration: 100, limit: 100});
    var rooms =  JSON.parse($.cookie("we-chat-rooms"));
    if (rooms == null) {
	rooms = [];
    }
    rooms.push({"wid": wid, "title": title});
    $.cookie("we-chat-rooms", JSON.stringify(rooms));
    if (open) {
	res.find("a").click();
    }
    return res;
}

function remove_chat(wid) {
    var rooms = JSON.parse($.cookie("we-chat-rooms"));
    var messages = JSON.parse($.cookie("we-chat"));
    var roomidx = 0;
    while (roomidx < rooms.length && rooms[roomidx].wid != wid) {
	roomidx += 1;
    }
    if (roomidx == rooms.length) {
	return;
    }
    var newmessages = [];
    var prefix = "" + roomidx + ".";
    messages.reverse();
    for (var i = 0; i < messages.length; i += 1) {
	if (messages[i].indexOf(prefix) != 0) {
	    newmessages.push(messages[i])
	}
    }
    $.cookie("we-chat", JSON.stringify(newmessages));
    $(".room").filter(function(idx){return $(this).data("wid") == wid}).remove();
}

function start_chat(nametxt) {
    var wid = nametxt;
    if (wid.indexOf("@") < 0) {
	wid += "@gmail.com";
    }
    add_chat(wid, nametxt, true);
}

function onuserclick() {
    start_chat($(this).text());
}

function stop_propagation(e) {
    e.stopPropagation();
}
function onroomclick () {
    if($(this).next(".roompanel").is(":visible")){
	$(this).next(".roompanel").hide();
	$(".roomname").removeClass("active");
    } else {
	$(".roompanel").hide();
	$(this).next(".roompanel").show();
	$(".roomname").removeClass("active");
	$(this).toggleClass("active");
	$(this).parent().find("div textarea").focus();
	var blinker = $(this).data("blink");
	if (blinker != null) {
	    window.clearInterval(blinker);
	    $(this).data("blink", null);
	}
    }
    return false;
}

function anchor_blink(anchor, interval) {
    anchor.toggleClass("blink");
    window.setTimeout(function(){anchor.toggleClass("blink");}, interval);
}

// default handlers
function handle_chat_add(v) {
    add_chat(v.wid, v.title, true);
}

function show_message(v, room) {
    var wid = v.wid;
    var message = decodeURIComponent(v.message);
    var sender = v.sender;
    var res;
    if (sender == "own") {
	res = "
" + message + "
";
    } else if (sender == "sys") {
	res = "
" + message + "
";
    } else if (sender != null && sender != "") {
	res = "
" + sender + ": " + message + "
";
    } else {
	res = "
" + message + "
";
    }
    room.find("div ul").append(res);
}

function handle_chat_message(v) {
    var room = $(".room").filter(function(idx){return $(this).data("wid") == v.wid});
    if (room.length == 0) {
	var wid = v.wid;
	room = add_chat(wid, wid.substring(0, wid.lastIndexOf("@")), true);
    }
    show_message(v, room);
    if (room.find(".roompanel").is(":not(:visible)") && v.sender != "own") {
	var anc = room.find(".roomname");
	if (anc.data("blink") != null) {
	    return;
	}
	anc.data("blink", window.setInterval(function(){anchor_blink(anc, 500)}, 1000))
    }
    var stored =  JSON.parse($.cookie("we-chat"));
    var rooms =  JSON.parse($.cookie("we-chat-rooms"));
    var i = 0;
    while (v.wid != rooms[i].wid) {
	i += 1;
    }
    if (stored == null) {
	stored = []
    }
    var sender = v.sender;
    if (sender == null) {
	sender = "";
    }
    stored.splice(0, 0, i + "." + sender + ":" + v.message);
    var tostore = JSON.stringify(stored);
    while (tostore.lendth > max_cookie) {
	stored.pop();
	tostore = JSON.stringify(stored);
    }
    $.cookie("we-chat", tostore);
}

<commit_msg>remove legacy double-click-on-username support<commit_after>var max_cookie = 4096;

function init_chat() {
    $(window).bind("resize", function () {
	    adjust_panel($(".roompanel"));
	});

    $(".roomname").bind("click", onroomclick);

    $(document).bind("click", function() {
	    $(".roompanel").hide();
	    $(".roomname").removeClass("active");
	});
    $(".roompanel ul").bind("click", stop_propagation);
    $(".roompanel textarea").bind("click", stop_propagation);

    $(".roompanel textarea").autoResize({extraSpace: 0, animateDuration: 100, limit: 100})
	.bind("keypress", onenter);
    $("#global").data("wid", "global");
    $("#users").data("wid", "users");

    $("#users div textarea").jsonSuggest(function(text, wildCard, caseSensitive, notCharacter, cb){
	    username_typeahead(text, cb);
	}, {"ajaxResults": true, minCharacters: 3, "onSelect": typeahead_select}).unbind("keypress");

    var rooms = JSON.parse($.cookie("we-chat-rooms"));
    if (rooms == null || rooms.length == 0) {
	rooms = $(".room").map(function() {return {"wid": $(this).data("wid")
						   , "title": $(this).find("div h3").text()}}).toArray();
	$.cookie("we-chat-rooms", JSON.stringify(rooms))
    }
    var messages = JSON.parse($.cookie("we-chat"), rooms);
    if (messages == null) {
	return;
    }
    messages.reverse();
    var newrooms = $(".room").map(function() {return {"wid": $(this).data("wid")
						      , "title": $(this).find("div h3").text()}}).toArray();
    var newmessages = [];
    var roomidxmap = {};
    for (var i = 0; i < newrooms.length; i += 1) {
	roomidxmap[i] = i;
    }
    for (var i = 0; i < messages.length; i += 1) {
	var m = messages[i];
	var idx = m.substr(0, m.indexOf("."));
	var rest = m.substr(m.indexOf(".") + 1);
	var sender = rest.substr(0, rest.indexOf(":"));
	var msg = rest.substr(rest.indexOf(":") + 1);
	var r = rooms[idx];
	if (r != null) {
	    var chatw = $(".room").filter(function(idx){return $(this).data("wid") == r.wid});
	    if (chatw.length == 0) {
		chatw = add_chat(r.wid, r.title, false);
		roomidxmap[idx] = newrooms.length;
		newrooms.push(r);
	    }
	    show_message({"wid": r.wid, "sender": sender, "message": msg}, chatw);
	    newmessages.push("" + roomidxmap[idx] + "." + sender + ":" + msg);
	}
    }
    newmessages.reverse();
    $.cookie("we-chat-rooms", JSON.stringify(newrooms));
    $.cookie("we-chat", JSON.stringify(newmessages));
}

function username_typeahead(text, callback) {
    $.getJSON("action.json?usernames/" + text,
	      function(data){
		  callback(
			   $.map(data,
				 function(e, i){return {"text": e};}));
		      });
}

function typeahead_select(selected) {
    $("#users div textarea").val("");
    var url = "action.json?chat/users/" + selected.text;
    $.post(url);
}

function adjust_panel(panel){
    var height = $(window).height();
    var max = height - 100;
    panel.css("max-height", max);
    panel.find("ul").css("max-height", max - 22);
}

function onenter(e){
    if (e.keyCode != "13"){
	return;
    }
    e.preventDefault();
    var text = $(this).val();
    if (!text.match(/\S+/g)) {
	return;
    }
    $(this).val("");
    var target = $(this).parent().parent().data("wid");
    var url = "action.json?chat/" + target + "/" + text;
    $.post(url);
}

function add_chat(wid, title, open){
    var room = $(".room").filter(function(idx){return $(this).data("wid") == wid});
    if (room.length > 0) {
	if (!room.find("div").is(":visible") && open) {
	    room.find("a").click();
	}
	return;
    }
    var ta = $("<textarea></textarea>").attr("rows", "1").bind("keypress", onenter)
	.bind("click", stop_propagation);
    var d = $("

").addClass("roompanel")
	.append($("

").html(title)
		.append($("")
			.bind("click", function(){remove_chat(wid)})))
	.append($("

").bind("click", stop_propagation))
	.append(ta);
    var link = $("").addClass("roomname").bind("click", onroomclick).text(title);
    var res = $("").data("wid", wid).addClass("room")
	.append(link)
	.append(d);
    $("#footpanel").append(res);
    adjust_panel(d);
    ta.autoResize({extraSpace: 0, animateDuration: 100, limit: 100});
    var rooms =  JSON.parse($.cookie("we-chat-rooms"));
    if (rooms == null) {
	rooms = [];
    }
    rooms.push({"wid": wid, "title": title});
    $.cookie("we-chat-rooms", JSON.stringify(rooms));
    if (open) {
	setTimeout(function(){link.click()}, 100);
    }
    return res;
}

function remove_chat(wid) {
    var rooms = JSON.parse($.cookie("we-chat-rooms"));
    var messages = JSON.parse($.cookie("we-chat"));
    var roomidx = 0;
    while (roomidx < rooms.length && rooms[roomidx].wid != wid) {
	roomidx += 1;
    }
    if (roomidx == rooms.length) {
	return;
    }
    var newmessages = [];
    var prefix = "" + roomidx + ".";
    messages.reverse();
    for (var i = 0; i < messages.length; i += 1) {
	if (messages[i].indexOf(prefix) != 0) {
	    newmessages.push(messages[i])
	}
    }
    $.cookie("we-chat", JSON.stringify(newmessages));
    $(".room").filter(function(idx){return $(this).data("wid") == wid}).remove();
}

function start_chat(nametxt) {
    var wid = nametxt;
    if (wid.indexOf("@") < 0) {
	wid += "@gmail.com";
    }
    add_chat(wid, nametxt, true);
}

function onuserclick() {
    start_chat($(this).text());
}

function stop_propagation(e) {
    e.stopPropagation();
}
function onroomclick () {
    if($(this).next(".roompanel").is(":visible")){
	$(this).next(".roompanel").hide();
	$(".roomname").removeClass("active");
    } else {
	$(".roompanel").hide();
	$(this).next(".roompanel").show();
	$(".roomname").removeClass("active");
	$(this).toggleClass("active");
	$(this).parent().find("div textarea").focus();
	var blinker = $(this).data("blink");
	if (blinker != null) {
	    window.clearInterval(blinker);
	    $(this).data("blink", null);
	}
    }
    return false;
}

function anchor_blink(anchor, interval) {
    anchor.toggleClass("blink");
    window.setTimeout(function(){anchor.toggleClass("blink");}, interval);
}

// default handlers
function handle_chat_add(v) {
    add_chat(v.wid, v.title, true);
}

function show_message(v, room) {
    var wid = v.wid;
    var message = decodeURIComponent(v.message);
    var sender = v.sender;
    var res;
    if (sender == "own") {
	res = "
" + message + "
";
    } else if (sender == "sys") {
	res = "
" + message + "
";
    } else if (sender != null && sender != "") {
	res = "
" + sender + ": " + message + "
";
    } else {
	res = "
" + message + "
";
    }
    room.find("div ul").append(res);
}

function handle_chat_message(v) {
    var room = $(".room").filter(function(idx){return $(this).data("wid") == v.wid});
    if (room.length == 0) {
	var wid = v.wid;
	room = add_chat(wid, wid.substring(0, wid.lastIndexOf("@")), true);
    }
    show_message(v, room);
    if (room.find(".roompanel").is(":not(:visible)") && v.sender != "own") {
	var anc = room.find(".roomname");
	if (anc.data("blink") != null) {
	    return;
	}
	anc.data("blink", window.setInterval(function(){anchor_blink(anc, 500)}, 1000))
    }
    var stored =  JSON.parse($.cookie("we-chat"));
    var rooms =  JSON.parse($.cookie("we-chat-rooms"));
    var i = 0;
    while (v.wid != rooms[i].wid) {
	i += 1;
    }
    if (stored == null) {
	stored = []
    }
    var sender = v.sender;
    if (sender == null) {
	sender = "";
    }
    stored.splice(0, 0, i + "." + sender + ":" + v.message);
    var tostore = JSON.stringify(stored);
    while (tostore.lendth > max_cookie) {
	stored.pop();
	tostore = JSON.stringify(stored);
    }
    $.cookie("we-chat", tostore);
}

<|endoftext|>


<commit_before>import test from 'zopf'
import proxyquire from 'proxyquire'

import electron from '../stubs/electron'

let setup = (t) => {
  let request = {
    get: (opts) => null
  }

  let stubs = Object.assign({
    request,
    'request-progress': (t) => t
  }, electron)

  let http = proxyquire('../../app/util/http', stubs)

  let handlers = {}
  let stub = {
    on: (ev, fn) => { handlers[ev] = fn },
    pipe: () => { return stub }
  }
  t.stub(request, 'get').returns(stub)

  return Object.assign({request, http, handlers}, electron)
}

let http_opts = {
  url: 'http://-invalid/hello.txt',
  sink: {},
  onprogress: () => {}
}

test('http', t => {
  let {http, handlers} = setup(t)

  t.case('resolves on close', t => {
    setImmediate(() => { handlers.close() })
    return http.request(http_opts)
  })

  t.case('rejects non-2xx response', t => {
    setImmediate(() => { handlers.response({statusCode: 404}) })
    return t.rejects(http.request(http_opts))
  })

  t.case('rejects errors', t => {
    setImmediate(() => { handlers.error('meow') })
    return t.rejects(http.request(http_opts))
  })
})
<commit_msg>:lipstick:<commit_after>import test from 'zopf'
import proxyquire from 'proxyquire'

import electron from '../stubs/electron'

let http_opts = {
  url: 'http://-invalid/hello.txt',
  sink: {},
  onprogress: () => {}
}

test('http', t => {
  let request = {
    get: (opts) => null
  }

  let stubs = Object.assign({
    request,
    'request-progress': (t) => t
  }, electron)

  let http = proxyquire('../../app/util/http', stubs)

  let handlers = {}
  let stub = {
    on: (ev, fn) => { handlers[ev] = fn },
    pipe: () => { return stub }
  }
  t.stub(request, 'get').returns(stub)

  t.case('resolves on close', t => {
    setImmediate(() => { handlers.close() })
    return http.request(http_opts)
  })

  t.case('rejects non-2xx response', t => {
    setImmediate(() => { handlers.response({statusCode: 404}) })
    return t.rejects(http.request(http_opts))
  })

  t.case('rejects errors', t => {
    setImmediate(() => { handlers.error('meow') })
    return t.rejects(http.request(http_opts))
  })
})
<|endoftext|>


<commit_before>debug = getUrlParameter('debug');
var cache = [];
var config = readConfig("config.json");

function lightweight_cctray_monitor(){
    updatePresentation(config.successText, cache, debug);
    setInterval(updatePresentation, 5000, config.successText, cache, debug);

    var autoHiddenRegexCompiled = config.autoHiddenRegex !== undefined && config.autoHiddenRegex !== "" ? new RegExp(config.autoHiddenRegex).compile() : null;
    updateCache(config.pipelines, autoHiddenRegexCompiled, config.defaultHiddenSteps, cache, true);
    setInterval(updateCache, 3000, config.pipelines, autoHiddenRegexCompiled, config.defaultHiddenSteps, cache, true);
}

window.onload = lightweight_cctray_monitor;<commit_msg>remove deprecated regex compile function<commit_after>debug = getUrlParameter('debug');
var cache = [];
var config = readConfig("config.json");

function lightweight_cctray_monitor(){
    updatePresentation(config.successText, cache, debug);
    setInterval(updatePresentation, 5000, config.successText, cache, debug);

    var autoHiddenRegexCompiled = config.autoHiddenRegex !== undefined && config.autoHiddenRegex !== "" ? new RegExp(config.autoHiddenRegex) : null;
    updateCache(config.pipelines, autoHiddenRegexCompiled, config.defaultHiddenSteps, cache, true);
    setInterval(updateCache, 3000, config.pipelines, autoHiddenRegexCompiled, config.defaultHiddenSteps, cache, true);
}

window.onload = lightweight_cctray_monitor;<|endoftext|>


<commit_before>(function () {
    'use strict';

    var thisModule = angular.module('appAppbar.Search', [
        'pipAppBar', 'pipAppBar.Part','pipSearchBar'
    ]);

    thisModule.controller('SearchController',
        function($scope, $rootScope, pipAppBar, pipSearch, $injector) {
            var pipTranslate = $injector.has('pipTranslate') ? $injector.get('pipTranslate') : null;
            if (pipTranslate) {
                pipTranslate.translations('en', {
                    DISPLAY_AND_HIDE_SEARCH: 'Display and hide search',
                    SHOW_SEARCH: 'Show search',
                    HIDE_SEARCH: 'Hide search',
                    UPDATE_SEARCH: 'Update search',
                });
                pipTranslate.translations('ru', {

                    DISPLAY_AND_HIDE_SEARCH: 'Отображение и скрытие поиска',
                    SHOW_SEARCH: 'Отобразить поиск',
                    HIDE_SEARCH: 'Скрыть поиск',
                    UPDATE_SEARCH: 'Обновить поиск',
                });
            }
            $scope.searchCriteria = 'Find this';

            $scope.$on('pipAppBarSearchClicked', function (event, search) {
                console.log('Search Clicked: ' + search);// eslint-disable-line
                $scope.searchCriteria = search;
                pipSearch.criteria($scope.searchCriteria);
            });

            $scope.onHideSearch = function () {
                pipAppBar.part('search', false);
                pipAppBar.part('title', 'text');
                $rootScope.$broadcast('pipSearchClose');
            };

            $scope.onShowSearch = function () {
                pipAppBar.part('search', true);
                pipAppBar.part('title', false);
                pipSearch.set(null, $scope.searchCriteria, null);
                $rootScope.$broadcast('pipSearchOpen');
            };

            $scope.onUpdateSearch = function () {
                pipSearch.criteria($scope.searchCriteria);
            };

            $scope.searchEnabled = true;

        }
    );

})();<commit_msg>appbar<commit_after>(function () {
    'use strict';

    var thisModule = angular.module('appAppbar.Search', [
        'pipAppBar', 'pipAppBar.Part','pipSearchBar'
    ]);

    thisModule.controller('SearchController',
        function($scope, $rootScope, pipAppBar, pipSearch, $injector) {
            var pipTranslate = $injector.has('pipTranslate') ? $injector.get('pipTranslate') : null;
            if (pipTranslate) {
                pipTranslate.translations('en', {
                    DISPLAY_AND_HIDE_SEARCH: 'Display and hide search',
                    SHOW_SEARCH: 'Show search',
                    HIDE_SEARCH: 'Hide search',
                    UPDATE_SEARCH: 'Update search',
                });
                pipTranslate.translations('ru', {

                    DISPLAY_AND_HIDE_SEARCH: 'Отображение и скрытие поиска',
                    SHOW_SEARCH: 'Отобразить поиск',
                    HIDE_SEARCH: 'Скрыть поиск',
                    UPDATE_SEARCH: 'Обновить поиск',
                });
            }
            $scope.searchCriteria = 'Find this';

            $scope.$on('pipAppBarSearchClicked', function (event, search) {
                console.log('Search Clicked: ' + search);// eslint-disable-line
                $scope.searchCriteria = search;
                pipSearch.criteria($scope.searchCriteria);
            });

            $scope.onHideSearch = function () {
                pipAppBar.part('search', false);
                pipAppBar.part('title', 'text');
                $rootScope.$broadcast('pipSearchClose');
            };

            function searchClicked (search) {
                alert('Search'+ search);
            };

            $scope.onShowSearch = function () {
                pipAppBar.part('search', true);
                pipAppBar.part('title', false);
                pipSearch.set(searchClicked, $scope.searchCriteria, null);
                $rootScope.$broadcast('pipSearchOpen');
            };

            $scope.onUpdateSearch = function () {
                pipSearch.criteria($scope.searchCriteria);
            };

            $scope.searchEnabled = true;

        }
    );

})();<|endoftext|>


<commit_before>'use strict';

function calculate_wcag(source, offset, length){
    var source = document.getElementById(source).value;
    var math = parseInt(
      length === 4
        ? source[offset / 2] + source[offset / 2]
        : source.substring(
          offset - 1,
          offset + 1
        ),
      16
    ) / 255;

    return math <= .03928
      ? math / 12.92
      : Math.pow(
        ((math + .055) / 1.055),
        2.4
      );
}

function darken_lighten(change){
    var hex = document.getElementById('hex').value;
    var hexlength = hex.length === 3;

    // Get colors.
    var blue =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(2, 3) + hex.substring(2, 3)
            : hex.substring(4, 6),
          16
        )
      ) / 51) * .2;
    var green =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(1, 2) + hex.substring(1, 2)
            : hex.substring(2, 4),
          16
        )
      ) / 51) * .2;
    var red =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(0, 1) + hex.substring(0, 1)
            : hex.substring(0, 2),
          16
        )
      ) / 51) * .2;

    var Max = 0;
    var Min = 0;

    Max = eval(eval(red) >= eval(green)
      ? red
      : green
    );
    if(eval(blue) > eval(Max)){
        Max = eval(blue);
    }
    Min = eval(eval(red) <= eval(green)
      ? red
      : green
    );
    if(eval(blue) < eval(Min)){
        Min = eval(blue);
    }

    var H = 0;
    var L = Math.round(
      (eval(Max) + eval(Min)) * 50
    );
    var S = 0;

    // Luminosity calculations.
    L = (L + (change ? 6.25 : -6.25)) / 100;
    if(L > 1){
        L = 1;

    }else if(L < 0){
        L = 0;
    }

    if(eval(Max) != eval(Min)){
        var dx = (eval(Max) - eval(Min));
        if(red === Max){
            H = (eval(green) - eval(blue)) / dx;
        }
        if(green === Max){
            H = 2 + (eval(blue) - eval(red)) / dx;
        }
        if(blue === Max){
            H = 4 + (eval(red) - eval(green)) / dx;
        }
        S = dx
          / (L<.5
            ? eval(Max) + eval(Min)
            : 2 - eval(Max) - eval(Min)
          );
    }

    H = Math.round(H * 60);
    if(H < 0){
        H += 360;

    }else if(H >= 360){
        H -= 360;
    }

    var temp = L < .5
      ? L * (1 + S)
      : L + S - (L * S);
    var temp2 = 2 * L - temp;
    red = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H + 120
      ) * 255
    );
    green = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H
      ) * 255
    );
    blue = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H - 120
      ) * 255
    );

    document.getElementById('red-255').value =
      (red < 0 || red > 255)
        ? 0
        : red;
    document.getElementById('green-255').value =
      (green < 0 || green > 255)
        ? 0
        : green;
    document.getElementById('blue-255').value =
      (blue < 0 || blue > 255)
        ? 0
        : blue;

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_hex();
}

function darken_lighten_math(d0, d1, d2){
    if(d2 > 360){
        d2 = d2 - 360;

    }else if(d2 < 0){
        d2 = d2 + 360;
    }

    if(d2 < 60){
        return d0 + (d1 - d0) * d2 / 60;

    }else if(d2 < 180){
        return d1;

    }else if(d2 < 240){
        return d0 + (d1 - d0) * (240 - d2) / 60;

    }else{
        return d0;
    }
}

function hexvalues(i){
    return '0123456789abcdef'.charAt(i);
}

function random_color(color){
    color = color || 'hex';

    if(color === 'hex'){
        document.getElementById(color).value = core_random_hex();
        update_fromhex();

    }else{
        document.getElementById(color).value = core_random_integer({
          'max': 256,
        });
        update_fromslider(color);
    }
}

function update_display(){
    // Set hex-color value to hex value.
    document.getElementById('hex-color').value =
      '#' + document.getElementById('hex').value;

    // Updates the display square background color.
    document.getElementById('display').style.background = 'rgb('
      + parseInt(document.getElementById('red').value, 10) + ','
      + parseInt(document.getElementById('green').value, 10) + ','
      + parseInt(document.getElementById('blue').value, 10) + ')';
}

function update_from1(color){
    // Update value of slider when 0-1 text input is changed
    //   and validate 0-1 text input value isn't less than 0 or greater than 1.
    var color_value = document.getElementById(color + '-1').value;
    if(isNaN(color_value)
      || color_value < 0
      || color_value > 1){
        color_value = 0;
        document.getElementById(color + '-1').value = color_value;
    }

    var color_value = Math.round(color_value * 255);
    document.getElementById(color).value = color_value;
    document.getElementById(color + '-255').value = color_value;
    update_display();
}

function update_from255(color){
    // Update value of slider when 0-255 text input is changed
    //   and validate 0-255 text input value is a number that isn't less than 0 or greater than 255.
    var color_value = document.getElementById(color + '-255').value;
    if(isNaN(color_value)
      || color_value < 0
      || color_value > 255){
        document.getElementById(color + '-255').value = 0;
    }

    // If 0-255 text input length is 0, just use color value of 0 instead of messing with user input.
    color_value = document.getElementById(color + '-255').value;
    document.getElementById(color).value = color_value.length < 1
      ? 0
      : color_value;
    document.getElementById(color + '-1').value = color_value.length < 1
      ? 0
      : (color_value / 255).toFixed(4);

    update_display();
}

function update_fromhex(){
    // Update values of slider/text inputs when hex input is changed.
    // Hex length of 3 is valid.
    var hex = document.getElementById('hex').value;
    var hexlength = hex.length === 3;

    document.getElementById('blue-255').value =
      parseInt(
        hexlength
          ? hex.substring(2, 3) + hex.substring(2, 3)
          : hex.substring(4, 6),
        16
      );
    document.getElementById('green-255').value =
      parseInt(
        hexlength
          ? hex.substring(1, 2) + hex.substring(1, 2)
          : hex.substring(2, 4),
        16
      );
    document.getElementById('red-255').value =
      parseInt(
        hexlength
          ? hex.substring(0, 1) + hex.substring(0, 1)
          : hex.substring(0, 2),
        16
      );

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_display();
}

function update_fromslider(color){
    // Update values of hex and text inputs when slider is slided.
    var color_value = document.getElementById(color).value;
    document.getElementById(color + '-1').value = (color_value / 255).toFixed(4);
    document.getElementById(color + '-255').value = color_value;

    update_display();
    update_hex();
}

function update_hex(){
    // Update the hex value based on slider values.
    var red = Math.max(0, Math.min(parseInt(document.getElementById('red').value, 10), 255));
    var green = Math.max(0, Math.min(parseInt(document.getElementById('green').value, 10), 255));
    var blue = Math.max(0, Math.min(parseInt(document.getElementById('blue').value, 10), 255));

    document.getElementById('hex').value =
      hexvalues((red - red % 16) / 16) + hexvalues(red % 16)
      + hexvalues((green - green % 16) / 16) + hexvalues(green % 16)
      + hexvalues((blue - blue % 16) / 16) + hexvalues(blue % 16);

    update_display();
}

function update_wcag(source, source_hex, length){
    var source_value = document.getElementById(source_hex).value;
    document.getElementById(source).value = length === 4
      ? '#'
        + source_value[1] + source_value[1]
        + source_value[2] + source_value[2]
        + source_value[3] + source_value[3]
      : source_value;

    var background_math =
      (.2126 * calculate_wcag('wcag-background-color', 2, length)
      + .7152 * calculate_wcag('wcag-background-color', 4, length)
      + .0722 * calculate_wcag('wcag-background-color', 6, length)
    );
    var foreground_math =
      (.2126 * calculate_wcag('wcag-foreground-color', 2, length)
      + .7152 * calculate_wcag('wcag-foreground-color', 4, length)
      + .0722 * calculate_wcag('wcag-foreground-color', 6, length)
    );

    var wcag_score = Math.round(
      (Math.max(background_math, foreground_math) + .05)
      / (Math.min(background_math, foreground_math) + .05)
      * 10
    ) / 10;

    document.getElementById('wcag-text-normal-result').innerHTML =
      wcag_score + ' / 7 = AAA '
      + (wcag_score > 7
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 4.5 = AA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      );
    document.getElementById('wcag-text-large-result').innerHTML =
      wcag_score + ' / 4.5 = AAA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 3 = AA '
      + (wcag_score > 3
        ? 'Passed'
        : 'Failed'
      );

    var background = document.getElementById('wcag-background-color').value;
    var foreground = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-text-normal').style.backgroundColor = background;
    document.getElementById('wcag-text-normal').style.color = foreground;
    document.getElementById('wcag-text-large').style.backgroundColor = background ;
    document.getElementById('wcag-text-large').style.color = foreground;
}

function wcag_set(target){
    document.getElementById('wcag-' + target + '-color').value =
      '#' + document.getElementById('hex').value;

    update_wcag(
      'wcag-' + target,
      'wcag-' + target + '-color',
      document.getElementById('wcag-' + target + '-color').value.length
    );
}

function wcag_switch(){
    var temp = document.getElementById('wcag-background-color').value;
    document.getElementById('wcag-background-color').value = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-foreground-color').value = temp;

    update_wcag(
      'wcag-background',
      'wcag-background-color',
      document.getElementById('wcag-background-color').value.length
    );

    update_wcag(
      'wcag-foreground',
      'wcag-foreground-color',
      temp.length
    );
}
<commit_msg>removed redundant update_wcag()<commit_after>'use strict';

function calculate_wcag(source, offset, length){
    var source = document.getElementById(source).value;
    var math = parseInt(
      length === 4
        ? source[offset / 2] + source[offset / 2]
        : source.substring(
          offset - 1,
          offset + 1
        ),
      16
    ) / 255;

    return math <= .03928
      ? math / 12.92
      : Math.pow(
        ((math + .055) / 1.055),
        2.4
      );
}

function darken_lighten(change){
    var hex = document.getElementById('hex').value;
    var hexlength = hex.length === 3;

    // Get colors.
    var blue =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(2, 3) + hex.substring(2, 3)
            : hex.substring(4, 6),
          16
        )
      ) / 51) * .2;
    var green =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(1, 2) + hex.substring(1, 2)
            : hex.substring(2, 4),
          16
        )
      ) / 51) * .2;
    var red =
      (eval(
        parseInt(
          hexlength
            ? hex.substring(0, 1) + hex.substring(0, 1)
            : hex.substring(0, 2),
          16
        )
      ) / 51) * .2;

    var Max = 0;
    var Min = 0;

    Max = eval(eval(red) >= eval(green)
      ? red
      : green
    );
    if(eval(blue) > eval(Max)){
        Max = eval(blue);
    }
    Min = eval(eval(red) <= eval(green)
      ? red
      : green
    );
    if(eval(blue) < eval(Min)){
        Min = eval(blue);
    }

    var H = 0;
    var L = Math.round(
      (eval(Max) + eval(Min)) * 50
    );
    var S = 0;

    // Luminosity calculations.
    L = (L + (change ? 6.25 : -6.25)) / 100;
    if(L > 1){
        L = 1;

    }else if(L < 0){
        L = 0;
    }

    if(eval(Max) != eval(Min)){
        var dx = (eval(Max) - eval(Min));
        if(red === Max){
            H = (eval(green) - eval(blue)) / dx;
        }
        if(green === Max){
            H = 2 + (eval(blue) - eval(red)) / dx;
        }
        if(blue === Max){
            H = 4 + (eval(red) - eval(green)) / dx;
        }
        S = dx
          / (L<.5
            ? eval(Max) + eval(Min)
            : 2 - eval(Max) - eval(Min)
          );
    }

    H = Math.round(H * 60);
    if(H < 0){
        H += 360;

    }else if(H >= 360){
        H -= 360;
    }

    var temp = L < .5
      ? L * (1 + S)
      : L + S - (L * S);
    var temp2 = 2 * L - temp;
    red = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H + 120
      ) * 255
    );
    green = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H
      ) * 255
    );
    blue = Math.round(
      darken_lighten_math(
        temp2,
        temp,
        H - 120
      ) * 255
    );

    document.getElementById('red-255').value =
      (red < 0 || red > 255)
        ? 0
        : red;
    document.getElementById('green-255').value =
      (green < 0 || green > 255)
        ? 0
        : green;
    document.getElementById('blue-255').value =
      (blue < 0 || blue > 255)
        ? 0
        : blue;

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_hex();
}

function darken_lighten_math(d0, d1, d2){
    if(d2 > 360){
        d2 = d2 - 360;

    }else if(d2 < 0){
        d2 = d2 + 360;
    }

    if(d2 < 60){
        return d0 + (d1 - d0) * d2 / 60;

    }else if(d2 < 180){
        return d1;

    }else if(d2 < 240){
        return d0 + (d1 - d0) * (240 - d2) / 60;

    }else{
        return d0;
    }
}

function hexvalues(i){
    return '0123456789abcdef'.charAt(i);
}

function random_color(color){
    color = color || 'hex';

    if(color === 'hex'){
        document.getElementById(color).value = core_random_hex();
        update_fromhex();

    }else{
        document.getElementById(color).value = core_random_integer({
          'max': 256,
        });
        update_fromslider(color);
    }
}

function update_display(){
    // Set hex-color value to hex value.
    document.getElementById('hex-color').value =
      '#' + document.getElementById('hex').value;

    // Updates the display square background color.
    document.getElementById('display').style.background = 'rgb('
      + parseInt(document.getElementById('red').value, 10) + ','
      + parseInt(document.getElementById('green').value, 10) + ','
      + parseInt(document.getElementById('blue').value, 10) + ')';
}

function update_from1(color){
    // Update value of slider when 0-1 text input is changed
    //   and validate 0-1 text input value isn't less than 0 or greater than 1.
    var color_value = document.getElementById(color + '-1').value;
    if(isNaN(color_value)
      || color_value < 0
      || color_value > 1){
        color_value = 0;
        document.getElementById(color + '-1').value = color_value;
    }

    var color_value = Math.round(color_value * 255);
    document.getElementById(color).value = color_value;
    document.getElementById(color + '-255').value = color_value;
    update_display();
}

function update_from255(color){
    // Update value of slider when 0-255 text input is changed
    //   and validate 0-255 text input value is a number that isn't less than 0 or greater than 255.
    var color_value = document.getElementById(color + '-255').value;
    if(isNaN(color_value)
      || color_value < 0
      || color_value > 255){
        document.getElementById(color + '-255').value = 0;
    }

    // If 0-255 text input length is 0, just use color value of 0 instead of messing with user input.
    color_value = document.getElementById(color + '-255').value;
    document.getElementById(color).value = color_value.length < 1
      ? 0
      : color_value;
    document.getElementById(color + '-1').value = color_value.length < 1
      ? 0
      : (color_value / 255).toFixed(4);

    update_display();
}

function update_fromhex(){
    // Update values of slider/text inputs when hex input is changed.
    // Hex length of 3 is valid.
    var hex = document.getElementById('hex').value;
    var hexlength = hex.length === 3;

    document.getElementById('blue-255').value =
      parseInt(
        hexlength
          ? hex.substring(2, 3) + hex.substring(2, 3)
          : hex.substring(4, 6),
        16
      );
    document.getElementById('green-255').value =
      parseInt(
        hexlength
          ? hex.substring(1, 2) + hex.substring(1, 2)
          : hex.substring(2, 4),
        16
      );
    document.getElementById('red-255').value =
      parseInt(
        hexlength
          ? hex.substring(0, 1) + hex.substring(0, 1)
          : hex.substring(0, 2),
        16
      );

    update_from255('blue');
    update_from255('green');
    update_from255('red');

    update_display();
}

function update_fromslider(color){
    // Update values of hex and text inputs when slider is slided.
    var color_value = document.getElementById(color).value;
    document.getElementById(color + '-1').value = (color_value / 255).toFixed(4);
    document.getElementById(color + '-255').value = color_value;

    update_display();
    update_hex();
}

function update_hex(){
    // Update the hex value based on slider values.
    var red = Math.max(0, Math.min(parseInt(document.getElementById('red').value, 10), 255));
    var green = Math.max(0, Math.min(parseInt(document.getElementById('green').value, 10), 255));
    var blue = Math.max(0, Math.min(parseInt(document.getElementById('blue').value, 10), 255));

    document.getElementById('hex').value =
      hexvalues((red - red % 16) / 16) + hexvalues(red % 16)
      + hexvalues((green - green % 16) / 16) + hexvalues(green % 16)
      + hexvalues((blue - blue % 16) / 16) + hexvalues(blue % 16);

    update_display();
}

function update_wcag(source, source_hex, length){
    var source_value = document.getElementById(source_hex).value;
    document.getElementById(source).value = length === 4
      ? '#'
        + source_value[1] + source_value[1]
        + source_value[2] + source_value[2]
        + source_value[3] + source_value[3]
      : source_value;

    var background_math =
      (.2126 * calculate_wcag('wcag-background-color', 2, length)
      + .7152 * calculate_wcag('wcag-background-color', 4, length)
      + .0722 * calculate_wcag('wcag-background-color', 6, length)
    );
    var foreground_math =
      (.2126 * calculate_wcag('wcag-foreground-color', 2, length)
      + .7152 * calculate_wcag('wcag-foreground-color', 4, length)
      + .0722 * calculate_wcag('wcag-foreground-color', 6, length)
    );

    var wcag_score = Math.round(
      (Math.max(background_math, foreground_math) + .05)
      / (Math.min(background_math, foreground_math) + .05)
      * 10
    ) / 10;

    document.getElementById('wcag-text-normal-result').innerHTML =
      wcag_score + ' / 7 = AAA '
      + (wcag_score > 7
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 4.5 = AA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      );
    document.getElementById('wcag-text-large-result').innerHTML =
      wcag_score + ' / 4.5 = AAA '
      + (wcag_score > 4.5
        ? 'Passed'
        : 'Failed'
      ) + '
' + wcag_score + ' / 3 = AA '
      + (wcag_score > 3
        ? 'Passed'
        : 'Failed'
      );

    var background = document.getElementById('wcag-background-color').value;
    var foreground = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-text-normal').style.backgroundColor = background;
    document.getElementById('wcag-text-normal').style.color = foreground;
    document.getElementById('wcag-text-large').style.backgroundColor = background ;
    document.getElementById('wcag-text-large').style.color = foreground;
}

function wcag_set(target){
    document.getElementById('wcag-' + target + '-color').value =
      '#' + document.getElementById('hex').value;

    update_wcag(
      'wcag-' + target,
      'wcag-' + target + '-color',
      document.getElementById('wcag-' + target + '-color').value.length
    );
}

function wcag_switch(){
    var temp = document.getElementById('wcag-background-color').value;
    document.getElementById('wcag-background-color').value = document.getElementById('wcag-foreground-color').value;
    document.getElementById('wcag-foreground-color').value = temp;

    update_wcag(
      'wcag-background',
      'wcag-background-color',
      document.getElementById('wcag-background-color').value.length
    );
}
<|endoftext|>