<commit_before>'use strict';

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

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

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

module.exports = class paymium extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'paymium',
            'name': 'Paymium',
            'countries': [ 'FR', 'EU' ],
            'rateLimit': 2000,
            'version': 'v1',
            'has': {
                'CORS': true,
                'spot': true,
                'margin': undefined,
                'swap': false,
                'future': false,
                'option': false,
                'cancelOrder': true,
                'createOrder': true,
                'fetchBalance': true,
                'fetchFundingHistory': false,
                'fetchFundingRate': false,
                'fetchFundingRateHistory': false,
                'fetchFundingRates': false,
                'fetchIndexOHLCV': false,
                'fetchIsolatedPositions': false,
                'fetchLeverage': false,
                'fetchMarkOHLCV': false,
                'fetchOrderBook': true,
                'fetchPositions': false,
                'fetchPositionsRisk': false,
                'fetchPremiumIndexOHLCV': false,
                'fetchTicker': true,
                'fetchTrades': true,
                'reduceMargin': false,
                'setLeverage': false,
                'setPositionMode': false,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/51840849/87153930-f0f02200-c2c0-11ea-9c0a-40337375ae89.jpg',
                'api': 'https://paymium.com/api',
                'www': 'https://www.paymium.com',
                'fees': 'https://www.paymium.com/page/help/fees',
                'doc': [
                    'https://github.com/Paymium/api-documentation',
                    'https://www.paymium.com/page/developers',
                ],
                'referral': 'https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj',
            },
            'api': {
                'public': {
                    'get': [
                        'countries',
                        'data/{currency}/ticker',
                        'data/{currency}/trades',
                        'data/{currency}/depth',
                        'bitcoin_charts/{id}/trades',
                        'bitcoin_charts/{id}/depth',
                    ],
                },
                'private': {
                    'get': [
                        'user',
                        'user/addresses',
                        'user/addresses/{address}',
                        'user/orders',
                        'user/orders/{uuid}',
                        'user/price_alerts',
                        'merchant/get_payment/{uuid}',
                    ],
                    'post': [
                        'user/addresses',
                        'user/orders',
                        'user/withdrawals',
                        'user/email_transfers',
                        'user/payment_requests',
                        'user/price_alerts',
                        'merchant/create_payment',
                    ],
                    'delete': [
                        'user/orders/{uuid}',
                        'user/orders/{uuid}/cancel',
                        'user/price_alerts/{id}',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'baseId': 'btc', 'quoteId': 'eur', 'type': 'spot', 'spot': true },
            },
            'fees': {
                'trading': {
                    'maker': this.parseNumber ('0.002'),
                    'taker': this.parseNumber ('0.002'),
                },
            },
        });
    }

    parseBalance (response) {
        const result = { 'info': response };
        const currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            const code = currencies[i];
            const currency = this.currency (code);
            const currencyId = currency['id'];
            const free = 'balance_' + currencyId;
            if (free in response) {
                const account = this.account ();
                const used = 'locked_' + currencyId;
                account['free'] = this.safeString (response, free);
                account['used'] = this.safeString (response, used);
                result[code] = account;
            }
        }
        return this.safeBalance (result);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.privateGetUser (params);
        return this.parseBalance (response);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'currency': this.marketId (symbol),
        };
        const response = await this.publicGetDataCurrencyDepth (this.extend (request, params));
        return this.parseOrderBook (response, symbol, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTicker (ticker, market = undefined) {
        //
        // {
        //     "high":"33740.82",
        //     "low":"32185.15",
        //     "volume":"4.7890433",
        //     "bid":"33313.53",
        //     "ask":"33497.97",
        //     "midpoint":"33405.75",
        //     "vwap":"32802.5263553",
        //     "at":1643381654,
        //     "price":"33143.91",
        //     "open":"33116.86",
        //     "variation":"0.0817",
        //     "currency":"EUR",
        //     "trade_id":"ce2f5152-3ac5-412d-9b24-9fa72338474c",
        //     "size":"0.00041087"
        // }
        //
        const symbol = this.safeSymbol (undefined, market);
        const timestamp = this.safeTimestamp (ticker, 'at');
        const vwap = this.safeString (ticker, 'vwap');
        const baseVolume = this.safeString (ticker, 'volume');
        const quoteVolume = Precise.stringMul (baseVolume, vwap);
        const last = this.safeString (ticker, 'price');
        return this.safeTicker ({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeString (ticker, 'high'),
            'low': this.safeString (ticker, 'low'),
            'bid': this.safeString (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeString (ticker, 'ask'),
            'askVolume': undefined,
            'vwap': vwap,
            'open': this.safeString (ticker, 'open'),
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeString (ticker, 'variation'),
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market, false);
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'currency': market['id'],
        };
        const ticker = await this.publicGetDataCurrencyTicker (this.extend (request, params));
        //
        // {
        //     "high":"33740.82",
        //     "low":"32185.15",
        //     "volume":"4.7890433",
        //     "bid":"33313.53",
        //     "ask":"33497.97",
        //     "midpoint":"33405.75",
        //     "vwap":"32802.5263553",
        //     "at":1643381654,
        //     "price":"33143.91",
        //     "open":"33116.86",
        //     "variation":"0.0817",
        //     "currency":"EUR",
        //     "trade_id":"ce2f5152-3ac5-412d-9b24-9fa72338474c",
        //     "size":"0.00041087"
        // }
        //
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        const timestamp = this.safeTimestamp (trade, 'created_at_int');
        const id = this.safeString (trade, 'uuid');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const side = this.safeString (trade, 'side');
        const priceString = this.safeString (trade, 'price');
        const amountField = 'traded_' + market['base'].toLowerCase ();
        const amountString = this.safeString (trade, amountField);
        const price = this.parseNumber (priceString);
        const amount = this.parseNumber (amountString);
        const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            '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 = {
            'currency': market['id'],
        };
        const response = await this.publicGetDataCurrencyTrades (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

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

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

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

    handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        if (response === undefined) {
            return;
        }
        const errors = this.safeValue (response, 'errors');
        if (errors !== undefined) {
            throw new ExchangeError (this.id + ' ' + this.json (response));
        }
    }
};
<commit_msg>paymium.has leverage non futures methods as false removed<commit_after>'use strict';

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

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

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

module.exports = class paymium extends Exchange {
    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'paymium',
            'name': 'Paymium',
            'countries': [ 'FR', 'EU' ],
            'rateLimit': 2000,
            'version': 'v1',
            'has': {
                'CORS': true,
                'spot': true,
                'margin': undefined,
                'swap': false,
                'future': false,
                'option': false,
                'cancelOrder': true,
                'createOrder': true,
                'fetchBalance': true,
                'fetchFundingHistory': false,
                'fetchFundingRate': false,
                'fetchFundingRateHistory': false,
                'fetchFundingRates': false,
                'fetchIndexOHLCV': false,
                'fetchMarkOHLCV': false,
                'fetchOrderBook': true,
                'fetchPremiumIndexOHLCV': false,
                'fetchTicker': true,
                'fetchTrades': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/51840849/87153930-f0f02200-c2c0-11ea-9c0a-40337375ae89.jpg',
                'api': 'https://paymium.com/api',
                'www': 'https://www.paymium.com',
                'fees': 'https://www.paymium.com/page/help/fees',
                'doc': [
                    'https://github.com/Paymium/api-documentation',
                    'https://www.paymium.com/page/developers',
                ],
                'referral': 'https://www.paymium.com/page/sign-up?referral=eDAzPoRQFMvaAB8sf-qj',
            },
            'api': {
                'public': {
                    'get': [
                        'countries',
                        'data/{currency}/ticker',
                        'data/{currency}/trades',
                        'data/{currency}/depth',
                        'bitcoin_charts/{id}/trades',
                        'bitcoin_charts/{id}/depth',
                    ],
                },
                'private': {
                    'get': [
                        'user',
                        'user/addresses',
                        'user/addresses/{address}',
                        'user/orders',
                        'user/orders/{uuid}',
                        'user/price_alerts',
                        'merchant/get_payment/{uuid}',
                    ],
                    'post': [
                        'user/addresses',
                        'user/orders',
                        'user/withdrawals',
                        'user/email_transfers',
                        'user/payment_requests',
                        'user/price_alerts',
                        'merchant/create_payment',
                    ],
                    'delete': [
                        'user/orders/{uuid}',
                        'user/orders/{uuid}/cancel',
                        'user/price_alerts/{id}',
                    ],
                },
            },
            'markets': {
                'BTC/EUR': { 'id': 'eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR', 'baseId': 'btc', 'quoteId': 'eur', 'type': 'spot', 'spot': true },
            },
            'fees': {
                'trading': {
                    'maker': this.parseNumber ('0.002'),
                    'taker': this.parseNumber ('0.002'),
                },
            },
        });
    }

    parseBalance (response) {
        const result = { 'info': response };
        const currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            const code = currencies[i];
            const currency = this.currency (code);
            const currencyId = currency['id'];
            const free = 'balance_' + currencyId;
            if (free in response) {
                const account = this.account ();
                const used = 'locked_' + currencyId;
                account['free'] = this.safeString (response, free);
                account['used'] = this.safeString (response, used);
                result[code] = account;
            }
        }
        return this.safeBalance (result);
    }

    async fetchBalance (params = {}) {
        await this.loadMarkets ();
        const response = await this.privateGetUser (params);
        return this.parseBalance (response);
    }

    async fetchOrderBook (symbol, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const request = {
            'currency': this.marketId (symbol),
        };
        const response = await this.publicGetDataCurrencyDepth (this.extend (request, params));
        return this.parseOrderBook (response, symbol, undefined, 'bids', 'asks', 'price', 'amount');
    }

    parseTicker (ticker, market = undefined) {
        //
        // {
        //     "high":"33740.82",
        //     "low":"32185.15",
        //     "volume":"4.7890433",
        //     "bid":"33313.53",
        //     "ask":"33497.97",
        //     "midpoint":"33405.75",
        //     "vwap":"32802.5263553",
        //     "at":1643381654,
        //     "price":"33143.91",
        //     "open":"33116.86",
        //     "variation":"0.0817",
        //     "currency":"EUR",
        //     "trade_id":"ce2f5152-3ac5-412d-9b24-9fa72338474c",
        //     "size":"0.00041087"
        // }
        //
        const symbol = this.safeSymbol (undefined, market);
        const timestamp = this.safeTimestamp (ticker, 'at');
        const vwap = this.safeString (ticker, 'vwap');
        const baseVolume = this.safeString (ticker, 'volume');
        const quoteVolume = Precise.stringMul (baseVolume, vwap);
        const last = this.safeString (ticker, 'price');
        return this.safeTicker ({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': this.safeString (ticker, 'high'),
            'low': this.safeString (ticker, 'low'),
            'bid': this.safeString (ticker, 'bid'),
            'bidVolume': undefined,
            'ask': this.safeString (ticker, 'ask'),
            'askVolume': undefined,
            'vwap': vwap,
            'open': this.safeString (ticker, 'open'),
            'close': last,
            'last': last,
            'previousClose': undefined,
            'change': undefined,
            'percentage': this.safeString (ticker, 'variation'),
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market, false);
    }

    async fetchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const request = {
            'currency': market['id'],
        };
        const ticker = await this.publicGetDataCurrencyTicker (this.extend (request, params));
        //
        // {
        //     "high":"33740.82",
        //     "low":"32185.15",
        //     "volume":"4.7890433",
        //     "bid":"33313.53",
        //     "ask":"33497.97",
        //     "midpoint":"33405.75",
        //     "vwap":"32802.5263553",
        //     "at":1643381654,
        //     "price":"33143.91",
        //     "open":"33116.86",
        //     "variation":"0.0817",
        //     "currency":"EUR",
        //     "trade_id":"ce2f5152-3ac5-412d-9b24-9fa72338474c",
        //     "size":"0.00041087"
        // }
        //
        return this.parseTicker (ticker, market);
    }

    parseTrade (trade, market) {
        const timestamp = this.safeTimestamp (trade, 'created_at_int');
        const id = this.safeString (trade, 'uuid');
        let symbol = undefined;
        if (market !== undefined) {
            symbol = market['symbol'];
        }
        const side = this.safeString (trade, 'side');
        const priceString = this.safeString (trade, 'price');
        const amountField = 'traded_' + market['base'].toLowerCase ();
        const amountString = this.safeString (trade, amountField);
        const price = this.parseNumber (priceString);
        const amount = this.parseNumber (amountString);
        const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
        return {
            'info': trade,
            'id': id,
            'order': undefined,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            '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 = {
            'currency': market['id'],
        };
        const response = await this.publicGetDataCurrencyTrades (this.extend (request, params));
        return this.parseTrades (response, market, since, limit);
    }

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

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

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

    handleErrors (httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody) {
        if (response === undefined) {
            return;
        }
        const errors = this.safeValue (response, 'errors');
        if (errors !== undefined) {
            throw new ExchangeError (this.id + ' ' + this.json (response));
        }
    }
};
<|endoftext|>


