<commit_before>'use strict';

const Exchange = require ('./base/Exchange');
const { ROUND } = require ('./base/functions/number');
const { ExchangeError, ArgumentsRequired, AuthenticationError, InsufficientFunds, InvalidOrder, OrderNotFound } = require ('./base/errors');

module.exports = class rightbtc extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'rightbtc',
            'name': 'RightBTC',
            'countries': [ 'AE' ],
            'has': {
                'cancelOrder': true,
                'createOrder': true,
                'privateAPI': false,
                'fetchBalance': true,
                'fetchClosedOrders': false,
                'fetchMarkets': true,
                'fetchMyTrades': true,
                'fetchOHLCV': true,
                'fetchOpenOrders': true,
                'fetchOrder': 'emulated',
                'fetchOrderBook': true,
                'fetchOrders': true,
                'fetchTicker': true,
                'fetchTickers': true,
                'fetchTrades': true,
            },
            'timeframes': {
                '1m': 'min1',
                '5m': 'min5',
                '15m': 'min15',
                '30m': 'min30',
                '1h': 'hr1',
                '1d': 'day1',
                '1w': 'week',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/51840849/87182092-1f372700-c2ec-11ea-8f9e-01b4d3ff8941.jpg',
                'api': 'https://www.rightbtc.com/api',
                'www': 'https://www.rightbtc.com',
                'doc': [
                    'https://docs.rightbtc.com/api/',
                ],
                // eslint-disable-next-line no-useless-escape
                // 'fees': 'https://www.rightbtc.com/\#\!/support/fee',
            },
            'api': {
                'public': {
                    'get': [
                        // 'getAssetsTradingPairs/zh', // 404
                        'trading_pairs',
                        'ticker/{trading_pair}',
                        'tickers',
                        'depth/{trading_pair}',
                        'depth/{trading_pair}/{count}',
                        'trades/{trading_pair}',
                        'trades/{trading_pair}/{count}',
                        'candlestick/latest/{trading_pair}',
                        'candlestick/{timeSymbol}/{trading_pair}',
                        'candlestick/{timeSymbol}/{trading_pair}/{count}',
                    ],
                },
                'trader': {
                    'get': [
                        'balance/{symbol}',
                        'balances',
                        'deposits/{asset}/{page}',
                        'withdrawals/{asset}/{page}',
                        'orderpage/{trading_pair}/{cursor}',
                        'orders/{trading_pair}/{ids}', // ids are a slash-separated list of {id}/{id}/{id}/...
                        'history/{trading_pair}/{ids}',
                        'historys/{trading_pair}/{page}',
                        'trading_pairs',
                    ],
                    'post': [
                        'order',
                    ],
                    'delete': [
                        'order/{trading_pair}/{ids}',
                    ],
                },
            },
            // HARDCODING IS DEPRECATED, THE FEES BELOW SHOULD BE REWRITTEN
            'fees': {
                'trading': {
                    // min trading fees
                    // 0.0001 BTC
                    // 0.01 ETP
                    // 0.001 ETH
                    // 0.1 BITCNY
                    'maker': 0.1 / 100,
                    'taker': 0.2 / 100,
                },
                'funding': {
                    'withdraw': {
                        // 'BTM': n => 3 + n * (1 / 100),
                        // 'ZDC': n => 1 + n * (0.5 / 100),
                        // 'ZGC': n => 0.5 + n * (0.5 / 100),
                        // 'BTS': n => 1 + n * (1 / 100),
                        // 'DLT': n => 3 + n * (1 / 100),
                        // 'SNT': n => 10 + n * (1 / 100),
                        // 'XNC': n => 1 + n * (1 / 100),
                        // 'ICO': n => 3 + n * (1 / 100),
                        // 'CMC': n => 1 + n * (0.5 / 100),
                        // 'GXS': n => 0.2 + n * (1 / 100),
                        // 'OBITS': n => 0.3 + n * (1 / 100),
                        // 'ICS': n => 2 + n * (1 / 100),
                        // 'TIC': n => 2 + n * (1 / 100),
                        // 'IND': n => 20 + n * (1 / 100),
                        // 'MVC': n => 20 + n * (1 / 100),
                        // 'BitCNY': n => 0.1 + n * (1 / 100),
                        // 'MTX': n => 1 + n * (1 / 100),
                        'ETP': 0.01,
                        'BTC': 0.0005,
                        'ETH': 0.005,
                        'ETC': 0.01,
                        'STORJ': 3,
                        'LTC': 0.01,
                        'ZEC': 0.001,
                        'BCC': 0.001,
                        'XRB': 0,
                        'NXS': 0.1,
                    },
                },
            },
            'commonCurrencies': {
                'XRB': 'NANO',
            },
            'exceptions': {
                'ERR_USERTOKEN_NOT_FOUND': AuthenticationError,
                'ERR_ASSET_NOT_EXISTS': ExchangeError,
                'ERR_ASSET_NOT_AVAILABLE': ExchangeError,
                'ERR_BALANCE_NOT_ENOUGH': InsufficientFunds,
                'ERR_CREATE_ORDER': InvalidOrder,
                'ERR_CANDLESTICK_DATA': ExchangeError,
            },
        });
    }

    async fetchMarkets (params = {}) {
        // let zh = await this.publicGetGetAssetsTradingPairsZh ();
        const markets = await this.publicGetTradingPairs (params);
        const marketIds = Object.keys (markets);
        const result = [];
        for (let i = 0; i < marketIds.length; i++) {
            const id = marketIds[i];
            const market = markets[id];
            const baseId = this.safeString (market, 'bid_asset_symbol');
            const quoteId = this.safeString (market, 'ask_asset_symbol');
            const base = this.safeCurrencyCode (baseId);
            const quote = this.safeCurrencyCode (quoteId);
            const symbol = base + '/' + quote;
            const amountPrecision = this.safeString (market, 'bid_asset_decimals');
            const pricePrecision = this.safeString (market, 'ask_asset_decimals');
            const amountLimit = this.parsePrecision (amountPrecision);
            const priceLimit = this.parsePrecision (pricePrecision);
            const precision = {
                'amount': parseInt (amountPrecision),
                'price': parseInt (pricePrecision),
            };
            result.push ({
                'id': id,
                'symbol': symbol,
                'base': base,
                'quote': quote,
                'baseId': baseId,
                'quoteId': quoteId,
                'active': true,
                'precision': precision,
                'limits': {
                    'amount': {
                        'min': this.parseNumber (amountLimit),
                        'max': undefined,
                    },
                    'price': {
                        'min': this.parseNumber (priceLimit),
                        'max': undefined,
                    },
                    'cost': {
                        'min': undefined,
                        'max': undefined,
                    },
                },
                'info': market,
            });
        }
        return result;
    }

    divideSafeNumber (x, key, divisor) {
        const value = this.safeNumber (x, key);
        if (value !== undefined) {
            return value / divisor;
        }
        return value;
    }

    parseTicker (ticker, market = undefined) {
        const symbol = market['symbol'];
        const timestamp = this.safeInteger (ticker, 'date');
        const last = this.divideSafeNumber (ticker, 'last', 1e8);
        const high = this.divideSafeNumber (ticker, 'high', 1e8);
        const low = this.divideSafeNumber (ticker, 'low', 1e8);
        const bid = this.divideSafeNumber (ticker, 'buy', 1e8);
        const ask = this.divideSafeNumber (ticker, 'sell', 1e8);
        const baseVolume = this.divideSafeNumber (ticker, 'vol24h', 1e8);
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': undefined,
            'ask': ask,
            'askVolume': undefined,
            'vwap': undefined,
            'open': undefined,
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': undefined,
            'info': ticker,
        };
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
        };
        const response = await this.publicGetTickerTradingPair (this.extend (request, params));
        const result = this.safeValue (response, 'result');
        if (result === undefined) {
            throw new ExchangeError (this.id + ' fetchTicker returned an empty response for symbol ' + symbol);
        }
        return this.parseTicker (result, market);
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        const response = await this.publicGetTickers (params);
        const tickers = response['result'];
        const result = {};
        for (let i = 0; i < tickers.length; i++) {
            const ticker = tickers[i];
            const id = ticker['market'];
            if (!(id in this.marketsById)) {
                continue;
            }
            const market = this.marketsById[id];
            const symbol = market['symbol'];
            result[symbol] = this.parseTicker (ticker, market);
        }
        return this.filterByArray (result, 'symbol', symbols);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'trading_pair': this.marketId (symbol),
        };
        let method = 'publicGetDepthTradingPair';
        if (limit !== undefined) {
            method += 'Count';
            request['count'] = limit;
        }
        const response = await this[method] (this.extend (request, params));
        const bidsasks = {};
        const types = ['bid', 'ask'];
        for (let ti = 0; ti < types.length; ti++) {
            const type = types[ti];
            bidsasks[type] = [];
            for (let i = 0; i < response['result'][type].length; i++) {
                const [ price, amount, total ] = response['result'][type][i];
                bidsasks[type].push ([
                    price / 1e8,
                    amount / 1e8,
                    total / 1e8,
                ]);
            }
        }
        return this.parseOrderBook (bidsasks, symbol, undefined, 'bid', 'ask');
    }

    parseTrade (trade, market = undefined) {
        //
        //     {
        //         "order_id": 118735,
        //         "trade_id": 7,
        //         "trading_pair": "BTCCNY",
        //         "side": "B",
        //         "quantity": 1000000000,
        //         "price": 900000000,
        //         "created_at": "2017-06-06T20:45:27.000Z"
        //     }
        //
        let timestamp = this.safeInteger (trade, 'date');
        if (timestamp === undefined) {
            timestamp = this.parse8601 (this.safeString (trade, 'created_at'));
        }
        let id = this.safeString (trade, 'tid');
        id = this.safeString (trade, 'trade_id', id);
        const orderId = this.safeString (trade, 'order_id');
        const price = this.divideSafeNumber (trade, 'price', 1e8);
        let amount = this.safeNumber (trade, 'amount');
        amount = this.safeNumber (trade, 'quantity', amount);
        if (amount !== undefined) {
            amount = amount / 1e8;
        }
        const marketId = this.safeString (trade, 'trading_pair');
        const symbol = this.safeSymbol (marketId, market);
        let cost = this.costToPrecision (symbol, price * amount);
        cost = parseFloat (cost);
        let side = this.safeStringLower (trade, 'side');
        if (side === 'b') {
            side = 'buy';
        } else if (side === 's') {
            side = 'sell';
        }
        return {
            'id': id,
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'order': orderId,
            'type': 'limit',
            'side': side,
            'takerOrMaker': undefined,
            'price': price,
            'amount': amount,
            'cost': cost,
            'fee': undefined,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
        };
        const response = await this.publicGetTradesTradingPair (this.extend (request, params));
        return this.parseTrades (response['result'], market, since, limit);
    }

    parseOHLCV (ohlcv, market = undefined) {
        return [
            this.safeInteger (ohlcv, 0),
            parseFloat (ohlcv[2]) / 1e8,
            parseFloat (ohlcv[3]) / 1e8,
            parseFloat (ohlcv[4]) / 1e8,
            parseFloat (ohlcv[5]) / 1e8,
            parseFloat (ohlcv[1]) / 1e8,
        ];
    }

    async fetchOHLCV (symbol, timeframe = '5m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'timeSymbol': this.timeframes[timeframe],
        };
        const response = await this.publicGetCandlestickTimeSymbolTradingPair (this.extend (request, params));
        const result = this.safeValue (response, 'result', []);
        return this.parseOHLCVs (result, market, timeframe, since, limit);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.traderGetBalances (params);
        //
        //     {
        //         "status": {
        //             "success": 1,
        //             "message": "GET_BALANCES"
        //         },
        //         "result": [
        //             {
        //                 "asset": "ETP",
        //                 "balance": "5000000000000",
        //                 "frozen": "0",
        //                 "state": "1"
        //             },
        //             {
        //                 "asset": "CNY",
        //                 "balance": "10000000000000",
        //                 "frozen": "240790000",
        //                 "state": "1"
        //             }
        //         ]
        //     }
        //
        const result = { 'info': response };
        const balances = this.safeValue (response, 'result', []);
        for (let i = 0; i < balances.length; i++) {
            const balance = balances[i];
            const currencyId = this.safeString (balance, 'asset');
            const code = this.safeCurrencyCode (currencyId);
            const account = this.account ();
            // https://github.com/ccxt/ccxt/issues/3873
            account['free'] = this.divideSafeNumber (balance, 'balance', 1e8);
            account['used'] = this.divideSafeNumber (balance, 'frozen', 1e8);
            result[code] = account;
        }
        return this.parseBalance (result);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const order = {
            'trading_pair': market['id'],
            // We need to use decimalToPrecision here, since
            //   0.036*1e8 === 3599999.9999999995
            // which would get truncated to 3599999 after parseInt
            // which would then be rejected by rightBtc because it's too precise
            'quantity': parseInt (this.decimalToPrecision (amount * 1e8, ROUND, 0, this.precisionMode)),
            'limit': parseInt (this.decimalToPrecision (price * 1e8, ROUND, 0, this.precisionMode)),
            'type': type.toUpperCase (),
            'side': side.toUpperCase (),
        };
        const response = await this.traderPostOrder (this.extend (order, params));
        return this.parseOrder (response);
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'ids': id,
        };
        const response = await this.traderDeleteOrderTradingPairIds (this.extend (request, params));
        return response;
    }

    parseOrderStatus (status) {
        const statuses = {
            'NEW': 'open',
            'TRADE': 'closed', // TRADE means filled or partially filled orders
            'CANCEL': 'canceled',
        };
        return this.safeString (statuses, status, status);
    }

    parseOrder (order, market = undefined) {
        //
        // fetchOrder / fetchOpenOrders
        //
        //     {
        //         "id": 4180528,
        //         "quantity": 20000000,
        //         "rest": 20000000,
        //         "limit": 1000000,
        //         "price": null,
        //         "side": "BUY",
        //         "created": 1496005693738
        //     }
        //
        // fetchOrders
        //
        //     {
        //         "trading_pair": "ETPCNY",
        //         "status": "TRADE",
        //         "fee": 0.23,
        //         "min_fee": 10000000,
        //         "created_at": "2017-05-25T00:12:27.000Z",
        //         "cost": 1152468000000,
        //         "limit": 3600000000,
        //         "id": 11060,
        //         "quantity": 32013000000,
        //         "filled_quantity": 32013000000
        //     }
        //
        const id = this.safeString (order, 'id');
        const status = this.parseOrderStatus (this.safeString (order, 'status'));
        const marketId = this.safeString (order, 'trading_pair');
        const symbol = this.safeSymbol (marketId, market);
        let timestamp = this.safeInteger (order, 'created');
        if (timestamp === undefined) {
            timestamp = this.parse8601 (this.safeString (order, 'created_at'));
        }
        if ('time' in order) {
            timestamp = order['time'];
        } else if ('transactTime' in order) {
            timestamp = order['transactTime'];
        }
        let price = this.safeNumber2 (order, 'limit', 'price');
        if (price !== undefined) {
            price = price / 1e8;
        }
        const amount = this.divideSafeNumber (order, 'quantity', 1e8);
        const filled = this.divideSafeNumber (order, 'filled_quantity', 1e8);
        const remaining = this.divideSafeNumber (order, 'rest', 1e8);
        const cost = this.divideSafeNumber (order, 'cost', 1e8);
        // lines 483-494 should be generalized into a base class method
        const type = 'limit';
        const side = this.safeStringLower (order, 'side');
        const feeCost = this.divideSafeNumber (order, 'min_fee', 1e8);
        let fee = undefined;
        if (feeCost !== undefined) {
            let feeCurrency = undefined;
            if (market !== undefined) {
                feeCurrency = market['quote'];
            }
            fee = {
                'rate': this.safeNumber (order, 'fee'),
                'cost': feeCost,
                'currency': feeCurrency,
            };
        }
        const trades = undefined;
        return this.safeOrder ({
            'info': order,
            'id': id,
            'clientOrderId': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'lastTradeTimestamp': undefined,
            'symbol': symbol,
            'type': type,
            'timeInForce': undefined,
            'postOnly': undefined,
            'side': side,
            'price': price,
            'stopPrice': undefined,
            'amount': amount,
            'cost': cost,
            'filled': filled,
            'remaining': remaining,
            'status': status,
            'fee': fee,
            'trades': trades,
            'average': undefined,
        });
    }

    async fetchOrder (id, symbol = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'ids': id,
        };
        const response = await this.traderGetOrdersTradingPairIds (this.extend (request, params));
        //
        // let response = {
        //         "status": {
        //             "success": 1,
        //             "message": "SUC_LIST_AVTICE_ORDERS"
        //         },
        //         "result": [
        //             {
        //                 "id": 4180528,
        //                 "quantity": 20000000,
        //                 "rest": 20000000,
        //                 "limit": 1000000,
        //                 "price": null,
        //                 "side": "BUY",
        //                 "created": 1496005693738
        //             }
        //         ]
        //     }
        //
        const orders = this.parseOrders (response['result'], market);
        const ordersById = this.indexBy (orders, 'id');
        if (!(id in ordersById)) {
            throw new OrderNotFound (this.id + ' fetchOrder could not find order ' + id.toString () + ' in open orders.');
        }
        return ordersById[id];
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchOpenOrders() requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'cursor': 0,
        };
        const response = await this.traderGetOrderpageTradingPairCursor (this.extend (request, params));
        //
        // let response = {
        //         "status": {
        //             "success": 1,
        //             "message": "SUC_LIST_AVTICE_ORDERS_PAGE"
        //         },
        //         "result": {
        //             "cursor": "0",
        //             "orders": [
        //                 {
        //                     "id": 4180528,
        //                     "quantity": 20000000,
        //                     "rest": 20000000,
        //                     "limit": 1000000,
        //                     "price": null,
        //                     "side": "BUY",
        //                     "created": 1496005693738
        //                 }
        //             ]
        //         }
        //     }
        //
        return this.parseOrders (response['result']['orders'], market, since, limit);
    }

    async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        let ids = this.safeString (params, 'ids');
        if ((symbol === undefined) || (ids === undefined)) {
            throw new ArgumentsRequired (this.id + " fetchOrders() requires a 'symbol' argument and an extra 'ids' parameter. The 'ids' should be an array or a string of one or more order ids separated with slashes."); // eslint-disable-line quotes
        }
        if (Array.isArray (ids)) {
            ids = ids.join ('/');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'ids': ids,
        };
        const response = await this.traderGetHistoryTradingPairIds (this.extend (request, params));
        //
        // let response = {
        //         "status": {
        //             "success": 1,
        //             "message": null
        //         },
        //         "result": [
        //             {
        //                 "trading_pair": "ETPCNY",
        //                 "status": "TRADE",
        //                 "fee": 0.23,
        //                 "min_fee": 10000000,
        //                 "created_at": "2017-05-25T00:12:27.000Z",
        //                 "cost": 1152468000000,
        //                 "limit": 3600000000,
        //                 "id": 11060,
        //                 "quantity": 32013000000,
        //                 "filled_quantity": 32013000000
        //             }
        //         ]
        //     }
        //
        return this.parseOrders (response['result'], undefined, since, limit);
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (symbol === undefined) {
            throw new ArgumentsRequired (this.id + ' fetchMyTrades() requires a symbol argument');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'trading_pair': market['id'],
            'page': 0,
        };
        const response = await this.traderGetHistorysTradingPairPage (this.extend (request, params));
        //
        // let response = {
        //         "status": {
        //             "success": 1,
        //             "message": null
        //         },
        //         "result": [
        //             {
        //                 "order_id": 118735,
        //                 "trade_id": 7,
        //                 "trading_pair": "BTCCNY",
        //                 "side": "B",
        //                 "quantity": 1000000000,
        //                 "price": 900000000,
        //                 "created_at": "2017-06-06T20:45:27.000Z"
        //             },
        //             {
        //                 "order_id": 118734,
        //                 "trade_id": 7,
        //                 "trading_pair": "BTCCNY",
        //                 "side": "S",
        //                 "quantity": 1000000000,
        //                 "price": 900000000,
        //                 "created_at": "2017-06-06T20:45:27.000Z"
        //             }
        //         ]
        //     }
        //
        return this.parseTrades (response['result'], undefined, since, limit);
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        const query = this.omit (params, this.extractParams (path));
        let url = this.urls['api'] + '/' + api + '/' + this.implodeParams (path, params);
        if (api === 'public') {
            if (Object.keys (query).length) {
                url += '?' + this.urlencode (query);
            }
        } else {
            this.checkRequiredCredentials ();
            headers = {
                'apikey': this.apiKey,
                'signature': this.secret,
            };
            if (method === 'GET') {
                if (Object.keys (query).length) {
                    url += '?' + this.urlencode (query);
                }
            } else {
                body = this.json (query);
                headers['Content-Type'] = 'application/json';
            }
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        if (response === undefined) {
            return; // fallback to default error handler
        }
        const status = this.safeValue (response, 'status');
        if (status !== undefined) {
            //
            //     {"status":{"success":0,"message":"ERR_USERTOKEN_NOT_FOUND"}}
            //
            const success = this.safeString (status, 'success');
            if (success !== '1') {
                const message = this.safeString (status, 'message');
                const feedback = this.id + ' ' + body;
                this.throwExactlyMatchedException (this.exceptions, message, feedback);
                throw new ExchangeError (feedback);
            }
        }
    }
};
<commit_msg>delist rightbtc<commit_after><|endoftext|>