<commit_before>// Avoid `console` errors in browsers that lack a console.
if (!(window.console && console.log)) {
    (function() {
        var noop = function() {};
        var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
        var length = methods.length;
        var console = window.console = {};
        while (length--) {
            console[methods[length]] = noop;
        }
    }());
}

// Place any jQuery/helper plugins in here.
<commit_msg>Remove duplicate `markTimeline` from plugins.js<commit_after>// Avoid `console` errors in browsers that lack a console.
if (!(window.console && console.log)) {
    (function() {
        var noop = function() {};
        var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
        var length = methods.length;
        var console = window.console = {};
        while (length--) {
            console[methods[length]] = noop;
        }
    }());
}

// Place any jQuery/helper plugins in here.
<|endoftext|>


<commit_before>/*

This is a custom js for the TutorStudy website.

By: Ryan Ngo

*/
var name, major, description, fee, UTID;

/* Generic Functions */
function getUserInfo(){
    loadMajors();
    $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://52.38.218.199/TutorStudyServlet/GetUserInfo",
        success: function(data){
            var result = data;
            console.log(result);
            switch(result.UTID){
                case 2:
                    $("#tutorInfoForm").hide();
                    break;
                case 3:
                    $("#studentInfoForm").hide();
                    $("#tutorInfoForm input[name='name']").val(result.name);
                    $("#tutorInfoForm input[name='email']").val(result.email);
                    $("#tutorInfoForm input[name='description']").val(result.description);
                    $("#tutorInfoForm input[name='rate']").val(result.rate);
                    $("#tutorInfoForm input[name='major']").val(result.mid);
                    break;
                default:
                    window.location.replace("index.html");
                    break;
            }
        }
    });
}

function loadMajors(){
     $.ajax({
        type: "GET",
        dataType: "json",
        url: "http://52.38.218.199/TutorStudyServlet/GetMajors",
        success:function(data){
            $("#studentMajorSelect").select2({
                data :  $.map(data, function(data){
                            return{
                                id: data.id,
                                text: data.major
                            }
                        }),
                createTag: function(){
                    return null;
                }

            });
            $("#tutorMajorSelect").select2({
                data :  $.map(data, function(data){
                            return{
                                id: data.id,
                                text: data.major
                            }
                        }),
                createTag: function(){
                    return null;
                }
            });
        }
    })
}
/* End Generic Functions */

/* Document Ready Functions */
$(document).ready(function(){
    getUserInfo();
});
/* End Document Ready Functions */<commit_msg>more changes<commit_after>/*

This is a custom js for the TutorStudy website.

By: Ryan Ngo

*/
var name, major, description, fee, UTID;

/* Generic Functions */
function getUserInfo(){
    loadMajors();
    $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://52.38.218.199/TutorStudyServlet/GetUserInfo",
        success: function(data){
            var result = data;
            console.log(result);
            switch(result.UTID){
                case 2:
                    $("#tutorInfoForm").hide();
                    break;
                case 3:
                    $("#studentInfoForm").hide();
                    $("#tutorInfoForm input[name='name']").val(result.name);
                    $("#tutorInfoForm input[name='email']").val(result.email);
                    $("#tutorInfoForm input[name='description']").val(result.Description);
                    $("#tutorInfoForm input[name='rate']").val(result.Rate);
                    $("#tutorInfoForm input[name='major']").val(result.MID);
                    break;
                default:
                    window.location.replace("index.html");
                    break;
            }
        }
    });
}

function loadMajors(){
     $.ajax({
        type: "GET",
        dataType: "json",
        url: "http://52.38.218.199/TutorStudyServlet/GetMajors",
        success:function(data){
            $("#studentMajorSelect").select2({
                data :  $.map(data, function(data){
                            return{
                                id: data.id,
                                text: data.major
                            }
                        }),
                createTag: function(){
                    return null;
                }

            });
            $("#tutorMajorSelect").select2({
                data :  $.map(data, function(data){
                            return{
                                id: data.id,
                                text: data.major
                            }
                        }),
                createTag: function(){
                    return null;
                }
            });
        }
    })
}
/* End Generic Functions */

/* Document Ready Functions */
$(document).ready(function(){
    getUserInfo();
});
/* End Document Ready Functions */<|endoftext|>


<commit_before>$(document).ready(function(){
    document.getElementById("homeLogo").addEventListener("click", function(){
        location.href = "/"
    });

    $.ajax({
        url:"/xiEzMyEY6LAhMzQhYS0=",
        success:function(resp){
            document.getElementById("email").innerHTML = "E-mail: " + resp.email;
        }
    });

    $.ajax({
        url:"/xiEzMyEY6LAhMzQhYS0=",
        success:function(resp){
            if(resp.type){
                document.getElementById("login").style.display = "none";
                document.getElementById("logout").style.visibility = "visible";
            }
        }
    });

    document.getElementById("logout").addEventListener("click", function(){
        $.ajax({
            url:"/logout",
            type:"post",
            success:function(resp){
                location.reload();
                }
            })
    });

    $(function(){
        $("#accView").click(function() {
            document.getElementById("accBox").style.display = "inline";
            document.getElementById("passBox").style.display = "none";
        });
    });

    $(function(){
        $("#passChange").click(function() {
            document.getElementById("passBox").style.display = "inline";
            document.getElementById("accBox").style.display = "none";
        });
    });

    $(function(){
        $("#confirmBut").click(function() {
            var newPass = document.getElementById("newPass").value;
            var confirmPass = document.getElementById("confirmPass").value;
            if (newPass == confirmPass){
                document.getElementById("newPass").value = "";
                document.getElementById("confirmPass").value = "";
                $.ajax({
                    url:"/changeMyPass",
                    data:{
                        confirmPass:confirmPass
                    },
                    type:"post", //"post" is behind the scenes (invisible) versus "get" (hijackable)
                    success:function(resp){
                        if(resp.status == "success"){
                            console.log("successful");
                            alert("Password successfully changed!");
                        } else if(resp.status == "fail"){
                            alert(resp.msg);
                        }
                    }
                });
            } else {
                alert("Please check that the passwords are the same");
            }
        });
    });
});<commit_msg>Update profile.js<commit_after>$(document).ready(function(){
    document.getElementById("homeLogo").addEventListener("click", function(){
        location.href = "/"
    });

    $.ajax({
        url:"/xiEzMyEY6LAhMzQhYS0=",
        success:function(resp){
            document.getElementById("email").innerHTML = "E-mail: " + resp.email;
        }
    });

    $.ajax({
        url:"/xiEzMyEY6LAhMzQhYS0=",
        success:function(resp){
            if(resp.type){
                document.getElementById("login").style.display = "none";
                document.getElementById("logout").style.visibility = "visible";
            }
        }
    });

    document.getElementById("logout").addEventListener("click", function(){
        $.ajax({
            url:"/logout",
            type:"post",
            success:function(resp){
                location.reload();
                }
            })
    });

    document.getElementById("cart").addEventListener("click", function(){
        location.href = "/cart"
    });

    $(function(){
        $("#accView").click(function() {
            document.getElementById("accBox").style.display = "inline";
            document.getElementById("passBox").style.display = "none";
        });
    });

    $(function(){
        $("#passChange").click(function() {
            document.getElementById("passBox").style.display = "inline";
            document.getElementById("accBox").style.display = "none";
        });
    });

    $(function(){
        $("#confirmBut").click(function() {
            var newPass = document.getElementById("newPass").value;
            var confirmPass = document.getElementById("confirmPass").value;
            if (newPass == confirmPass){
                document.getElementById("newPass").value = "";
                document.getElementById("confirmPass").value = "";
                $.ajax({
                    url:"/changeMyPass",
                    data:{
                        confirmPass:confirmPass
                    },
                    type:"post", //"post" is behind the scenes (invisible) versus "get" (hijackable)
                    success:function(resp){
                        if(resp.status == "success"){
                            console.log("successful");
                            alert("Password successfully changed!");
                        } else if(resp.status == "fail"){
                            alert(resp.msg);
                        }
                    }
                });
            } else {
                alert("Please check that the passwords are the same");
            }
        });
    });
});
<|endoftext|>


<commit_before>(function(exports){
  $(document).ready(function(){
    $('.modal-trigger').leanModal();
  });

  const fakeDataMode = false;
  const CHART_FORMAT = 'LLL';
  const CONTRIBUTOR_MARKUP ='

${name}

';

  var projectId = $.url().param('id');
  var latestSensors;

  var gMap;
  var markerMap = new Map();

  var ctx = $("#sensor-data-chart").get(0).getContext("2d");

  var dataChartContainer = document.getElementById("sensor-data-chart-container");
  var dataChart;
  var chartName = $('#sensor-information .name');
  var chartDescription = $('#sensor-information .description');
  var chartValue = $('#sensor-information .value');
  var chartLatestUpdate = $('#sensor-information .latest-update');
  var chartCloseBtn = $('#chart-close-btn');

  chartCloseBtn.click(function () {
    dataChartContainer.classList.add('hide');
    dataChart && dataChart.destroy();
  });

  $(window).load(function handleClientLoad() {
    var auth = gapi.auth2.getAuthInstance();

    if (!auth) {
      return;
    }

    var loginBtn = $('#login-btn');
    var accountBtn = $('#account-btn');

    function btnState(isSignedIn) {
      if (isSignedIn) {
        var email = auth.currentUser.get().getBasicProfile().getEmail();
        $.ajax({
          url: API_URL + 'users?email=' + email,
          dataType: 'jsonp'
        })
        .done(function(result) {
          loginBtn.addClass('hide');
          accountBtn.removeClass('hide');
          accountBtn.attr('href', 'user-detail.html?userId=' + result.id);
        })
        .fail(function(err) {
          console.error(err)
        });
      } else {
        accountBtn.addClass('hide');
        loginBtn.removeClass('hide');
      }
    }

    btnState(auth.isSignedIn.get() || auth.currentUser.get().isSignedIn());
    auth.isSignedIn.listen(btnState);
  });

  function onSignIn(googleUser) {
    var userId = $('#user-id').val();

    if (!userId) {
      return;
    }

    var auth = googleUser.getAuthResponse();
    var profile = googleUser.getBasicProfile();
    var userData = {
      // token: auth.access_token, Do we really need this?
      id: userId,
      name: profile.getName(),
      email: profile.getEmail(),
      picture: profile.getImageUrl()
    };
    //TODO: create user in DB and get user profile

    $('#user-id').text();
    $('#google-sign-in-modal').closeModal();

    $.ajax({
      type: 'POST',
      url: API_URL + 'users',
      data: userData,
      dataType: 'jsonp'
    })
    .done(function() {
      window.location = 'user-detail.html?userId=' + userId;
    })
    .fail(function(err) {
      console.error(err)
    });
  }

  function dataConvertion(dataArray) {
    var config = {
      type: 'line',
      data: {
        datasets: [{
          label: "PM2.5 value",
    			 pointBorderWidth: .2,
          fill: false,
          data: dataArray.map(function(d) {
            return { x: moment(d.datetime).format(CHART_FORMAT), y: d.pm25Index };
          })
        }]
      },
      options: {
        responsive: true,
        scales: {
          xAxes: [{
            type: "time",
            display: true,
            scaleLabel: {
              display: true,
              // labelString: 'Time'
            }
          }, ],
          yAxes: [{
            display: true,
            scaleLabel: {
              display: true,
              labelString: 'PM2.5 index(μg/m)'
            }
          }]
        }
      }
    };
    return config;
  }

  function updateMap(sensors) {
    if (!gMap || !sensors) {
      return;
    }

    sensors.forEach(function(sensor, index) {
      if (markerMap.has(sensor._id)) {
        return;
      }

      var coords = sensor.coords;
      var gMapMarker = new google.maps.Marker({
        position: { lat: Number(coords.lat), lng: Number(coords.lng) },
        map: gMap,
        title: sensor.name,
        zIndex: index + 1
      });

      gMapMarker.addListener('click', function() {
        chartName.html('' + sensor.name + '');
        chartDescription.text(sensor.description);
        chartValue.text(sensor.pm25Index);
        chartLatestUpdate.text(moment(sensor.latestUpdate).fromNow());
        dataChartContainer.classList.remove('hide');

        if (fakeDataMode) {
          var fakeArray = [];
          for (var i=100; i>0; i--) {
            fakeArray.push({
              datetime: Date.now() - i * 60000,
              pm25Index: Math.random() * 100
            })
          }
          dataChart = new Chart(ctx, dataConvertion(fakeArray));
          // $('#sensor-information').height($('#sensor-chart').height());
          return;
        }

        $.ajax({
          url: API_URL + 'sensors/' + sensor._id + '/data',
          dataType: 'jsonp'
        })
        .done(function(dataArray) {
          dataChart = new Chart(ctx, dataConvertion(dataArray));
        })
        .fail(function(error) {
          console.error(error);
        });
      });

      markerMap.set(sensor._id, gMapMarker);
    });
  }

  function renderContributorList(contributors) {
    $.tmpl(CONTRIBUTOR_MARKUP, contributors).appendTo("#contributor-list");
  }

  function initMap() {
    // mapAPIReady = true;
    //
    // if (!latestSensorData) {
    //   return;
    // }
    // TODO: var location = latestSensorData.location;
    var location = {lat: 25.032506, lng: 121.5674536};

    gMap = new google.maps.Map(document.getElementById('sensors-location-map'), {
      zoom: 14,
      center: location,
      scrollwheel: false
    });

    if (fakeDataMode) {
      latestSensors = [
        {
          id: 1,
          name: 'Test 1',
          description: 'Test 1\'s data',
          location: {lat: 25.032506, lng: 121.5674536},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        },
        {
          id: 2,
          name: 'Test 2',
          description: 'Test 2\'s data',
          location: {lat: 25.0, lng: 121.6674536},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        },
        {
          id: 3,
          name: 'Test 3',
          description: 'Test 3\'s data',
          location: {lat: 25.05, lng: 121.5},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        }
      ];
    }

    updateMap(latestSensors);
  }

  // Fetch project detail, should set project ID as parameter
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25',
    dataType: 'jsonp'
  })
  .done(function(project) {
    $('#pm25 .description').text(project.description);
    $('#pm25 .creator').text(project.creator.name);
    // $('#pm25 .last-update').text(project.detail);
    $('#pm25 .created-date').text(moment(project.createDate).format('LL'));
  })
  .fail(function(error) {
    console.error(error);
  });

  // Fetch sensor list
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25/sensors',
    dataType: 'jsonp'
  })
  .done(function(sensors) {
    latestSensors = sensors;
    updateMap(latestSensors);
  })
  .fail(function(error) {
    console.error(error);
  });

  // Fetch user list, should set project ID as parameter
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25/contributors',
    dataType: 'jsonp'
  })
  .done(function(contributors) {
    $('#pm25 .contributors').text(contributors.length);
    renderContributorList(contributors);
  })
  .fail(function(error) {
    console.error(error);
  });

  exports.initMap = initMap;
  exports.onSignIn = onSignIn;

})(window);
<commit_msg>Fix bugs<commit_after>(function(exports){
  $(document).ready(function(){
    $('.modal-trigger').leanModal();
  });

  const fakeDataMode = false;
  const CHART_FORMAT = 'LLL';
  const CONTRIBUTOR_MARKUP ='

${name}

';

  var projectId = $.url().param('id');
  var latestSensors;

  var gMap;
  var markerMap = new Map();

  var ctx = $("#sensor-data-chart").get(0).getContext("2d");

  var dataChartContainer = document.getElementById("sensor-data-chart-container");
  var dataChart;
  var chartName = $('#sensor-information .name');
  var chartDescription = $('#sensor-information .description');
  var chartValue = $('#sensor-information .value');
  var chartLatestUpdate = $('#sensor-information .latest-update');
  var chartCloseBtn = $('#chart-close-btn');

  chartCloseBtn.click(function () {
    dataChartContainer.classList.add('hide');
    dataChart && dataChart.destroy();
  });

  $(window).load(function handleClientLoad() {
    var auth = gapi.auth2.getAuthInstance();

    if (!auth) {
      return;
    }

    var loginBtn = $('#login-btn');
    var accountBtn = $('#account-btn');

    function btnState(isSignedIn) {
      if (isSignedIn) {
        var email = auth.currentUser.get().getBasicProfile().getEmail();
        $.ajax({
          url: API_URL + 'users?email=' + email,
          dataType: 'jsonp'
        })
        .done(function(result) {
          loginBtn.addClass('hide');
          accountBtn.removeClass('hide');
          accountBtn.attr('href', 'user-detail.html?userId=' + result.id);
        })
        .fail(function(err) {
          console.error(err)
        });
      } else {
        accountBtn.addClass('hide');
        loginBtn.removeClass('hide');
      }
    }

    btnState(auth.isSignedIn.get() || auth.currentUser.get().isSignedIn());
    auth.isSignedIn.listen(btnState);
  });

  function onSignIn(googleUser) {
    var userId = $('#user-id').val();

    if (!userId) {
      return;
    }

    var auth = googleUser.getAuthResponse();
    var profile = googleUser.getBasicProfile();
    var userData = {
      // token: auth.access_token, Do we really need this?
      id: userId,
      name: profile.getName(),
      email: profile.getEmail(),
      picture: profile.getImageUrl()
    };
    //TODO: create user in DB and get user profile

    $('#user-id').text();
    $('#google-sign-in-modal').closeModal();

    $.ajax({
      type: 'POST',
      url: API_URL + 'users',
      data: userData,
      dataType: 'jsonp'
    })
    .done(function() {
      window.location = 'user-detail.html?userId=' + userId;
    })
    .fail(function(err) {
      console.error(err)
    });
  }

  function dataConvertion(dataArray) {
    var config = {
      type: 'line',
      data: {
        datasets: [{
          label: "PM2.5 value",
    			 pointBorderWidth: .2,
          fill: false,
          data: dataArray.map(function(d) {
            return { x: moment(d.datetime).format(CHART_FORMAT), y: d.pm25Index };
          })
        }]
      },
      options: {
        responsive: true,
        scales: {
          xAxes: [{
            type: "time",
            display: true,
            scaleLabel: {
              display: true,
              // labelString: 'Time'
            }
          }, ],
          yAxes: [{
            display: true,
            scaleLabel: {
              display: true,
              labelString: 'PM2.5 index(μg/m)'
            }
          }]
        }
      }
    };
    return config;
  }

  function updateMap(sensors) {
    if (!gMap || !sensors) {
      return;
    }

    sensors.forEach(function(sensor, index) {
      if (markerMap.has(sensor._id)) {
        return;
      }

      var coords = sensor.coords;
      var gMapMarker = new google.maps.Marker({
        position: { lat: Number(coords.lat), lng: Number(coords.lng) },
        map: gMap,
        title: sensor.name,
        zIndex: index + 1
      });

      gMapMarker.addListener('click', function() {
        chartName.html('' + sensor.name + '');
        chartDescription.text(sensor.description);
        chartValue.text(sensor.pm25Index);
        chartLatestUpdate.text(moment(sensor.latestUpdate).fromNow());
        dataChartContainer.classList.remove('hide');

        if (fakeDataMode) {
          var fakeArray = [];
          for (var i=100; i>0; i--) {
            fakeArray.push({
              datetime: Date.now() - i * 60000,
              pm25Index: Math.random() * 100
            })
          }
          dataChart = new Chart(ctx, dataConvertion(fakeArray));
          // $('#sensor-information').height($('#sensor-chart').height());
          return;
        }

        $.ajax({
          url: API_URL + 'sensors/' + sensor._id + '/data',
          dataType: 'jsonp'
        })
        .done(function(dataArray) {
          dataChart = new Chart(ctx, dataConvertion(dataArray));
        })
        .fail(function(error) {
          console.error(error);
        });
      });

      markerMap.set(sensor._id, gMapMarker);
    });
  }

  function renderContributorList(contributors) {
    $.tmpl(CONTRIBUTOR_MARKUP, contributors).appendTo("#contributor-list");
  }

  function initMap() {
    // mapAPIReady = true;
    //
    // if (!latestSensorData) {
    //   return;
    // }
    // TODO: var location = latestSensorData.location;
    var location = {lat: 25.032506, lng: 121.5674536};

    gMap = new google.maps.Map(document.getElementById('sensors-location-map'), {
      zoom: 14,
      center: location,
      scrollwheel: false
    });

    if (fakeDataMode) {
      latestSensors = [
        {
          id: 1,
          name: 'Test 1',
          description: 'Test 1\'s data',
          location: {lat: 25.032506, lng: 121.5674536},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        },
        {
          id: 2,
          name: 'Test 2',
          description: 'Test 2\'s data',
          location: {lat: 25.0, lng: 121.6674536},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        },
        {
          id: 3,
          name: 'Test 3',
          description: 'Test 3\'s data',
          location: {lat: 25.05, lng: 121.5},
          pm25Index: Math.random()*100,
          latestUpdate: Date.now()
        }
      ];
    }

    updateMap(latestSensors);
  }

  // Fetch project detail, should set project ID as parameter
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25',
    dataType: 'jsonp'
  })
  .done(function(project) {
    $('#pm25 .description').text(project.description);
    $('#pm25 .creator').text(project.creator.name);
    // $('#pm25 .last-update').text(project.detail);
    $('#pm25 .created-date').text(moment(project.createDate).format('LL'));
  })
  .fail(function(error) {
    console.error(error);
  });

  // Fetch sensor list
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25/sensors',
    dataType: 'jsonp'
  })
  .done(function(sensors) {
    latestSensors = sensors;
    updateMap(latestSensors);
  })
  .fail(function(error) {
    console.error(error);
  });

  // Fetch user list, should set project ID as parameter
  $.ajax({
    url: API_URL + 'projects/sensorweb/pm25/contributors',
    dataType: 'jsonp'
  })
  .done(function(contributors) {
    $('#pm25 .contributors').text(contributors.length);
    renderContributorList(contributors);
  })
  .fail(function(error) {
    console.error(error);
  });

  exports.initMap = initMap;
  exports.onSignIn = onSignIn;

})(window);
<|endoftext|>