<commit_before>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

//var parkMap = {
//  acad: 'Acadia National Park',
//  arch: 'Arches National Park',
//  badl: 'Badlands National Park',
//  brca: 'Bryce Canyon National Park',
//  crla: 'Crater Lake National Park',
//  dena: 'Denali National Park',
//  glac: 'Glacier National Park',
//  grca: 'Grand Canyon National Park',
//  grte: 'Grand Teton National Park',
//  olym: 'Olympic National Park',
//  yell: 'Yellowstone National Park',
//  yose: 'Yosemite National Park',
//  zion: 'Zion National Park'
//};
//var retrievedSharedMaps = {
//  general: 'General',
//  stackPanel: 'Stack Panel',
//  libraries: 'Libraries',
//  parks: 'Parks',
//  parkHighlights: 'Park Highlights',
//  firstFleetPark: 'First Fleet Park',
//  commuting: 'Commuting',
//  drivingDirections: 'Driving Directions',
//  mapRulers: 'Map Rulers'
//};

var getBadges = function(t){
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = GRAY_ICON;
    var lowercaseName = cardName.toLowerCase();
    if(lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = WHITE_ICON;
    }

    if (lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var doGet = function(url) {
  var getPromise = new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open('GET', urlForLocale(resourceUrl, targetLocale), true);
    request.onload = function() {
      try {
        if (request.status === 200) {
          var responseJson = JSON.parse(request.responseText);
          return resolve(responseJson);
        } else if (request.status === 404) {
          return reject(new i18nError.LocaleNotFound(targetLocale + " not found."));
        } else {
          return reject(new i18nError.Unknown("Unable to load locale, status: " + request.status));
        }
      } catch(ex) {
        return reject(new i18nError.Unknown(ex.message));
      }
    };
    request.send();
  });
  return getPromise;
};

var retrieveSharedMaps = function(t) {
  //var retrievedSharedMaps = {
  //  general: 'General',
  //  stackPanel: 'Stack Panel',
  //  libraries: 'Libraries',
  //  parks: 'Parks',
  //  parkHighlights: 'Park Highlights',
  //  firstFleetPark: 'First Fleet Park',
  //  commuting: 'Commuting',
  //  drivingDirections: 'Driving Directions',
  //  mapRulers: 'Map Rulers'
  //};

  //return retrievedSharedMaps;

  var retrievedSharedMaps = [];
  var retrieveSharedMapsUrl = 'https://www.maprosoft.com/app/shared?team=demo&getSharedMapNames=yes';
  var promise = doGet(retrieveSharedMapsUrl);
  //promise = promise.then(function(data) {
  //  //retrievedSharedMaps = data;
  //  var mapNames = data.mapNames;
  //  retrievedSharedMaps = data.mapNames;
  //});
  //promise.resolve();
  //return retrievedSharedMaps;
  return promise;
};

var formatNPSUrl = function(t, url){
  if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){
    return null;
  }
  var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1];
  if (parkShort && parkMap[parkShort]){
    return parkMap[parkShort];
  } else{
    return null;
  }
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Popup List Example',
    items: [
      {
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]
  });
};