<commit_before>function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    buffer.save();

    buffer.translate(
      x,
      y
    );

    for(var vertex in vertices){
        buffer.fillStyle = vertices[vertex]['color'];
        buffer.fillRect(
          vertices[vertex]['x'],
          vertices[vertex]['y'],
          10,
          10
        );
    }

    buffer.restore();

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['rotation'] += rotation_rate * (25 - vertices[vertex]['layer']);
        if(vertices[vertex]['rotation'] >= tau){
            vertices[vertex]['rotation'] -= tau;
        }else if(vertices[vertex]['rotation'] < 0){
            vertices[vertex]['rotation'] += tau;
        }

        vertices[vertex]['x'] = vertices[vertex]['layer'] * 10 * Math.cos(vertices[vertex]['rotation']) - 5;
        vertices[vertex]['y'] = vertices[vertex]['layer'] * 10 * Math.sin(vertices[vertex]['rotation']) - 5;
    }
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var height = 0;
var rotation_rate = .005;
var tau = Math.PI * 2;
var vertices = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: rotation_rate += 0.001;
    if(key == 187){
        rotation_rate += 0.001;

    // -: rotation_rate -= 0.001;
    }else if(key == 189){
        rotation_rate -= 0.001;

    // ESC: rotation_rate = 0;
    }else if(key == 27){
        rotation_rate = 0;
    }
};

window.onload = function(e){
    resize();

    var loop_counter = 23;
    do{
        var inner_counter = loop_counter;
        do{
            vertices.push({
              'color': '#fff',
              'layer': loop_counter + 1,
              'rotation': inner_counter,
              'x': 0,
              'y': 0,
            });
        }while(inner_counter--);
    }while(loop_counter--);

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onresize = resize;
<commit_msg>added use strict<commit_after>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    buffer.save();

    buffer.translate(
      x,
      y
    );

    for(var vertex in vertices){
        buffer.fillStyle = vertices[vertex]['color'];
        buffer.fillRect(
          vertices[vertex]['x'],
          vertices[vertex]['y'],
          10,
          10
        );
    }

    buffer.restore();

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    window.requestAnimationFrame(draw);
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['rotation'] += rotation_rate * (25 - vertices[vertex]['layer']);
        if(vertices[vertex]['rotation'] >= tau){
            vertices[vertex]['rotation'] -= tau;
        }else if(vertices[vertex]['rotation'] < 0){
            vertices[vertex]['rotation'] += tau;
        }

        vertices[vertex]['x'] = vertices[vertex]['layer'] * 10 * Math.cos(vertices[vertex]['rotation']) - 5;
        vertices[vertex]['y'] = vertices[vertex]['layer'] * 10 * Math.sin(vertices[vertex]['rotation']) - 5;
    }
}

function resize(){
    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
}

var buffer = document.getElementById('buffer').getContext('2d');
var canvas = document.getElementById('canvas').getContext('2d');
var height = 0;
var rotation_rate = .005;
var tau = Math.PI * 2;
var vertices = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // +: rotation_rate += 0.001;
    if(key == 187){
        rotation_rate += 0.001;

    // -: rotation_rate -= 0.001;
    }else if(key == 189){
        rotation_rate -= 0.001;

    // ESC: rotation_rate = 0;
    }else if(key == 27){
        rotation_rate = 0;
    }
};

window.onload = function(e){
    resize();

    var loop_counter = 23;
    do{
        var inner_counter = loop_counter;
        do{
            vertices.push({
              'color': '#fff',
              'layer': loop_counter + 1,
              'rotation': inner_counter,
              'x': 0,
              'y': 0,
            });
        }while(inner_counter--);
    }while(loop_counter--);

    window.requestAnimationFrame(draw);
    window.setInterval(
      'logic()',
      30
    );
};

window.onresize = resize;
<|endoftext|>


<commit_before>/*************
 *  Toolbox  *
 *************/

var current_tool;

var button_color_inactive = new HsbColor(250, 0.6, 0.45);
var button_color_active = new HsbColor(120, 0.6, 0.45);