var cardButtonCallback = function(t) {
  //var items = Object.keys(retrievedSharedMaps).map(function(sharedMapKey) {
  //  var sharedMapName = retrievedSharedMaps[sharedMapKey];
  //  var teamKey = 'demo';
  //  var encodedSharedMapName = encodeURIComponent(sharedMapName);
  //  var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
  //  return {
  //    text: sharedMapName,
  //    url: sharedMapUrl,
  //    callback: function(t) {
  //      return t.attach({
  //        url: sharedMapUrl,
  //        name: sharedMapName
  //      })
  //      .then(function(){
  //        return t.closePopup();
  //      });
  //    }
  //  };
  //});
  //
  //return t.popup({
  //  title: 'Select a Maprosoft map',
  //  items: items,
  //  search: {
  //    count: 5,
  //    placeholder: 'Search shared maps',
  //    empty: 'No share map found'
  //  }
  //});

  var promise = retrieveSharedMaps(t).then(function(data) {
    var mapNames = data.mapNames;
    var retrievedSharedMaps = data.mapNames;

    var items = Object.keys(retrievedSharedMaps).map(function(sharedMapKey) {
      var sharedMapName = retrievedSharedMaps[sharedMapKey];
      var teamKey = 'demo';
      var encodedSharedMapName = encodeURIComponent(sharedMapName);
      var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
      return {
        text: sharedMapName,
        url: sharedMapUrl,
        callback: function(t) {
          return t.attach({
            url: sharedMapUrl,
            name: sharedMapName
          })
          .then(function(){
            return t.closePopup();
          });
        }
      };
    });

    return t.popup({
      title: 'Select a Maprosoft map',
      items: items,
      search: {
        count: 5,
        placeholder: 'Search shared maps',
        empty: 'No share map found'
      }
    });

  });

  //var mapNames = retrieveSharedMaps(t);
  //var popupItems = [];
  //for (var index = 0; index < mapNames.length; index++) {
  //  var sharedMapName = mapNames[index];
  //  var teamKey = 'demo';
  //  var encodedSharedMapName = encodeURIComponent(sharedMapName);
  //  var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
  //  var popupItem = {
  //    text: sharedMapName,
  //    url: sharedMapUrl,
  //    callback: function(t) {
  //      return t.attach({
  //          url: sharedMapUrl,
  //          name: sharedMapName
  //      }).then(function(){
  //          return t.closePopup();
  //      });
  //    }
  //  };
  //  popupItems.push(popupItem);
  //}
  //
  //
  //return t.popup({
  //  title: 'Select a Maprosoft map',
  //  items: items,
  //  search: {
  //    count: 5,
  //    placeholder: 'Search shared maps',
  //    empty: 'No share map found'
  //  }
  //});
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options) {
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment) {
      return attachment.url.indexOf('https://www.maprosoft.com/app/map') === 0 || attachment.url.indexOf('https://www.maprosoft.com/app/shared') === 0;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if (claimed && claimed.length > 0) {
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var sections = [];
      if (claimed && claimed.length > 0) {
        for (var claimIndex = 0; claimIndex < claimed.length; claimIndex++) {
          var attachment = claimed[claimIndex];
          var claimedAttachments = [];
          claimedAttachments.push(attachment);
          var mapSection = {
            id: 'maprosoft-map', // optional if you aren't using a function for the title
            claimed: claimedAttachments,
            icon: GRAY_ICON,
            title: 'Maprosoft Map v13 [' + claimIndex + ']',
            content: {
              type: 'iframe',
              url: t.signUrl('./map-section.html',
                  { "map-url": attachment.url }),
              height: 400
            }
          };
          sections.push(mapSection);
        }
      }
      return sections;
    } else {
      return [];
    }
  },
  'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if (parkName) {
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Template',
      callback: boardButtonCallback
    }];
  },
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Maprosoft map',
      callback: cardButtonCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: GRAY_ICON,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>update<commit_after>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

//var parkMap = {
//  acad: 'Acadia National Park',
//  arch: 'Arches National Park',
//  badl: 'Badlands National Park',
//  brca: 'Bryce Canyon National Park',
//  crla: 'Crater Lake National Park',
//  dena: 'Denali National Park',
//  glac: 'Glacier National Park',
//  grca: 'Grand Canyon National Park',
//  grte: 'Grand Teton National Park',
//  olym: 'Olympic National Park',
//  yell: 'Yellowstone National Park',
//  yose: 'Yosemite National Park',
//  zion: 'Zion National Park'
//};
//var retrievedSharedMaps = {
//  general: 'General',
//  stackPanel: 'Stack Panel',
//  libraries: 'Libraries',
//  parks: 'Parks',
//  parkHighlights: 'Park Highlights',
//  firstFleetPark: 'First Fleet Park',
//  commuting: 'Commuting',
//  drivingDirections: 'Driving Directions',
//  mapRulers: 'Map Rulers'
//};

var getBadges = function(t){
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = GRAY_ICON;
    var lowercaseName = cardName.toLowerCase();
    if(lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = WHITE_ICON;
    }

    if (lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var doGet = function(url) {
  var getPromise = new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open('GET', urlForLocale(resourceUrl, targetLocale), true);
    request.onload = function() {
      try {
        if (request.status === 200) {
          var responseJson = JSON.parse(request.responseText);
          return resolve(responseJson);
        } else if (request.status === 404) {
          return reject(new i18nError.LocaleNotFound(targetLocale + " not found."));
        } else {
          return reject(new i18nError.Unknown("Unable to load locale, status: " + request.status));
        }
      } catch(ex) {
        return reject(new i18nError.Unknown(ex.message));
      }
    };
    request.send();
  });
  return getPromise;
};

var retrieveSharedMaps = function(t) {
  //var retrievedSharedMaps = {
  //  general: 'General',
  //  stackPanel: 'Stack Panel',
  //  libraries: 'Libraries',
  //  parks: 'Parks',
  //  parkHighlights: 'Park Highlights',
  //  firstFleetPark: 'First Fleet Park',
  //  commuting: 'Commuting',
  //  drivingDirections: 'Driving Directions',
  //  mapRulers: 'Map Rulers'
  //};

  //return retrievedSharedMaps;

  var retrievedSharedMaps = [];
  var retrieveSharedMapsUrl = 'https://www.maprosoft.com/app/shared?team=demo&getSharedMapNames=yes';
  var promise = doGet(retrieveSharedMapsUrl);
  //promise = promise.then(function(data) {
  //  //retrievedSharedMaps = data;
  //  var mapNames = data.mapNames;
  //  retrievedSharedMaps = data.mapNames;
  //});
  //promise.resolve();
  //return retrievedSharedMaps;
  return promise;
};

var formatNPSUrl = function(t, url){
  if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){
    return null;
  }
  var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1];
  if (parkShort && parkMap[parkShort]){
    return parkMap[parkShort];
  } else{
    return null;
  }
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Popup List Example',
    items: [
      {
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]
  });
};

var cardButtonCallback = function(t) {
  //var items = Object.keys(retrievedSharedMaps).map(function(sharedMapKey) {
  //  var sharedMapName = retrievedSharedMaps[sharedMapKey];
  //  var teamKey = 'demo';
  //  var encodedSharedMapName = encodeURIComponent(sharedMapName);
  //  var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
  //  return {
  //    text: sharedMapName,
  //    url: sharedMapUrl,
  //    callback: function(t) {
  //      return t.attach({
  //        url: sharedMapUrl,
  //        name: sharedMapName
  //      })
  //      .then(function(){
  //        return t.closePopup();
  //      });
  //    }
  //  };
  //});
  //
  //return t.popup({
  //  title: 'Select a Maprosoft map',
  //  items: items,
  //  search: {
  //    count: 5,
  //    placeholder: 'Search shared maps',
  //    empty: 'No share map found'
  //  }
  //});

  var promise = retrieveSharedMaps(t);
  var promise = promise.then(function(data) {
    var mapNames = data.mapNames;
    var retrievedSharedMaps = data.mapNames;

    var items = Object.keys(retrievedSharedMaps).map(function(sharedMapKey) {
      var sharedMapName = retrievedSharedMaps[sharedMapKey];
      var teamKey = 'demo';
      var encodedSharedMapName = encodeURIComponent(sharedMapName);
      var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
      return {
        text: sharedMapName,
        url: sharedMapUrl,
        callback: function(t) {
          return t.attach({
            url: sharedMapUrl,
            name: sharedMapName
          })
          .then(function(){
            return t.closePopup();
          });
        }
      };
    });

    return t.popup({
      title: 'Select a Maprosoft map',
      items: items,
      search: {
        count: 5,
        placeholder: 'Search shared maps',
        empty: 'No share map found'
      }
    });

  });

  //var mapNames = retrieveSharedMaps(t);
  //var popupItems = [];
  //for (var index = 0; index < mapNames.length; index++) {
  //  var sharedMapName = mapNames[index];
  //  var teamKey = 'demo';
  //  var encodedSharedMapName = encodeURIComponent(sharedMapName);
  //  var sharedMapUrl = 'https://www.maprosoft.com/app/shared/' + teamKey + '/' + encodedSharedMapName;
  //  var popupItem = {
  //    text: sharedMapName,
  //    url: sharedMapUrl,
  //    callback: function(t) {
  //      return t.attach({
  //          url: sharedMapUrl,
  //          name: sharedMapName
  //      }).then(function(){
  //          return t.closePopup();
  //      });
  //    }
  //  };
  //  popupItems.push(popupItem);
  //}
  //
  //
  //return t.popup({
  //  title: 'Select a Maprosoft map',
  //  items: items,
  //  search: {
  //    count: 5,
  //    placeholder: 'Search shared maps',
  //    empty: 'No share map found'
  //  }
  //});
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options) {
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment) {
      return attachment.url.indexOf('https://www.maprosoft.com/app/map') === 0 || attachment.url.indexOf('https://www.maprosoft.com/app/shared') === 0;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if (claimed && claimed.length > 0) {
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var sections = [];
      if (claimed && claimed.length > 0) {
        for (var claimIndex = 0; claimIndex < claimed.length; claimIndex++) {
          var attachment = claimed[claimIndex];
          var claimedAttachments = [];
          claimedAttachments.push(attachment);
          var mapSection = {
            id: 'maprosoft-map', // optional if you aren't using a function for the title
            claimed: claimedAttachments,
            icon: GRAY_ICON,
            title: 'Maprosoft Map v13 [' + claimIndex + ']',
            content: {
              type: 'iframe',
              url: t.signUrl('./map-section.html',
                  { "map-url": attachment.url }),
              height: 400
            }
          };
          sections.push(mapSection);
        }
      }
      return sections;
    } else {
      return [];
    }
  },
  'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if (parkName) {
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Template',
      callback: boardButtonCallback
    }];
  },
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Maprosoft map',
      callback: cardButtonCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: GRAY_ICON,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>/* global Trello, jQuery, TrelloPowerUp */
var SHARE_ICON = './images/fa-share-alt.svg';
var PRINTER_URL = 'https://awolf81.github.io/TrelloPrinter/?url=';

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