var button_size = new Size(150, 40);
var button_corners = new Size(5, 5);
var button_text_offset = new Point(10, 25);
var button_hotkey_offset = new Point(button_size.width - 30, 25);

function make_button(label, hotkey, x, y) {
	var rectangle = new Rectangle(new Point(x, y), button_size);

	var button = new Path.RoundRectangle(rectangle, button_corners);
	button.fillColor = button_color_inactive;

	var label_text = new PointText(rectangle.point + button_text_offset);
	label_text.content = label;
	label_text.characterStyle.fillColor = 'white';

	var hotkey_text = new PointText(rectangle.point + button_hotkey_offset);
	hotkey_text.content = '[' + hotkey + ']';
	hotkey_text.characterStyle.fillColor = 'white';

	return new Group([button, label_text, hotkey_text]);
}

var toolbox_buttons = {};
var toolbox_button_ypos = 10;

function add_toolbox_button(name, label, hotkey) {
	toolbox_buttons[name] = make_button(label, hotkey, 10, toolbox_button_ypos);

	toolbox_button_ypos += button_size.height + 5;
}

add_toolbox_button('add_vertex', 'Add vertex', 'V');
add_toolbox_button('move_vertex', 'Move vertex', 'M');
add_toolbox_button('remove_vertex', 'Remove vertex', 'R');
add_toolbox_button('add_edge', 'Add edge', 'E');
add_toolbox_button('delete_edge', 'Delete edge', 'D');

function set_button_color(button, color) {
	button.firstChild.fillColor = color;
}

function set_active_tool(name) {
	if (current_tool) {
		set_button_color(toolbox_buttons[current_tool], button_color_inactive);
	}

	current_tool = name;
	set_button_color(toolbox_buttons[current_tool], button_color_active);
}

set_active_tool('add_vertex');

/***********
 *  Graph  *
 ***********/

// Array of Group objects corresponding to the vertices.
var vertices = [];

// Object of Path objects. The keys are of the form 'eA:B' where A and B are
// indices into the vertices array, and A < B. The first point of the path is
// always at A, and the last is always at B.
var edges = {};

function make_edge_name(vertex1, vertex2) {
	return 'e' + Math.min(vertex1, vertex2) + ':' + Math.max(vertex1, vertex2);
}

function parse_edge_name(name) {
	var colon = name.indexOf(':');

	return [parseInt(name.substring(1, colon), 10), parseInt(name.substring(colon+1), 10)];
}

function vertex_circle(vertex) {
	return vertices[vertex].children[0];
}

function vertex_label(vertex) {
	return vertices[vertex].children[1];
}

function add_vertex(coords) {
	var circle = new Path.Circle(0, 20);
	circle.fillColor = new HsbColor(Math.random() * 360, 0.7, 0.5);

	var label_text = new PointText(circle.position);
	label_text.content = vertices.length;
	label_text.characterStyle.fillColor = 'white';

	var group = new Group([circle, label_text]);
	group.position = coords;

	vertices.push(group);
}

function move_vertex(vertex, point) {
	// Move the vertex itself.
	vertices[vertex].position = point;

	// Move all the edges incident to the vertex.
	for (var i in edges) {
		var edge_vertices = parse_edge_name(i);

		if (edge_vertices[0] == vertex) {
			edges[i].removeSegment(0);
			edges[i].insert(0, point);
		} else if (edge_vertices[1] == vertex) {
			last_segment = edges[i].segments.length - 1;

			edges[i].removeSegment(last_segment);
			edges[i].insert(last_segment, point);
		}
	}
}

function remove_vertex(vertex) {
	// Get rid of the vertex by shuffling all the vertices that have greater
	// indices.
	vertices[vertex].remove();
	vertices.splice(vertex, 1);

	// Update all the labels on the later vertices.
	for (var i = vertex; i < vertices.length; i++) {
		vertex_label(i).content = i;
	}

	// Keep track of all the edges that will need to be re-created with new
	// end-points.
	var temp_edges = [];

	for (var i in edges) {
		var edge_vertices = parse_edge_name(i);

		if (edge_vertices[0] == vertex || edge_vertices[1] == vertex) {
			// This edge doesn't exist anymore, so just remove it.
			delete_edge(edge_vertices[0], edge_vertices[1]);
		} else if (edge_vertices[0] > vertex || edge_vertices[1] > vertex) {
			// This edge still exists, but at least one of the vertices has had
			// its index decremented.
			var v1 = edge_vertices[0] - (edge_vertices[0] > vertex ? 1 : 0);
			var v2 = edge_vertices[1] - (edge_vertices[1] > vertex ? 1 : 0);

			temp_edges.push([v1, v2]);

			delete_edge(edge_vertices[0], edge_vertices[1]);
		}
	}

	// Re-create the necessary edges.
	for (var i = 0; i < temp_edges.length; i++) {
		add_edge(temp_edges[i][0], temp_edges[i][1]);
	}
}

// Get the vertex sitting at the given position, if there is one.
function vertex_at_posn(point) {
	for (var i = 0; i < vertices.length; i++) {
		if (vertices[i].hitTest(point)) {
			return i;
		}
	}

	return false;
}

function add_edge(start, end) {
	var name = make_edge_name(start, end);

	// Not if it already exists or if it connects a vertex with itself.
	if (edges[name] || start == end) {
		return;
	}

	// Make sure the path is always in the same direction as the edge name.
	if (start > end) {
		temp = start;
		start = end;
		end = temp;
	}

	var path = new Path();
	path.strokeColor = 'grey';

	path.add(vertex_circle(start).position);
	path.add(vertex_circle(end).position);

	edges[name] = path;
}

function delete_edge(start, end) {
	var name = make_edge_name(start, end);

	// Not if it doesn't exist.
	if (!edges[name]) {
		return;
	}

	edges[name].remove();
	delete edges[name];
}

/*****************
 *  Interaction  *
 *****************/

// Don't draw too many points.
tool.minDistance = 20;

// Callbacks configured on the initial mouse press.
var dragFunction;
var releaseFunction;

// Start an edge action at a vertices, draw a path following the mouse, and
// call the completion callback end_function when the mouse is released.
function start_edge_action(start_vertex, color, end_function) {
	var path = new Path();
	path.strokeColor = color;
	path.add(vertex_circle(start_vertex).position);

	dragFunction = function(point) {
		path.add(point);
		path.smooth();
	}

	releaseFunction = function(point) {
		path.remove();

		var end_vertex = vertex_at_posn(point);

		if (end_vertex !== false) {
			end_function(start_vertex, end_vertex);
		}

		dragFunction = false;
		releaseFunction = false;
	}
}

function onKeyDown(event) {
	switch (event.key) {
		// Toggle tools using hotkeys.
		case 'v':
		set_active_tool('add_vertex');
		break;

		case 'm':
		set_active_tool('move_vertex');
		break;

		case 'r':
		set_active_tool('remove_vertex');
		break;

		case 'e':
		set_active_tool('add_edge');
		break;

		case 'd':
		set_active_tool('delete_edge');
		break;
	}
}

function onMouseDown(event) {
	// Toolbox buttons always take precedence.
	for (var i in toolbox_buttons) {
		if (toolbox_buttons[i].hitTest(event.point)) {
			set_active_tool(i);

			return;
		}
	}

	// Clicked elsewhere, so make use of the current tool.
	switch (current_tool) {
		case 'add_vertex':
		add_vertex(event.point);
		break;

		case 'move_vertex':
		var vertex = vertex_at_posn(event.point);

		if (vertex === false) {
			break;
		}

		dragFunction = function(point) {
			move_vertex(vertex, point);
		}

		releaseFunction = function(point) {
			dragFunction = false;
			releaseFunction = false;
		}
		break;

		case 'remove_vertex':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			remove_vertex(vertex);
		}
		break;

		case 'add_edge':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			start_edge_action(vertex, '#00ff00', add_edge);
		}
		break;

		case 'delete_edge':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			start_edge_action(vertex, '#ff0000', delete_edge);
		}
		break;
	}
}

function onMouseDrag(event) {
	if (dragFunction) {
		dragFunction(event.point);
	}
}

function onMouseUp(event) {
	if (releaseFunction) {
		releaseFunction(event.point);
	}
}
<commit_msg>Add tool help and automatic hotkeys<commit_after>/*************
 *  Toolbox  *
 *************/

var current_tool;

var button_color_inactive = new HsbColor(250, 0.6, 0.45);
var button_color_active = new HsbColor(120, 0.6, 0.45);

var button_size = new Size(150, 40);
var button_corners = new Size(5, 5);
var button_text_offset = new Point(10, 25);
var button_hotkey_offset = new Point(button_size.width - 30, 25);

var toolbox_buttons = {};
var toolbox_button_posn = new Point(10, 10);

var tool_help = {};
var tool_hotkey_actions = {};

var tool_help_text = new PointText(toolbox_button_posn + new Point(button_size.width + 10, 15));
tool_help_text.characterStyle.fillColor = 'white';

function make_button(label, hotkey, posn) {
	var rectangle = new Rectangle(posn, button_size);

	var button = new Path.RoundRectangle(rectangle, button_corners);
	button.fillColor = button_color_inactive;

	var label_text = new PointText(rectangle.point + button_text_offset);
	label_text.content = label;
	label_text.characterStyle.fillColor = 'white';

	var hotkey_text = new PointText(rectangle.point + button_hotkey_offset);
	hotkey_text.content = '[' + hotkey.toUpperCase() + ']';
	hotkey_text.characterStyle.fillColor = 'white';

	return new Group([button, label_text, hotkey_text]);
}

function add_toolbox_button(name, label, hotkey, help_text) {
	toolbox_buttons[name] = make_button(label, hotkey, toolbox_button_posn);
	tool_hotkey_actions[hotkey] = name;
	tool_help[name] = help_text;

	toolbox_button_posn.y += button_size.height + 5;
}

add_toolbox_button('add_vertex', 'Add vertex', 'v', 'Click.');
add_toolbox_button('move_vertex', 'Move vertex', 'm', 'Drag a vertex.');
add_toolbox_button('remove_vertex', 'Remove vertex', 'r', 'Click.');
add_toolbox_button('add_edge', 'Add edge', 'e', 'Drag from vertex to vertex.');
add_toolbox_button('delete_edge', 'Delete edge', 'd', 'Drag from vertex to vertex.');

function set_button_color(button, color) {
	button.firstChild.fillColor = color;
}

function draw_help_text(text) {
	tool_help_text.content = text;
}

function set_active_tool(name) {
	if (current_tool) {
		set_button_color(toolbox_buttons[current_tool], button_color_inactive);
	}

	current_tool = name;
	set_button_color(toolbox_buttons[current_tool], button_color_active);

	if (tool_help[name]) {
		draw_help_text(tool_help[name]);
	} else {
		draw_help_text('');
	}
}

set_active_tool('add_vertex');

/***********
 *  Graph  *
 ***********/

// Array of Group objects corresponding to the vertices.
var vertices = [];

// Object of Path objects. The keys are of the form 'eA:B' where A and B are
// indices into the vertices array, and A < B. The first point of the path is
// always at A, and the last is always at B.
var edges = {};

function make_edge_name(vertex1, vertex2) {
	return 'e' + Math.min(vertex1, vertex2) + ':' + Math.max(vertex1, vertex2);
}

function parse_edge_name(name) {
	var colon = name.indexOf(':');

	return [parseInt(name.substring(1, colon), 10), parseInt(name.substring(colon+1), 10)];
}

function vertex_circle(vertex) {
	return vertices[vertex].children[0];
}

function vertex_label(vertex) {
	return vertices[vertex].children[1];
}

function add_vertex(coords) {
	var circle = new Path.Circle(0, 20);
	circle.fillColor = new HsbColor(Math.random() * 360, 0.7, 0.5);

	var label_text = new PointText(circle.position);
	label_text.content = vertices.length;
	label_text.characterStyle.fillColor = 'white';

	var group = new Group([circle, label_text]);
	group.position = coords;

	vertices.push(group);
}

function move_vertex(vertex, point) {
	// Move the vertex itself.
	vertices[vertex].position = point;

	// Move all the edges incident to the vertex.
	for (var i in edges) {
		var edge_vertices = parse_edge_name(i);

		if (edge_vertices[0] == vertex) {
			edges[i].removeSegment(0);
			edges[i].insert(0, point);
		} else if (edge_vertices[1] == vertex) {
			last_segment = edges[i].segments.length - 1;

			edges[i].removeSegment(last_segment);
			edges[i].insert(last_segment, point);
		}
	}
}

function remove_vertex(vertex) {
	// Get rid of the vertex by shuffling all the vertices that have greater
	// indices.
	vertices[vertex].remove();
	vertices.splice(vertex, 1);

	// Update all the labels on the later vertices.
	for (var i = vertex; i < vertices.length; i++) {
		vertex_label(i).content = i;
	}

	// Keep track of all the edges that will need to be re-created with new
	// end-points.
	var temp_edges = [];

	for (var i in edges) {
		var edge_vertices = parse_edge_name(i);

		if (edge_vertices[0] == vertex || edge_vertices[1] == vertex) {
			// This edge doesn't exist anymore, so just remove it.
			delete_edge(edge_vertices[0], edge_vertices[1]);
		} else if (edge_vertices[0] > vertex || edge_vertices[1] > vertex) {
			// This edge still exists, but at least one of the vertices has had
			// its index decremented.
			var v1 = edge_vertices[0] - (edge_vertices[0] > vertex ? 1 : 0);
			var v2 = edge_vertices[1] - (edge_vertices[1] > vertex ? 1 : 0);

			temp_edges.push([v1, v2]);

			delete_edge(edge_vertices[0], edge_vertices[1]);
		}
	}

	// Re-create the necessary edges.
	for (var i = 0; i < temp_edges.length; i++) {
		add_edge(temp_edges[i][0], temp_edges[i][1]);
	}
}

// Get the vertex sitting at the given position, if there is one.
function vertex_at_posn(point) {
	for (var i = 0; i < vertices.length; i++) {
		if (vertices[i].hitTest(point)) {
			return i;
		}
	}

	return false;
}

function add_edge(start, end) {
	var name = make_edge_name(start, end);

	// Not if it already exists or if it connects a vertex with itself.
	if (edges[name] || start == end) {
		return;
	}

	// Make sure the path is always in the same direction as the edge name.
	if (start > end) {
		temp = start;
		start = end;
		end = temp;
	}

	var path = new Path();
	path.strokeColor = 'grey';

	path.add(vertex_circle(start).position);
	path.add(vertex_circle(end).position);

	edges[name] = path;
}

function delete_edge(start, end) {
	var name = make_edge_name(start, end);

	// Not if it doesn't exist.
	if (!edges[name]) {
		return;
	}

	edges[name].remove();
	delete edges[name];
}

/*****************
 *  Interaction  *
 *****************/

// Don't draw too many points.
tool.minDistance = 20;

// Callbacks configured on the initial mouse press.
var dragFunction;
var releaseFunction;

// Start an edge action at a vertices, draw a path following the mouse, and
// call the completion callback end_function when the mouse is released.
function start_edge_action(start_vertex, color, end_function) {
	var path = new Path();
	path.strokeColor = color;
	path.add(vertex_circle(start_vertex).position);

	dragFunction = function(point) {
		path.add(point);
		path.smooth();
	}

	releaseFunction = function(point) {
		path.remove();

		var end_vertex = vertex_at_posn(point);

		if (end_vertex !== false) {
			end_function(start_vertex, end_vertex);
		}

		dragFunction = false;
		releaseFunction = false;
	}
}

function onKeyDown(event) {
	if (event.key in tool_hotkey_actions) {
		set_active_tool(tool_hotkey_actions[event.key]);

		return;
	}
}

function onMouseDown(event) {
	// Toolbox buttons always take precedence.
	for (var i in toolbox_buttons) {
		if (toolbox_buttons[i].hitTest(event.point)) {
			set_active_tool(i);

			return;
		}
	}

	// Clicked elsewhere, so make use of the current tool.
	switch (current_tool) {
		case 'add_vertex':
		add_vertex(event.point);
		break;

		case 'move_vertex':
		var vertex = vertex_at_posn(event.point);

		if (vertex === false) {
			break;
		}

		dragFunction = function(point) {
			move_vertex(vertex, point);
		}

		releaseFunction = function(point) {
			dragFunction = false;
			releaseFunction = false;
		}
		break;

		case 'remove_vertex':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			remove_vertex(vertex);
		}
		break;

		case 'add_edge':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			start_edge_action(vertex, '#00ff00', add_edge);
		}
		break;

		case 'delete_edge':
		var vertex = vertex_at_posn(event.point);

		if (vertex !== false) {
			start_edge_action(vertex, '#ff0000', delete_edge);
		}
		break;
	}
}

function onMouseDrag(event) {
	if (dragFunction) {
		dragFunction(event.point);
	}
}

function onMouseUp(event) {
	if (releaseFunction) {
		releaseFunction(event.point);
	}
}
<|endoftext|>


<commit_before><commit_msg>test fist commit<commit_after>//business logic//