function postJSON(data) {
    return $.ajax('https://jsonblob.com/api/jsonBlob', {
    	method: 'POST',
        crossDomain: true,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var cardButtonCallback = function(t) {
    return t.card('all')
    .then(function(promiseResult) {
      console.log(promiseResult);
      var url = promiseResult.url;
      return t.popup({
          title: 'Share this card',
          items: [
              {
                text: 'Share card: ' + url,
                url: url,
                callback: function(t){
                  return postJSON(promiseResult).then(
                      function(res, status, jqXHR) {
                          var sharedURL  = jqXHR.getResponseHeader('Location');
                          return t.attach({
                              url: PRINTER_URL + sharedURL,
                              name: 'Shared JSON'

                          })
                          .then(function(){
                            return t.closePopup();
                          })
                      },
                      function(err) {
                          console.log(err); // todo --> show notifcation
                      }
                  )
                }
              }
          ]
      });
    });
}

// share board or panel
function shareCallback(type, t) {
    return t.lists('all')
        .then(function(promiseResult) {
            // always load board data --> needed to post or display selection
            if (type === 'board') {
                return postJSON(promiseResult).then(function(res, status, jqXHR) {
                    var sharedURL  = jqXHR.getResponseHeader('Location');
                    return t.popup({
                        //url: PRINTER_URL + sharedURL, // url loads html into the popup
                        title: 'Shared board successfully',
                        items: [
                            {
                                text: 'Open share',
                                callback: function(t) {
                                    openInNewTab(PRINTER_URL + sharedURL),
                                    t.closePopup();
                                }
                            },
                            {
                                text: 'Copy URL to clipboard',
                                callback: function(t) {
                                    window.prompt("Copy to clipboard: Ctrl+C, Enter", PRINTER_URL + sharedURL);
                                    t.closePopup();
                                }
                            }
                        ]
                    })
                    /*.then(function(){
                      return t.closePopup();
                  })*/
                },
                function(err) {
                    console.log(err); // todo --> show notifcation
                });
            }
            else {
                // load board bar and display checkboxes with panels to export
                return t.boardBar({
                    url: './board-bar.html',
                    height: 200
                })
                .then(function(){
                    return t.closePopup();
                });
            }
        });

}

// wrapper functions for sharing
var shareBoard = function(t) {
    return shareCallback('board', t);
};

var sharePanel = function(t) {
    return shareCallback('panel', t);
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Share board or panel',
    items: [
        {
            text: 'Board',
            callback: shareBoard
        },
        {
            text: 'Panel',
            callback: sharePanel
        }
    ]
      /*{
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]*/
  });
};

TrelloPowerUp.initialize({
  'card-buttons': function(t, options) {
    return [{
      icon: SHARE_ICON,
      text: 'Share',
      callback: cardButtonCallback
    }];
  },
  'board-buttons': function(t, options){
    return [{
      icon: SHARE_ICON,
      text: 'Share board or panel',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>changed share query<commit_after>/* global Trello, jQuery, TrelloPowerUp */
var SHARE_ICON = './images/fa-share-alt.svg';
var PRINTER_URL = 'https://awolf81.github.io/TrelloPrinter/?url=';

function openInNewTab(url) {
  var win = window.open(url, '_blank');
  win.focus();
}

function postJSON(data) {
    return $.ajax('https://jsonblob.com/api/jsonBlob', {
    	method: 'POST',
        crossDomain: true,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
}

var cardButtonCallback = function(t) {
    return t.card('all')
    .then(function(promiseResult) {
      console.log(promiseResult);
      var url = promiseResult.url;
      return t.popup({
          title: 'Share this card',
          items: [
              {
                text: 'Share card: ' + url,
                url: url,
                callback: function(t){
                  return postJSON(promiseResult).then(
                      function(res, status, jqXHR) {
                          var sharedURL  = jqXHR.getResponseHeader('Location');
                          return t.attach({
                              url: PRINTER_URL + sharedURL,
                              name: 'Shared JSON'

                          })
                          .then(function(){
                            return t.closePopup();
                          })
                      },
                      function(err) {
                          console.log(err); // todo --> show notifcation
                      }
                  )
                }
              }
          ]
      });
    });
}

// share board or panel
function shareCallback(type, t) {
    return t.get(window.location + '.json') // browser url + json --> returns json of board
        .then(function(promiseResult) {
            // always load board data --> needed to post or display selection
            if (type === 'board') {
                return postJSON(promiseResult).then(function(res, status, jqXHR) {
                    var sharedURL  = jqXHR.getResponseHeader('Location');
                    return t.popup({
                        //url: PRINTER_URL + sharedURL, // url loads html into the popup
                        title: 'Shared board successfully',
                        items: [
                            {
                                text: 'Open share',
                                callback: function(t) {
                                    openInNewTab(PRINTER_URL + sharedURL),
                                    t.closePopup();
                                }
                            },
                            {
                                text: 'Copy URL to clipboard',
                                callback: function(t) {
                                    window.prompt("Copy to clipboard: Ctrl+C, Enter", PRINTER_URL + sharedURL);
                                    t.closePopup();
                                }
                            }
                        ]
                    })
                    /*.then(function(){
                      return t.closePopup();
                  })*/
                },
                function(err) {
                    console.log(err); // todo --> show notifcation
                });
            }
            else {
                // load board bar and display checkboxes with panels to export
                return t.boardBar({
                    url: './board-bar.html',
                    height: 200
                })
                .then(function(){
                    return t.closePopup();
                });
            }
        });

}

// wrapper functions for sharing
var shareBoard = function(t) {
    return shareCallback('board', t);
};

var sharePanel = function(t) {
    return shareCallback('panel', t);
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Share board or panel',
    items: [
        {
            text: 'Board',
            callback: shareBoard
        },
        {
            text: 'Panel',
            callback: sharePanel
        }
    ]
      /*{
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]*/
  });
};

TrelloPowerUp.initialize({
  'card-buttons': function(t, options) {
    return [{
      icon: SHARE_ICON,
      text: 'Share',
      callback: cardButtonCallback
    }];
  },
  'board-buttons': function(t, options){
    return [{
      icon: SHARE_ICON,
      text: 'Share board or panel',
      callback: boardButtonCallback
    }];
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

var parkMap = {
  acad: 'Acadia National Park',
  arch: 'Arches National Park',
  badl: 'Badlands National Park',
  brca: 'Bryce Canyon National Park',
  crla: 'Crater Lake National Park',
  dena: 'Denali National Park',
  glac: 'Glacier National Park',
  grca: 'Grand Canyon National Park',
  grte: 'Grand Teton National Park',
  olym: 'Olympic National Park',
  yell: 'Yellowstone National Park',
  yose: 'Yosemite National Park',
  zion: 'Zion National Park'
};

var getBadges = function(t){
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = GRAY_ICON;
    var lowercaseName = cardName.toLowerCase();
    if(lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = WHITE_ICON;
    }

    if(lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var formatNPSUrl = function(t, url){
  if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){
    return null;
  }
  var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1];
  if(parkShort && parkMap[parkShort]){
    return parkMap[parkShort];
  } else{
    return null;
  }
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Popup List Example',
    items: [
      {
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]
  });
};

var cardButtonCallback = function(t){
  var items = Object.keys(parkMap).map(function(parkCode){
    var urlForCode = 'http://www.nps.gov/' + parkCode + '/';
    return {
      text: parkMap[parkCode],
      url: urlForCode,
      callback: function(t) {
        //return t.attach({
        //  url: urlForCode,
        //  name: parkMap[parkCode] })
        //.then(function(){
        //  return t.closePopup();
        //});

        return t.attach({
              url: t.signUrl('./map-section.html', { arg: 'you can pass your section args here' }),
              name: "My Map"
        }).then(function() {
              return t.closePopup();
        });

        //return t.attach({
        //    id: 'maprosoft-map', // optional if you aren't using a function for the title
        //    claimed: claimed,
        //    icon: GRAY_ICON,
        //    title: 'Maprosoft Map v3',
        //    content: {
        //      type: 'iframe',
        //      url: t.signUrl('./map-section.html',
        //          { arg: 'you can pass your section args here' }),
        //      height: 400
        //    }
        //}).then(function(){
        //      return t.closePopup();
        //    });
      }
    };
  });

  return t.popup({
    title: 'Popup Search Example',
    items: items,
    search: {
      count: 5,
      placeholder: 'Search National Parks',
      empty: 'No parks found'
    }
  });
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options){
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment){
      return attachment.url.indexOf('http://www.nps.gov/yell/') == 0;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if(claimed && claimed.length > 0){
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var parkSectionJson = {
        id: 'Yellowstone', // optional if you aren't using a function for the title
        claimed: claimed,
        icon: GRAY_ICON,
        title: 'Example Attachment Section: Yellowstone',
        content: {
          type: 'iframe',
          url: t.signUrl('./section.html', { arg: 'you can pass your section args here' }),
          height: 230
        }
      };
      var mapSectionJson = {
        id: 'maprosoft-map', // optional if you aren't using a function for the title
        claimed: claimed,
        icon: GRAY_ICON,
        title: 'Maprosoft Map v2',
        content: {
          type: 'iframe',
          url: t.signUrl('./map-section.html',
              { arg: 'you can pass your section args here' }),
          height: 400
        }
      };
      //return [mapSectionJson, parkSectionJson];

      return [mapSectionJson];
    } else {
      return [];
    }
  },
  'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Template',
      callback: boardButtonCallback
    }];
  },
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Maprosoft map',
      callback: cardButtonCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: GRAY_ICON,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>change<commit_after>/* global TrelloPowerUp */

var WHITE_ICON = './images/icon-white.svg';
var GRAY_ICON = './images/icon-gray.svg';

var parkMap = {
  acad: 'Acadia National Park',
  arch: 'Arches National Park',
  badl: 'Badlands National Park',
  brca: 'Bryce Canyon National Park',
  crla: 'Crater Lake National Park',
  dena: 'Denali National Park',
  glac: 'Glacier National Park',
  grca: 'Grand Canyon National Park',
  grte: 'Grand Teton National Park',
  olym: 'Olympic National Park',
  yell: 'Yellowstone National Park',
  yose: 'Yosemite National Park',
  zion: 'Zion National Park'
};

var getBadges = function(t){
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = GRAY_ICON;
    var lowercaseName = cardName.toLowerCase();
    if(lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = WHITE_ICON;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = WHITE_ICON;
    }

    if(lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var formatNPSUrl = function(t, url){
  if(!/^https?:\/\/www\.nps\.gov\/[a-z]{4}\//.test(url)){
    return null;
  }
  var parkShort = /^https?:\/\/www\.nps\.gov\/([a-z]{4})\//.exec(url)[1];
  if(parkShort && parkMap[parkShort]){
    return parkMap[parkShort];
  } else{
    return null;
  }
};

var boardButtonCallback = function(t){
  return t.popup({
    title: 'Popup List Example',
    items: [
      {
        text: 'Open Overlay',
        callback: function(t){
          return t.overlay({
            url: './overlay.html',
            args: { rand: (Math.random() * 100).toFixed(0) }
          })
          .then(function(){
            return t.closePopup();
          });
        }
      },
      {
        text: 'Open Board Bar',
        callback: function(t){
          return t.boardBar({
            url: './board-bar.html',
            height: 200
          })
          .then(function(){
            return t.closePopup();
          });
        }
      }
    ]
  });
};

var cardButtonCallback = function(t){
  var items = Object.keys(parkMap).map(function(parkCode){
    var urlForCode = 'http://www.nps.gov/' + parkCode + '/';
    return {
      text: parkMap[parkCode],
      url: urlForCode,
      callback: function(t) {
        //return t.attach({
        //  url: urlForCode,
        //  name: parkMap[parkCode] })
        //.then(function(){
        //  return t.closePopup();
        //});

        //return t.attach({
        //      url: t.signUrl('./map-section.html', { arg: 'you can pass your section args here' }),
        //      name: "My Map"
        //}).then(function() {
        //      return t.closePopup();
        //});

        return t.attach({
          url: t.signUrl('./map-section.html', { arg: 'you can pass your section args here' }),
          name: "My Map"
        }).then(function() {
          return t.closePopup();
        });

        //return t.attach({
        //    id: 'maprosoft-map', // optional if you aren't using a function for the title
        //    claimed: claimed,
        //    icon: GRAY_ICON,
        //    title: 'Maprosoft Map v3',
        //    content: {
        //      type: 'iframe',
        //      url: t.signUrl('./map-section.html',
        //          { arg: 'you can pass your section args here' }),
        //      height: 400
        //    }
        //}).then(function(){
        //      return t.closePopup();
        //    });
      }
    };
  });

  return t.popup({
    title: 'Popup Search Example',
    items: items,
    search: {
      count: 5,
      placeholder: 'Search National Parks',
      empty: 'No parks found'
    }
  });
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options){
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment){
      return attachment.url.indexOf('https://www.maprosoft.com/app/map') == 0;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if(claimed && claimed.length > 0){
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var parkSectionJson = {
        id: 'Yellowstone', // optional if you aren't using a function for the title
        claimed: claimed,
        icon: GRAY_ICON,
        title: 'Example Attachment Section: Yellowstone',
        content: {
          type: 'iframe',
          url: t.signUrl('./section.html', { arg: 'you can pass your section args here' }),
          height: 230
        }
      };
      var mapSectionJson = {
        id: 'maprosoft-map', // optional if you aren't using a function for the title
        claimed: claimed,
        icon: GRAY_ICON,
        title: 'Maprosoft Map v2',
        content: {
          type: 'iframe',
          url: t.signUrl('./map-section.html',
              { "map-url": 'abc' }),
          height: 400
        }
      };
      //return [mapSectionJson, parkSectionJson];
      //return [mapSectionJson];

      var sections = [];
      if (claimed && claimed.length > 0) {
        for (var claimIndex = 0; claimIndex < claimed.length; claimIndex++) {
          var attachment = claimed[claimIndex];
          var mapSection = {
            id: 'maprosoft-map', // optional if you aren't using a function for the title
            claimed: claimed,
            icon: GRAY_ICON,
            title: 'Maprosoft Map v3',
            content: {
              type: 'iframe',
              url: t.signUrl('./map-section.html',
                  { "map-url": attachment.url }),
              height: 400
            }
          };
          sections.push(mapSection);
        }
      }
      return sections;
    } else {
      return [];
    }
  },
  'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },
  'board-buttons': function(t, options){
    return [{
      icon: WHITE_ICON,
      text: 'Template',
      callback: boardButtonCallback
    }];
  },
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: GRAY_ICON,
      text: 'Maprosoft map',
      callback: cardButtonCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: GRAY_ICON,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>/* global TrelloPowerUp */

var cachedCardInfo = {};

var getBadges = function(t) {
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = MAPROSOFT_ICON_GRAY;
    var lowercaseName = cardName.toLowerCase();
    if (lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = MAPROSOFT_ICON_COLOR;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = MAPROSOFT_ICON_COLOR;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = MAPROSOFT_ICON_COLOR;
    }

    if (lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var boardButtonCallback = function(t) {
  return t.get('board', 'private', TEAM_NAME_KEY)
      .then(function(teamName) {
        if (teamName) {
          var generalMapUrl = buildGeneralMapUrl(teamName);
          var settingsOk = teamName && teamName.length;
          return t.overlay({
            url: './map-overlay.html',
            args: {
              settingsOk: settingsOk,
              'map-url': generalMapUrl,
              overlayMode: true
            }
          })
          .then(function(){
            return t.closePopup();
          });
        } else {
          return t.overlay({
            url: './no-settings.html',
            args: {}
          })
          .then(function () {
            return t.closePopup();
          });
        }
      });
};

var buildMapSection = function(t, attachment) {
  // Capture the attachment variable in a closure so that it's attributes are safe to pass
  // into promises such as the signUrl function.
  var claimedAttachments = [attachment];
  var attachmentUrl = attachment.url;
  var signedUrl = t.signUrl('./map-section.html', {
    "map-url": attachmentUrl,
    settingsOk: true
  });
  if (attachment.name) {
    var attachmentTitle = attachment.name;
  } else {
    if (attachmentUrl.indexOf('dropPin') > 0) {
      var attachmentTitle = 'Maprosoft location map';
    } else {
      var attachmentTitle = extractSharedMapNameFromUrl(attachmentUrl);
    }
  }
  //console.log('Signed URL for attachment ' + attachmentUrl + " => " + signedUrl);
  var mapSection = {
    //id: 'maprosoft-map', // optional if you aren't using a function for the title
    claimed: claimedAttachments,
    icon: MAPROSOFT_ICON_GRAY,
    title: attachmentTitle,
    content: {
      type: 'iframe',
      url: signedUrl,
      height: 400
    }
  };
  //console.log('Built map section: ' + attachmentUrl);
  return mapSection;
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options) {
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment) {
      var claim = isMapLinkAttachment(attachment);
      //console.log('Returning ' + claim + ' for attachment ' + attachment.url);
      return claim;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if (claimed && claimed.length > 0) {
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var sections = [];
      for (var claimIndex = 0; claimIndex < claimed.length; claimIndex++) {
        var attachment = claimed[claimIndex];
        var mapSection = buildMapSection(t, attachment);
        sections.push(mapSection);
      }
      return sections;
    } else {
      return [];
    }
  },
  /*'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if (parkName) {
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },*/
  /*'board-buttons': function(t, options){
    return [{
      icon: MAPROSOFT_ICON_COLOR,
      text: 'Maprosoft Map',
      callback: boardButtonCallback
    }];
  },*/
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: MAPROSOFT_ICON_GRAY,
      text: 'Add map',
      callback: handleAddMapCallback
    }, {
      icon: MAPROSOFT_ICON_GRAY,
      text: 'A: Map',
      callback: addSharedMapCallbackA
    }, {
      icon: MAPROSOFT_ICON_GRAY,
      text: 'B: Map',
      callback: addSharedMapCallbackB
    }, {
      icon: MAPROSOFT_ICON_GRAY,
      text: 'C: Map',
      callback: addSharedMapCallbackC
    }, /*, {
      icon: MAPROSOFT_ICON_GRAY,
      text: 'Location Map',
      callback: addLocationMapCallback
    }*/];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  /*'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: MAPROSOFT_ICON_GRAY,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },*/
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<commit_msg>update<commit_after>/* global TrelloPowerUp */

var cachedCardInfo = {};

var getBadges = function(t) {
  return t.card('name')
  .get('name')
  .then(function(cardName){
    var badgeColor;
    var icon = MAPROSOFT_ICON_GRAY;
    var lowercaseName = cardName.toLowerCase();
    if (lowercaseName.indexOf('green') > -1){
      badgeColor = 'green';
      icon = MAPROSOFT_ICON_COLOR;
    } else if(lowercaseName.indexOf('yellow') > -1){
      badgeColor = 'yellow';
      icon = MAPROSOFT_ICON_COLOR;
    } else if(lowercaseName.indexOf('red') > -1){
      badgeColor = 'red';
      icon = MAPROSOFT_ICON_COLOR;
    }

    if (lowercaseName.indexOf('dynamic') > -1){
      // dynamic badges can have their function rerun after a set number
      // of seconds defined by refresh. Minimum of 10 seconds.
      return [{
        dynamic: function(){
          return {
            title: 'Detail Badge', // for detail badges only
            text: 'Dynamic ' + (Math.random() * 100).toFixed(0).toString(),
            icon: icon, // for card front badges only
            color: badgeColor,
            refresh: 10
          }
        }
      }]
    }

    if(lowercaseName.indexOf('static') > -1){
      // return an array of badge objects
      return [{
        title: 'Detail Badge', // for detail badges only
        text: 'Static',
        icon: icon, // for card front badges only
        color: badgeColor
      }];
    } else {
      return [];
    }
  })
};

var boardButtonCallback = function(t) {
  return t.get('board', 'private', TEAM_NAME_KEY)
      .then(function(teamName) {
        if (teamName) {
          var generalMapUrl = buildGeneralMapUrl(teamName);
          var settingsOk = teamName && teamName.length;
          return t.overlay({
            url: './map-overlay.html',
            args: {
              settingsOk: settingsOk,
              'map-url': generalMapUrl,
              overlayMode: true
            }
          })
          .then(function(){
            return t.closePopup();
          });
        } else {
          return t.overlay({
            url: './no-settings.html',
            args: {}
          })
          .then(function () {
            return t.closePopup();
          });
        }
      });
};

var buildMapSection = function(t, attachment) {
  // Capture the attachment variable in a closure so that it's attributes are safe to pass
  // into promises such as the signUrl function.
  var claimedAttachments = [attachment];
  var attachmentUrl = attachment.url;
  var signedUrl = t.signUrl('./map-section.html', {
    "map-url": attachmentUrl,
    settingsOk: true
  });
  if (attachment.name) {
    var attachmentTitle = attachment.name;
  } else {
    if (attachmentUrl.indexOf('dropPin') > 0) {
      var attachmentTitle = 'Maprosoft location map';
    } else {
      var attachmentTitle = extractSharedMapNameFromUrl(attachmentUrl);
    }
  }
  //console.log('Signed URL for attachment ' + attachmentUrl + " => " + signedUrl);
  var mapSection = {
    //id: 'maprosoft-map', // optional if you aren't using a function for the title
    claimed: claimedAttachments,
    icon: MAPROSOFT_ICON_GRAY,
    title: attachmentTitle,
    content: {
      type: 'iframe',
      url: signedUrl,
      height: 400
    }
  };
  //console.log('Built map section: ' + attachmentUrl);
  return mapSection;
};

TrelloPowerUp.initialize({
  'attachment-sections': function(t, options) {
    // options.entries is a list of the attachments for this card
    // you can look through them and 'claim' any that you want to
    // include in your section.

    // we will just claim urls for Yellowstone
    var claimed = options.entries.filter(function(attachment) {
      var claim = isMapLinkAttachment(attachment);
      //console.log('Returning ' + claim + ' for attachment ' + attachment.url);
      return claim;
    });

    // you can have more than one attachment section on a card
    // you can group items together into one section, have a section
    // per attachment, or anything in between.
    if (claimed && claimed.length > 0) {
      // if the title for your section requires a network call or other
      // potentially length operation you can provide a function for the title
      // that returns the section title. If you do so, provide a unique id for
      // your section
      var sections = [];
      for (var claimIndex = 0; claimIndex < claimed.length; claimIndex++) {
        var attachment = claimed[claimIndex];
        var mapSection = buildMapSection(t, attachment);
        sections.push(mapSection);
      }
      return sections;
    } else {
      return [];
    }
  },
  /*'attachment-thumbnail': function(t, options){
    var parkName = formatNPSUrl(t, options.url);
    if (parkName) {
      // return an object with some or all of these properties:
      // url, title, image, openText, modified (Date), created (Date), createdBy, modifiedBy
      return {
        url: options.url,
        title: parkName,
        image: {
          url: './images/nps.svg',
          logo: true // false if you are using a thumbnail of the content
        },
        openText: 'Open in NPS'
      };
    } else {
      throw t.NotHandled();
    }
  },*/
  /*'board-buttons': function(t, options){
    return [{
      icon: MAPROSOFT_ICON_COLOR,
      text: 'Maprosoft Map',
      callback: boardButtonCallback
    }];
  },*/
  'card-badges': function(t, options){
    return getBadges(t);
  },
  'card-buttons': function(t, options) {
    return [{
      icon: MAPROSOFT_ICON_GRAY,
      text: 'Add map',
      callback: handleAddMapCallback
    //} , {
    //  icon: MAPROSOFT_ICON_GRAY,
    //  text: 'A: Map',
    //  callback: addSharedMapCallbackA
    //}, {
    //  icon: MAPROSOFT_ICON_GRAY,
    //  text: 'B: Map',
    //  callback: addSharedMapCallbackB
    //}, {
    //  icon: MAPROSOFT_ICON_GRAY,
    //  text: 'C: Map',
    //  callback: addSharedMapCallbackC
    //}, {
    //  icon: MAPROSOFT_ICON_GRAY,
    //  text: 'Location Map',
    //  callback: addLocationMapCallback
    }];
  },
  'card-detail-badges': function(t, options) {
    return getBadges(t);
  },
  /*'card-from-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        name: parkName,
        desc: 'An awesome park: ' + options.url
      };
    } else {
      throw t.NotHandled();
    }
  },
  'format-url': function(t, options) {
    var parkName = formatNPSUrl(t, options.url);
    if(parkName){
      return {
        icon: MAPROSOFT_ICON_GRAY,
        text: parkName
      };
    } else {
      throw t.NotHandled();
    }
  },*/
  'show-settings': function(t, options){
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184
    });
  }
});
<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
    $('#terminal').terminal({
            help: function () {
                this.echo('');
                this.echo('[[;#E2462A;#000]profiles]         all my social profiles');
                this.echo('[[;#D4E22A;#000]languages]        programming languages of course');
                this.echo('[[;#2AE27F;#000]softwares]        software I use');
                this.echo('[[;#2ACEE2;#000]pgp]              send me something encrypted');
                this.echo('');
                this.echo('[[;#E22AD1;#000]clear]          clears the console');
            },
            profiles: function() {
                this.echo('');
                this.echo("Github           http://github.com/xcrucifier");
                this.echo("Twitter          http://twitter.com/nigelmd");
                this.echo("LinkedIn         http://linkedin.com/in/nigelmd");
                this.echo("Keybase          http://keybase.io/xcrucifier");
                this.echo('');
            },
            languages: function() {
                this.echo('');
                this.echo('Python');
                this.echo('Java');
                this.echo('Scala');
                this.echo('C/C++');
                this.echo('PHP');
                this.echo('HTML5');
                this.echo('JavaScript');
                this.echo('');
            },
            softwares: function() {
                this.echo('');
                this.echo('Mac OSX');
                this.echo('Z shell');
                this.echo('Windows');
                this.echo('Linux(Ubuntu, Redhat)');
                this.echo('All Jetbrains products');
                this.echo('Sequel Pro');
                this.echo('Homebrew');
                this.echo('Vagrant');
                this.echo('Amazon Web Services');
                this.echo('');
            },
            pgp: function() {
                this.echo('');
                this.echo('PGP              http://pgp.mit.edu/pks/lookup?search=0x6C8571E9');
                this.echo('Fingerprint      9B87 856A 6C85 71E9');
                this.echo('');
            }
        },
        {
            prompt: 'guest@nigeldsouza> ',
            name: 'Nigel\'s Terminal',
            height: 400,
            enabled: true,
            greetings: 'Hi, welcome to my website. Type [[;#2AE24C;#000]help] for more options',
            history: true,
            cookie: true,
            exit: true,
            keypress: function(e) {
                if (e.which == 96) {
                    return false;
                }
            },
            tabcomplete: function() { return ""; }
        });
});
<commit_msg>Shell change<commit_after>jQuery(document).ready(function($) {
    $('#terminal').terminal({
            help: function () {
                this.echo('');
                this.echo('[[;#E2462A;#000]profiles]         all my social profiles');
                this.echo('[[;#D4E22A;#000]languages]        programming languages of course');
                this.echo('[[;#2AE27F;#000]softwares]        software I use');
                this.echo('[[;#2ACEE2;#000]pgp]              send me something encrypted');
                this.echo('');
                this.echo('[[;#E22AD1;#000]clear]          clears the console');
            },
            profiles: function() {
                this.echo('');
                this.echo("Github           http://github.com/xcrucifier");
                this.echo("Twitter          http://twitter.com/nigelmd");
                this.echo("LinkedIn         http://linkedin.com/in/nigelmd");
                this.echo("Keybase          http://keybase.io/xcrucifier");
                this.echo('');
            },
            languages: function() {
                this.echo('');
                this.echo('Python');
                this.echo('Java');
                this.echo('Scala');
                this.echo('C/C++');
                this.echo('PHP');
                this.echo('HTML5');
                this.echo('JavaScript');
                this.echo('');
            },
            softwares: function() {
                this.echo('');
                this.echo('Mac OSX');
                this.echo('ZSH');
                this.echo('Windows');
                this.echo('Linux(Ubuntu, Redhat)');
                this.echo('All Jetbrains products');
                this.echo('Sequel Pro');
                this.echo('Homebrew');
                this.echo('Vagrant');
                this.echo('Amazon Web Services');
                this.echo('');
            },
            pgp: function() {
                this.echo('');
                this.echo('PGP              http://pgp.mit.edu/pks/lookup?search=0x6C8571E9');
                this.echo('Fingerprint      9B87 856A 6C85 71E9');
                this.echo('');
            }
        },
        {
            prompt: 'guest@nigeldsouza> ',
            name: 'Nigel\'s Terminal',
            height: 400,
            enabled: true,
            greetings: 'Hi, welcome to my website. Type [[;#2AE24C;#000]help] for more options',
            history: true,
            cookie: true,
            exit: true,
            keypress: function(e) {
                if (e.which == 96) {
                    return false;
                }
            },
            tabcomplete: function() { return ""; }
        });
});
<|endoftext|>