//front-end logic//
document.ready(function(event())
event
<|endoftext|>


<commit_before>$( document ).ready( function() {

    /**************************************************
    detect os to show correct download links
    **************************************************/

    var desktop = true;
    var uAgent = navigator.userAgent || navigator.vendor || window.opera;
    var osName = "unknown";
    var downloadLink = "<site_url_placeholder>/downloads";

    if( uAgent.indexOf( "Win" ) > -1 ) {
        osName = "win64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.exe";
    } else if( uAgent.indexOf( "Mac" ) > -1 ) {
        osName = "mac";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-<bisq_version_placeholder>.dmg";
    } else if( uAgent.indexOf( "Linux" ) > -1 && ( uAgent.indexOf( "Ubuntu" ) > -1 || uAgent.indexOf( "Debian" ) > -1 ) ) {
        osName = "deb64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.deb";
    } else if( uAgent.indexOf( "Linux" ) > -1 && ( uAgent.indexOf( "Fedora" ) > -1 || uAgent.indexOf( "Red Hat" ) > -1 ) ) {
        osName = "rpm64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.rpm";
    }

    //mobile
    if( /android/i.test( uAgent ) ) {
        desktop = false;
        $( '.downloads-android' ).removeClass( 'hidden' ).addClass( 'shown' );
        $( '.id-all').removeClass( 'hidden' ).addClass( 'shown' );
    }
    if( /iPad|iPhone|iPod/.test( uAgent ) && !window.MSStream ) {
        desktop = false;
        $( '.downloads-ios' ).removeClass('hidden').addClass( 'shown' );
        $( '.id-all' ).removeClass( 'hidden' ).addClass( 'shown' );
    }

    //desktop
    if( desktop ) {
        if( osName !== 'unknown' ) {
            showOSDownloads( osName );
        } else {
            $( '.id-all').removeClass('hidden').addClass('shown');
        }
    }

    //capture click on currently-selected value in dropdown (otherwise
    //link click event doesn't register on firefox)
    $( 'button.selected-os-download' ).on( 'click', function(e) {
        if( ( e.target.className ).indexOf( 'dl-' ) > -1 ) {
            return;
        } else {
            serveDownload( $( e.currentTarget ).attr( 'data-bisq-version' ), $( e.currentTarget ).attr( 'data-site-url' ) );
        }
    });

    $( '.dl-win64, .dl-mac, .dl-deb64, .dl-rpm64' ).on( 'click', function() {
        sendAnalytic( $(this).attr('class').split('-').pop().split(" ").shift() );
    });

    //change dom to show downloads for the specific os
    function showOSDownloads( os ) {
        $( '.dl-' + os ).addClass( 'selected' );
        $( '.id-' + os ).removeClass( 'hidden' ).addClass( 'shown' );
        return;
    }

    //for non-link clicks (i.e., the 'download for xx' text on closed dropdown)
    function serveDownload( bisqVersion, siteURL ) {
        if( osName === 'unknown' ) {
            downloadLink = downloadLink.replace( /<site_url_placeholder>/g, siteURL );
        } else {
            downloadLink = downloadLink.replace( /<bisq_version_placeholder>/g, bisqVersion );
            sendAnalytic( osName );
        }
        location.href = downloadLink;
        return;
    }

    //add virtual pageview and event tracking for download attempts
    function sendAnalytic( platform ) {
        ga( 'send', 'pageview', location.pathname + 'release' );
        ga( 'send', 'event', 'Release Build', 'download', platform );
        return;
    }

  //Home Video
  $('#play-video').on('click', function(ev) {
    ev.preventDefault();
    //$("#video")[0].src += "&autoplay=1";
    $("#video-overlay").fadeIn('fast');
    $('body').addClass('no-scroll');

  });

  $(document).keyup(function(e) {
    if (e.keyCode === 27) $("#video-overlay").fadeOut('fast');
    $('body').removeClass('no-scroll');
  });

  //How to get started
  $('.step').on({
    mouseenter: function () {
      $('.step').css('opacity', 0.5),
      $(this).css('opacity', 1),
      $('.step-image').addClass('d-none').removeClass('d-block');
      $('.'+$(this).attr('data-image')).addClass('d-block').removeClass('d-none');
      console.log($(this).attr('data-image'));
    },
    mouseout: function () {}
  });

  //FAQ Accordion
  $('.accordion').each(function() {

     $(this).find('.accordion-toggle').click(function(event) {
       event.preventDefault();

       $(".accordion-toggle").not($(this)).removeClass('accordion-toggle-active');

       if($(this).hasClass('accordion-toggle-active')){
          $(this).removeClass('accordion-toggle-active');
       }else{
         $(this).addClass('accordion-toggle-active');
       }

       $(this).next().slideToggle('fast');
       $(".accordion-content").not($(this).next()).slideUp('fast');

       if($(this).attr('id') !== undefined){
         //add hash to url
         if(history.pushState) {
              history.pushState(null, null, '#' + $(this).attr('id'));
          } else {
              location.hash = '#' + $(this).attr('id');
          }
        }

     });

  });

  if(window.location.hash) {
    $("html, body").animate({ scrollTop: ($(window.location.hash).offset().top - 100) }, 1000);
    $(window.location.hash).addClass('accordion-toggle-active').next().slideToggle('fast');
  }

});
<commit_msg>Re-enable anchor linking & refactor javascript<commit_after>$( document ).ready( function() {

    /**************************************************
    detect os to show correct download links
    **************************************************/

    var desktop = true;
    var uAgent = navigator.userAgent || navigator.vendor || window.opera;
    var osName = "unknown";
    var downloadLink = "<site_url_placeholder>/downloads";

    if( uAgent.indexOf( "Win" ) > -1 ) {
        osName = "win64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.exe";
    } else if( uAgent.indexOf( "Mac" ) > -1 ) {
        osName = "mac";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-<bisq_version_placeholder>.dmg";
    } else if( uAgent.indexOf( "Linux" ) > -1 && ( uAgent.indexOf( "Ubuntu" ) > -1 || uAgent.indexOf( "Debian" ) > -1 ) ) {
        osName = "deb64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.deb";
    } else if( uAgent.indexOf( "Linux" ) > -1 && ( uAgent.indexOf( "Fedora" ) > -1 || uAgent.indexOf( "Red Hat" ) > -1 ) ) {
        osName = "rpm64";
        downloadLink = "https://bisq.network/downloads/v<bisq_version_placeholder>/Bisq-64bit-<bisq_version_placeholder>.rpm";
    }

    //mobile
    if( /android/i.test( uAgent ) ) {
        desktop = false;
        $( '.downloads-android' ).removeClass( 'hidden' ).addClass( 'shown' );
        $( '.id-all').removeClass( 'hidden' ).addClass( 'shown' );
    }
    if( /iPad|iPhone|iPod/.test( uAgent ) && !window.MSStream ) {
        desktop = false;
        $( '.downloads-ios' ).removeClass('hidden').addClass( 'shown' );
        $( '.id-all' ).removeClass( 'hidden' ).addClass( 'shown' );
    }

    //desktop
    if( desktop ) {
        if( osName !== 'unknown' ) {
            showOSDownloads( osName );
        } else {
            $( '.id-all').removeClass('hidden').addClass('shown');
        }
    }

    //capture click on currently-selected value in dropdown (otherwise
    //link click event doesn't register on firefox)
    $( 'button.selected-os-download' ).on( 'click', function(e) {
        if( ( e.target.className ).indexOf( 'dl-' ) > -1 ) {
            return;
        } else {
            serveDownload( $( e.currentTarget ).attr( 'data-bisq-version' ), $( e.currentTarget ).attr( 'data-site-url' ) );
        }
    });

    $( '.dl-win64, .dl-mac, .dl-deb64, .dl-rpm64' ).on( 'click', function() {
        sendAnalytic( $(this).attr('class').split('-').pop().split(" ").shift() );
    });

    //change dom to show downloads for the specific os
    function showOSDownloads( os ) {
        $( '.dl-' + os ).addClass( 'selected' );
        $( '.id-' + os ).removeClass( 'hidden' ).addClass( 'shown' );
        return;
    }

    //for non-link clicks (i.e., the 'download for xx' text on closed dropdown)
    function serveDownload( bisqVersion, siteURL ) {
        if( osName === 'unknown' ) {
            downloadLink = downloadLink.replace( /<site_url_placeholder>/g, siteURL );
        } else {
            downloadLink = downloadLink.replace( /<bisq_version_placeholder>/g, bisqVersion );
            sendAnalytic( osName );
        }
        location.href = downloadLink;
        return;
    }

    //add virtual pageview and event tracking for download attempts
    function sendAnalytic( platform ) {
        ga( 'send', 'pageview', location.pathname + 'release' );
        ga( 'send', 'event', 'Release Build', 'download', platform );
        return;
    }

    //How to get started
    $('.step').on({
        mouseenter: function () {
            $('.step').css('opacity', 0.5),
            $(this).css('opacity', 1),
            $('.step-image').addClass('d-none').removeClass('d-block');
            $('.'+$(this).attr('data-image')).addClass('d-block').removeClass('d-none');
        },
        mouseout: function () {}
    });

    //FAQ Accordion
    $('.accordion').each(function() {

        $(this).find('.accordion-toggle').click(function(event) {
            event.preventDefault();

            $(".accordion-toggle").not($(this)).removeClass('accordion-toggle-active');

            if($(this).hasClass('accordion-toggle-active')){
                $(this).removeClass('accordion-toggle-active');
            }else{
                $(this).addClass('accordion-toggle-active');
            }

            $(this).next().slideToggle('fast');
            $(".accordion-content").not($(this).next()).slideUp('fast');

            if($(this).attr('id') !== undefined) {
                //add hash to url
                if(history.pushState) {
                    history.pushState(null, null, '#' + $(this).attr('id'));
                } else {
                    location.hash = '#' + $(this).attr('id');
                }
            }
        });
    });

    if( window.location.hash ) {
        showAccordionItem();
    }

    $( ".accordion-content a" ).on( "click", function() {
        var address = $(this).attr('href');
        if( address.charAt(0) === '#' ) {
            showAccordionItem( address );
        };
        return;
    });

    function showAccordionItem( anchorAddress ) {

        var address = anchorAddress ? anchorAddress : window.location.hash;

        $("html, body").animate( {
            scrollTop: ( $( address ).offset().top - 100 )
        }, 1000 );

        $( address ).addClass( 'accordion-toggle-active' ).next().slideToggle( 'fast' );

        return;
    }

});
<|endoftext|>


<commit_before>Version = { id: 'unknown' };
<commit_msg>Bump up version<commit_after>Version = { id: '35e1308' };
<|endoftext|>


<commit_before>if (window.jQuery) {
  define( "jquery", [], function () { return window.jQuery; } );
}
define([
  'jquery',
  'jam/Patterns/src/registry',
  'js/pattern.select2',
  'js/pattern.datetime'
//  'js/pattern.tabs',
//  'js/plone.tabs'
], function($, registry, Select2, DateTime) {

  registry.register(registry.wrap(Select2));
  registry.register(registry.wrap(DateTime));

  // Initial initialization of patterns
  $(document).ready(function() {
    registry.scan(document);
  });

});
<commit_msg>registering of widgets happens in widgets itself and transforms dom before patterns are being initialized<commit_after>if (window.jQuery) {
  define( "jquery", [], function () { return window.jQuery; } );
}
define([
  'jquery',
  'jam/Patterns/src/registry',
  'js/pattern.select2',
  'js/pattern.datetime'
//  'js/pattern.tabs',
//  'js/plone.tabs'
], function($, registry, Select2, DateTime) {

  // Initial initialization of patterns
  $(document).ready(function() {
    registry.scan(document);
  });

  $(document).on("patterns-registry-before-scan.patterns", function(e) {
    var $el = $(e.target);

    // enableFormTabbing
    $match = $el.filter('.enableFormTabbing');
    $match = $match.add($el.find('.enableFormTabbing'));
    $match.addClass('pat-autotoc');

  });

});
<|endoftext|>


<commit_before>var torrenter = require('./torrenter');
var renamer = require('./renamer');
var subtitler = require('./subtitler');
var notifier = require('./notifier');
var xbmc = require('../notifiers/xbmc');

var Item = require('../models/item').Item;
var ItemStates = require('../models/item').ItemStates;

notifier.use(xbmc);
torrenter.setNotifier(notifier);

function check() {
	Item.find({nextCheck : {$lte : new Date().toJSON()}, $where : function() { return this.lastCheck < this.nextCheck; }}, function(err, items) {
		if (err) {
			console.log(err);
			return;
		}

		for (var index in items) {
			var item = items[index];

			console.log('Checking ' + item.name);

			item.lastCheck = new Date().toJSON();
			item.save(function(err) {});

			if (item.state === ItemStates.wanted)
				torrenter.findTorrent(item);
			else if (item.state === ItemStates.snatched)
				torrenter.checkFinished(item);
			else if (item.state === ItemStates.downloaded)
				renamer.rename(item);
			else if (item.state === ItemStates.renamed)
				subtitler.findSubtitles(item);
			else if (item.state === ItemStates.subtitled)
				notifier.updateLibrary(item);
			else if (item.state === ItemStates.finished)
				console.log('Item ' + item.name + ' finished');
			else
				console.log('Invalid state ' + item.state);
		}
	});
}

module.exports = check;<commit_msg>Removed redundant xbmc notifier subscription.<commit_after>var torrenter = require('./torrenter');
var renamer = require('./renamer');
var subtitler = require('./subtitler');
var notifier = require('./notifier');
var xbmc = require('../notifiers/xbmc');

var Item = require('../models/item').Item;
var ItemStates = require('../models/item').ItemStates;

torrenter.setNotifier(notifier);

function check() {
	Item.find({nextCheck : {$lte : new Date().toJSON()}, $where : function() { return this.lastCheck < this.nextCheck; }}, function(err, items) {
		if (err) {
			console.log(err);
			return;
		}

		for (var index in items) {
			var item = items[index];

			console.log('Checking ' + item.name);

			item.lastCheck = new Date().toJSON();
			item.save(function(err) {});

			if (item.state === ItemStates.wanted)
				torrenter.findTorrent(item);
			else if (item.state === ItemStates.snatched)
				torrenter.checkFinished(item);
			else if (item.state === ItemStates.downloaded)
				renamer.rename(item);
			else if (item.state === ItemStates.renamed)
				subtitler.findSubtitles(item);
			else if (item.state === ItemStates.subtitled)
				notifier.updateLibrary(item);
			else if (item.state === ItemStates.finished)
				console.log('Item ' + item.name + ' finished');
			else
				console.log('Invalid state ' + item.state);
		}
	});
}

module.exports = check;<|endoftext|>


<commit_before>module.exports = Cmds.addCommand({
    cmds: [';closeticket ', ';closesupport ', ';stopticket ', ';endticket ', ';close '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Create a ticket to be viewed by Support',

    args: '([ticket_details])',

    example: 'Am I able to give away my whitelist?',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        if (!Util.checkStaff(guild, speaker) && !Util.hasRoleName(speaker, 'Support')) {
            return Util.commandFailed(channel, speaker, 'This command can only be used by Support and above');
        }

        const data = Util.getDataFromString(args, [
            function (str) {
                return (str.match(/\d*(?:\.\d+)?/) || [])[0];
            },
        ], false);

        if (!data) return Util.commandFailed(channel, speaker, 'Invalid parameters');

        const numTicket = data[0];

        const foundTicket = ((await Data.getRecords(guild, 'tickets', { ticket_id: numTicket })) || [])[0];

        if (!foundTicket) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} does not exist`);
        if (!foundTicket.active) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} is already closed`);

        Data.updateRecords(guild, 'tickets', {
            ticket_id: numTicket,
        }, {
            active: 0,
        });

        const sendEmbedFields = [
            { name: 'Ticket Number', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket User', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket Date', value: Util.getDateString(new Date(foundTicket.open_tick)), inline: false },
        ];
        Util.sendEmbed(channel, 'Support Ticket Closed', null, Util.makeEmbedFooter(speaker), null, colGreen, sendEmbedFields);

        return true;
    },
});
<commit_msg>Fixed formatting<commit_after>module.exports = Cmds.addCommand({
    cmds: [';closeticket ', ';closesupport ', ';stopticket ', ';endticket ', ';close '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Create a ticket to be viewed by Support',

    args: '([ticket_details])',

    example: 'Am I able to give away my whitelist?',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: async (cmd, args, msgObj, speaker, channel, guild) => {
        if (!Util.checkStaff(guild, speaker) && !Util.hasRoleName(speaker, 'Support')) {
            return Util.commandFailed(channel, speaker, 'This command can only be used by Support and above');
        }

        const data = Util.getDataFromString(args, [
            function (str) {
                return (str.match(/\d*(?:\.\d+)?/) || [])[0];
            },
        ], false);

        if (!data) return Util.commandFailed(channel, speaker, 'Invalid parameters');

        const numTicket = data[0];

        const foundTicket = ((await Data.getRecords(guild, 'tickets', { ticket_id: numTicket })) || [])[0];

        if (!foundTicket) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} does not exist`);
        if (!foundTicket.active) return Util.commandFailed(channel, speaker, `Ticket #${numTicket} is already closed`);

        Data.updateRecords(guild, 'tickets', {
            ticket_id: numTicket,
        }, {
            active: 0,
        });

        const sendEmbedFields = [
            { name: 'Ticket User', value: `<@${foundTicket.user_id}>`, inline: false },
            { name: 'Ticket Date', value: Util.getDateString(new Date(foundTicket.open_tick)), inline: false },
        ];
        Util.sendEmbed(channel, `Closed Ticket #${foundTicket.ticket_id}`, null, Util.makeEmbedFooter(speaker), null, colGreen, sendEmbedFields);

        return true;
    },
});
<|endoftext|>


<commit_before>(function() {

function MoveList(board) {
  this.board    = board;
  this.moves    = board.moves;
  this.move     = null;
  this.position = null;
  this.stops    = null;
}

Dagaz.Model.getMoveList = function(board) {
  board.generate();
  return new MoveList(board);
}

MoveList.prototype.isPassForced = function() {
  return false;
}

MoveList.prototype.isEmpty = function() {
  return this.moves.length == 0;
}

MoveList.prototype.getMoves = function() {
  if (this.move !== null) {
      return [ this.move ];
  }
  return this.moves;
}

MoveList.prototype.isDone = function() {
  return this.move !== null;
}

MoveList.prototype.canPass = function() {
  return false;
}

MoveList.prototype.getTargets = function() {
  return [];
}

MoveList.prototype.getStarts = function() {
  var result = [];
  _.each(this.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null)) {
          result.push(move.actions[0][1][0]);
      }
  }, this);
  result = _.uniq(_.union(result, this.getCaptures()));
  return result;
}

MoveList.prototype.getStops = function() {
  return this.getStarts();
}

MoveList.prototype.getCaptures = function() {
  return [];
}

MoveList.prototype.getDrops = function() {
  return this.getStarts();
}

MoveList.prototype.getDropPieces = function(pos) {
  var result = [];
  _.each(this.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null) && (move.actions[0][2] !== null)) {
           result.push(move.actions[0][2][0]);
      }
  });
  return _.sortBy(result, function(piece) {
      return piece.type;
  });
}

MoveList.prototype.setPosition = function(pos) {
  if (this.move !== null) return this.move;
  var result = Dagaz.Model.createMove();
  if (_.indexOf(this.getStops(), pos) >= 0) {
      _.each(this.moves, function(move) {
          if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null) && (move.actions[0][1][0] == pos)) {
              result = move;
              this.move = result;
          }
      }, this);
  }
  this.stops = null;
  return result;
}

})();
<commit_msg>Fox Hunting (fixed)<commit_after>(function() {

function MoveList(board) {
  this.board    = board;
  this.moves    = board.moves;
  this.move     = null;
  this.position = null;
  this.stops    = null;
}

Dagaz.Model.getMoveList = function(board) {
  board.generate();
  return new MoveList(board);
}

MoveList.prototype.isPassForced = function() {
  return false;
}

MoveList.prototype.isEmpty = function() {
  return this.moves.length == 0;
}

MoveList.prototype.getMoves = function() {
  if (this.move !== null) {
      return [ this.move ];
  }
  return this.moves;
}

MoveList.prototype.isDone = function() {
  return this.move !== null;
}

MoveList.prototype.canPass = function() {
  return false;
}

MoveList.prototype.getTargets = function() {
  return [];
}

MoveList.prototype.getStarts = function() {
  var result = [];
  _.each(this.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null)) {
          result.push(move.actions[0][1][0]);
      }
  }, this);
  result = _.uniq(_.union(result, this.getCaptures()));
  return result;
}

MoveList.prototype.filterDrops = function(moves, ix) {
  return moves;
}

MoveList.prototype.getStops = function() {
  return this.getStarts();
}

MoveList.prototype.getCaptures = function() {
  return [];
}

MoveList.prototype.getDrops = function() {
  return this.getStarts();
}

MoveList.prototype.getDropPieces = function(pos) {
  var result = [];
  _.each(this.moves, function(move) {
      if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null) && (move.actions[0][2] !== null)) {
           result.push(move.actions[0][2][0]);
      }
  });
  return _.sortBy(result, function(piece) {
      return piece.type;
  });
}

MoveList.prototype.setPosition = function(pos) {
  if (this.move !== null) return this.move;
  var result = Dagaz.Model.createMove();
  if (_.indexOf(this.getStops(), pos) >= 0) {
      _.each(this.moves, function(move) {
          if ((move.actions.length > 0) && (move.actions[0][0] === null) && (move.actions[0][1] !== null) && (move.actions[0][1][0] == pos)) {
              result = move;
              this.move = result;
          }
      }, this);
  }
  this.stops = null;
  return result;
}

})();
<|endoftext|>