<commit_before>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');
var moment = require('moment');
var _ = require('lodash');

/* GET campaigns default get route page. */
router.get('/', function (req, res) {

    Campaign.find({}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
        }
    })

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring
        || !req.body.image || !req.body.tags )
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            image : req.body.image,
            thumbnail:req.body.thumbnail,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

/*
 Like Campaign

 */
router.post('/likeCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    console.log( moment.utc().format('YYYY-MM-DD HH:mm:ss'));
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { likes : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user likes for this campaign ' });
    })
    }
});

router.post('/shareCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{

    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { share : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }
        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user share for this campaign ' });
        }
    })
    }

});

router.post('/wantinCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { wantin : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of wantin for this campaign ' });
    })
    }

});

//Update Campaign details
router.put('/', function(req, res){
    console.log(req.body);

    if(!req.body.field || !req.body.value || !req.body.newValue){
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

    var field = req.body.field;
    var value = req.body.value;
    Campaign.findOne({field :value }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

    })
});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {
    console.log(req);

    Campaign.find({likes: { $gte: 10 }}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }
        else{

        res.status(200).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
        }
    })

});

/*
Get campaigns that would displayed on user timeline
*/
router.post('/getUserCampaigns', function (req, res) {

    console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
   //Get all campaigns that user has not liked or opted in to
            Campaign.find({}, function (err, result) {
                if (err) {
                    console.log(err);
                    return res.status(400).json({
                        success: false,
                        message: 'An error occurred on trying to pull the campaigns ' + err
                    });
                }

                result = _.reject(result, {likes: [{email: req.body.email}] });

                console.log(result.length);
                res.status(200).json({success: true, result: result, message: 'Successfully pulled the Campaigns '});
            }).limit(20);
        }
        });

/*
Get Campaigns liked by User
*/
router.post('/userCampaignLikes', function (req, res) {

     console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

     Campaign.find({"likes":{"$all": [req.body.email]}}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        res.status(200).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
    })

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<commit_msg>Updated User Ikes Endpoint<commit_after>var express = require('express');
var router = express.Router();
var Campaign = require('../models/campaign');
var moment = require('moment');
var _ = require('lodash');

/* GET campaigns default get route page. */
router.get('/', function (req, res) {

    Campaign.find({}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
        }
    })

});

router.post('/', function (req, res) {
    console.log(req.body);

    if(!req.body.name || !req.body.type || !req.body.description || !req.body.enabled || !req.body.expiring
        || !req.body.image || !req.body.tags )
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
        const campaign = new Campaign({
            name: req.body.name,
            type: req.body.type,
            description: req.body.description,
            enabled : req.body.enabled,
            expiring : req.body.expiring,
            image : req.body.image,
            thumbnail:req.body.thumbnail,
            tags : req.body.tags,
            wantin: req.body.wantin
        });

        console.log('Saving Campaign :  ' + req.body.name);

        campaign.save(function(err){
            if(err)
            {
                console.log(err);
                return res.status(400).json({ success: false, message: 'An error occurred on trying to save campaign, please try again later ' + err});
            }

            res.status(201).json({ success: true, message: 'Successfully created Campaign ' + req.body.name });
        })
    }

});

/*
 Like Campaign

 */
router.post('/likeCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    console.log( moment.utc().format('YYYY-MM-DD HH:mm:ss'));
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { likes : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user likes for this campaign ' });
    })
    }
});

router.post('/shareCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{

    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { share : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }
        else{
        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of user share for this campaign ' });
        }
    })
    }

});

router.post('/wantinCampaign', function(req,res){
    console.log(req.body);

    if(!req.body.email || !req.body.campaignid)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else{
    Campaign.findOneAndUpdate({_id:req.body.campaignid}, { $push: { wantin : {"email" : req.body.email, "timestamp" : moment.utc().format('YYYY-MM-DD HH:mm:ss') } } }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to update the share for this campaign ' + err});
        }

        res.status(201).json({ success: true,result:result, message: 'Successfully added users to the list of wantin for this campaign ' });
    })
    }

});

//Update Campaign details
router.put('/', function(req, res){
    console.log(req.body);

    if(!req.body.field || !req.body.value || !req.body.newValue){
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

    var field = req.body.field;
    var value = req.body.value;
    Campaign.findOne({field :value }, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }

    })
});

//Get the top trending campaigns on Shoppa
router.get('/getTopCampaigns', function (req, res) {
    console.log(req);

    Campaign.find({likes: { $gte: 10 }}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }
        else{

        res.status(200).json({ success: true,result:result, message: 'Successfully created Campaign ' + req.body.name });
        }
    })

});

/*
Get campaigns that would displayed on user timeline
*/
router.post('/getUserCampaigns', function (req, res) {

    console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }
    else
    {
   //Get all campaigns that user has not liked or opted in to
            Campaign.find({}, function (err, result) {
                if (err) {
                    console.log(err);
                    return res.status(400).json({
                        success: false,
                        message: 'An error occurred on trying to pull the campaigns ' + err
                    });
                }

                result = _.reject(result, {likes: [{email: req.body.email}] });

                console.log(result.length);
                res.status(200).json({success: true, result: result, message: 'Successfully pulled the Campaigns '});
            }).limit(20);
        }
        });

/*
Get Campaigns liked by User
*/
router.post('/userCampaignLikes', function (req, res) {

     console.log(req.body);

    if(!req.body.email)
    {
        res.status(400).json({ success: false, message: 'Please make sure you pass all the required parameter for this endpoint.' });
        console.log('Missing Parameter');
    }

     Campaign.find({}, function(err,result){
        if(err)
        {
            console.log(err);
            return res.status(400).json({ success: false, message: 'An error occurred on trying to pull the campaigns ' + err});
        }
        result = _.filter(result, {likes: [{email: req.body.email}] });
        res.status(200).json({ success: true,result:result, message: 'Successfully pulled the Campaigns ' });
    })

});

/*
Get expiring campaigns by number of days

*/

router.get('/getExpiringCampaigns', function (req, res) {

    res.sendStatus(200);

});

module.exports = router;
<|endoftext|>


<commit_before>const domain = require('domain'); // eslint-disable-line no-restricted-modules
const vm = require('vm');
const oe = require('obj-ease');
const mw = require('mqtt-wildcard');

const time = process.env.DEBUG ? console.time : () => {};
const timeEnd = process.env.DEBUG ? console.timeEnd : () => {};

class Views {
    constructor() {
        this.db = {};
        this.queries = {};
        this.views = {};
        this.viewsEnv = {};
        this.updateQueue = [];

        process.on('message', msg => {
            switch (msg.type) {
                case 'db':
                    this.db = msg.db;
                    this.rev = msg.rev;
                    Object.keys(this.db).forEach(id => {
                        Object.freeze(this.db[id]);
                    });
                    break;
                case 'update':
                    if (msg.payload === '') {
                        delete this.db[msg.id];
                    } else {
                        this.db[msg.id] = msg.payload;
                        Object.freeze(this.db[msg.id]);
                    }
                    this.rev = msg.rev;
                    this.updateViews();
                    break;

                case 'query':
                    if (msg.init) {
                        this.views[msg.id] = msg.init;
                    }
                    this.query(msg.id, msg.payload, Boolean(msg.init));
                    break;

                default:
            }
        });
    }

    query(id, payload) {
        if (payload === '') {
            // Delete view
            delete this.queries[id];
            delete this.views[id];
            delete this.viewsEnv[id];
            process.send({type: 'view', id, payload: ''});
        } else {
            // Create/overwrite view
            this.queries[id] = payload;

            const map = payload.map;
            const reduce = payload.reduce;
            const filter = payload.filter;

            if (!this.viewsEnv[id]) {
                this.viewsEnv[id] = {};
            }
            this.viewsEnv[id].rev = -1;

            if (!this.views[id]) {
                this.views[id] = {
                    _id: id,
                    _rev: -1
                };
            }

            let src = `
                _meta.map = function () {
                    ${map}
                };
                _meta.result = [];
                Object.keys(_meta.db).forEach(id => {`;

            if (filter) {
                src += `
                    if (_meta.mw(id, ${JSON.stringify(filter)})) {
                        _meta.map.apply(_meta.db[id], [_meta.db[id]]);
                    }`;
            } else {
                src += `
                    _meta.map.apply(_meta.db[id], [_meta.db[id]]);`;
            }
            src += `
                });
            `;
            if (reduce) {
                src += `
                _meta.reduce = function (result) {
                    ${reduce}
                }
                _meta.result = _meta.reduce(_meta.result);
                `;
            }
            delete this.viewsEnv[id].context;
            delete this.viewsEnv[id].script;
            delete this.views[id].serror;
            try {
                time(process.pid + ' create script ' + id);
                this.viewsEnv[id].script = new vm.Script(src, {
                    filename: 'view-' + id
                });
                timeEnd(process.pid + ' create script ' + id);
            } catch (err) {
                this.views[id].error = 'script creation: ' + err.message;
                delete this.views[id].result;
                delete this.views[id].length;
                delete this.viewsEnv[id].script;
                process.send({type: 'view', id, payload: this.views[id]});
            }

            if (!this.viewsEnv[id].context) {
                const sandbox = {
                    _meta: {
                        db: this.db,
                        mw,
                        result: []
                    },
                    emit: item => {
                        sandbox._meta.result.push(item);
                    }
                };
                time(process.pid + ' createContext ' + id);
                this.viewsEnv[id].context = vm.createContext(sandbox);
                timeEnd(process.pid + ' createContext ' + id);
            }

            if (this.viewsEnv[id].script) {
                this.updateQueue.push(id);
                this.shiftQueue();
            }
        }
    }

    execView(id, callback) {
        time(process.pid + ' execView ' + id);
        const script = this.viewsEnv[id].script;
        time(process.pid + ' create domain ' + id);
        const viewDomain = domain.create();
        timeEnd(process.pid + ' create domain ' + id);
        const context = this.viewsEnv[id].context;

        viewDomain.on('error', err => {
            this.views[id].error = 'script execution: ' + err.message;
            delete this.views[id].result;
            delete this.views[id].length;
            process.send({type: 'view', id, payload: this.views[id]});
            callback();
        });

        viewDomain.run(() => {
            setTimeout(() => {
                const rev = this.rev;
                time(process.pid + ' runInContext ' + id);
                script.runInContext(context, {
                    filename: 'view-' + id,
                    timeout: this.scriptTimeout,
                    lineOffset: 2
                });
                timeEnd(process.pid + ' runInContext ' + id);
                timeEnd(process.pid + ' execView ' + id);

                this.viewsEnv[id].rev = rev;

                const res = context._meta.result;
                if (!this.views[id]) {
                    this.views[id] = {
                        _rev: -1
                    };
                }
                delete this.views[id].error;
                delete this.views[id].serror;
                if (!oe.equal(res, this.views[id].result)) {
                    this.views[id]._rev += 1;
                    this.views[id].result = res;
                    this.views[id].length = res.length;
                    process.send({type: 'view', id, payload: this.views[id]});
                }
                callback();
            }, 0);
        });
    }

    updateViews() {
        Object.keys(this.queries).forEach(id => {
            this.updateQueue.push(id);
        });
        this.shiftQueue();
    }

    shiftQueue() {
        if (this.viewRunning || this.updateQueue.length === 0) {
            return;
        }
        const id = this.updateQueue.shift();
        if (this.viewsEnv[id].rev === this.rev) {
            setTimeout(() => {
                this.shiftQueue();
            }, 0);
        } else {
            this.viewRunning = true;
            this.execView(id, () => {
                this.viewRunning = false;
                setTimeout(() => {
                    this.shiftQueue();
                }, 0);
            });
        }
    }
}

new Views(); // eslint-disable-line no-new
<commit_msg>improve coverage<commit_after>const domain = require('domain'); // eslint-disable-line no-restricted-modules
const vm = require('vm');
const oe = require('obj-ease');
const mw = require('mqtt-wildcard');

/* istanbul ignore next */
const time = process.env.DEBUG ? console.time : () => {};
/* istanbul ignore next */
const timeEnd = process.env.DEBUG ? console.timeEnd : () => {};

class Views {
    constructor() {
        this.db = {};
        this.queries = {};
        this.views = {};
        this.viewsEnv = {};
        this.updateQueue = [];

        process.on('message', msg => {
            switch (msg.type) {
                case 'db':
                    this.db = msg.db;
                    this.rev = msg.rev;
                    Object.keys(this.db).forEach(id => {
                        Object.freeze(this.db[id]);
                    });
                    break;
                case 'update':
                    if (msg.payload === '') {
                        delete this.db[msg.id];
                    } else {
                        this.db[msg.id] = msg.payload;
                        Object.freeze(this.db[msg.id]);
                    }
                    this.rev = msg.rev;
                    this.updateViews();
                    break;

                case 'query':
                    if (msg.init) {
                        this.views[msg.id] = msg.init;
                    }
                    this.query(msg.id, msg.payload, Boolean(msg.init));
                    break;

                /* istanbul ignore next */
                default:
            }
        });
    }

    query(id, payload) {
        if (payload === '') {
            // Delete view
            delete this.queries[id];
            delete this.views[id];
            delete this.viewsEnv[id];
            process.send({type: 'view', id, payload: ''});
        } else {
            // Create/overwrite view
            this.queries[id] = payload;

            const map = payload.map;
            const reduce = payload.reduce;
            const filter = payload.filter;

            if (!this.viewsEnv[id]) {
                this.viewsEnv[id] = {};
            }
            this.viewsEnv[id].rev = -1;

            if (!this.views[id]) {
                this.views[id] = {
                    _id: id,
                    _rev: -1
                };
            }

            let src = `
                _meta.map = function () {
                    ${map}
                };
                _meta.result = [];
                Object.keys(_meta.db).forEach(id => {`;

            if (filter) {
                src += `
                    if (_meta.mw(id, ${JSON.stringify(filter)})) {
                        _meta.map.apply(_meta.db[id], [_meta.db[id]]);
                    }`;
            } else {
                src += `
                    _meta.map.apply(_meta.db[id], [_meta.db[id]]);`;
            }
            src += `
                });
            `;
            if (reduce) {
                src += `
                _meta.reduce = function (result) {
                    ${reduce}
                }
                _meta.result = _meta.reduce(_meta.result);
                `;
            }
            delete this.viewsEnv[id].context;
            delete this.viewsEnv[id].script;
            delete this.views[id].serror;
            try {
                time(process.pid + ' create script ' + id);
                this.viewsEnv[id].script = new vm.Script(src, {
                    filename: 'view-' + id
                });
                timeEnd(process.pid + ' create script ' + id);
            } catch (err) {
                this.views[id].error = 'script creation: ' + err.message;
                delete this.views[id].result;
                delete this.views[id].length;
                delete this.viewsEnv[id].script;
                process.send({type: 'view', id, payload: this.views[id]});
            }

            if (!this.viewsEnv[id].context) {
                const sandbox = {
                    _meta: {
                        db: this.db,
                        mw,
                        result: []
                    },
                    emit: item => {
                        sandbox._meta.result.push(item);
                    }
                };
                time(process.pid + ' createContext ' + id);
                this.viewsEnv[id].context = vm.createContext(sandbox);
                timeEnd(process.pid + ' createContext ' + id);
            }

            if (this.viewsEnv[id].script) {
                this.updateQueue.push(id);
                this.shiftQueue();
            }
        }
    }

    execView(id, callback) {
        time(process.pid + ' execView ' + id);
        const script = this.viewsEnv[id].script;
        time(process.pid + ' create domain ' + id);
        const viewDomain = domain.create();
        timeEnd(process.pid + ' create domain ' + id);
        const context = this.viewsEnv[id].context;

        viewDomain.on('error', err => {
            this.views[id].error = 'script execution: ' + err.message;
            delete this.views[id].result;
            delete this.views[id].length;
            process.send({type: 'view', id, payload: this.views[id]});
            callback();
        });

        viewDomain.run(() => {
            setTimeout(() => {
                const rev = this.rev;
                time(process.pid + ' runInContext ' + id);
                script.runInContext(context, {
                    filename: 'view-' + id,
                    timeout: this.scriptTimeout,
                    lineOffset: 2
                });
                timeEnd(process.pid + ' runInContext ' + id);
                timeEnd(process.pid + ' execView ' + id);

                this.viewsEnv[id].rev = rev;

                const res = context._meta.result;
                if (!this.views[id]) {
                    this.views[id] = {
                        _rev: -1
                    };
                }
                delete this.views[id].error;
                delete this.views[id].serror;
                if (!oe.equal(res, this.views[id].result)) {
                    this.views[id]._rev += 1;
                    this.views[id].result = res;
                    this.views[id].length = res.length;
                    process.send({type: 'view', id, payload: this.views[id]});
                }
                callback();
            }, 0);
        });
    }

    updateViews() {
        Object.keys(this.queries).forEach(id => {
            this.updateQueue.push(id);
        });
        this.shiftQueue();
    }

    shiftQueue() {
        if (this.viewRunning || this.updateQueue.length === 0) {
            return;
        }
        const id = this.updateQueue.shift();
        if (this.viewsEnv[id].rev === this.rev) {
            setTimeout(() => {
                this.shiftQueue();
            }, 0);
        } else {
            this.viewRunning = true;
            this.execView(id, () => {
                this.viewRunning = false;
                setTimeout(() => {
                    this.shiftQueue();
                }, 0);
            });
        }
    }
}

new Views(); // eslint-disable-line no-new
<|endoftext|>


<commit_before>export default Ember.Route.extend({
  setupController: function (controller) {

    controller.set('wxmlDoneClass', 'pending');
    controller.set('wxmlStatus', {
      messages: false,
      parsingXML: { running: false, class: 'pending' },
      siteInfo: { running: false, class: 'pending' },
      tags: { running: false, class: 'pending' },
      authors: { running: false, class: 'pending' },
      images: { running: false, class: 'pending' },
      posts: { running: false, class: 'pending' },
      pages: { running: false, class: 'pending' },
      firebase: { running: false, class: 'pending' },
      search: { running: false, class: 'pending' },
    });

    controller.set('isComplete', false);

    controller.convertXml(this.controllerFor('wh.settings.data').get('wordpressXml'));

    return this._super.apply(this, arguments);
  }
});
<commit_msg>intercept wordpress route if no file<commit_after>export default Ember.Route.extend({
  beforeModel: function (transition) {

    var xml = this.controllerFor('wh.settings.data').get('wordpressXml');

    if (xml) {
      this.set('xml', xml);
    } else {
      this.transitionTo('wh');
    }

  },
  setupController: function (controller) {

    controller.set('wxmlDoneClass', 'pending');
    controller.set('wxmlStatus', {
      messages: false,
      parsingXML: { running: false, class: 'pending' },
      siteInfo: { running: false, class: 'pending' },
      tags: { running: false, class: 'pending' },
      authors: { running: false, class: 'pending' },
      images: { running: false, class: 'pending' },
      posts: { running: false, class: 'pending' },
      pages: { running: false, class: 'pending' },
      firebase: { running: false, class: 'pending' },
      search: { running: false, class: 'pending' },
    });

    controller.set('isComplete', false);

    controller.convertXml(this.get('xml'));

    return this._super.apply(this, arguments);
  }
});
<|endoftext|>


<commit_before>var inherits      = require('util').inherits
var EventEmitter  = require('events').EventEmitter;
var LockError     = require('lock/exception.js');

/**
 * Initialize and Register a new worker to the given queue.
 * --------------------------------------------------------
 * @constructor
 * @param {Queue} queue
 * @param {Object} options {
 *    types: {Array.<string>}
 * }
 */
function Worker(queue, options) {
  this.id = queue.workerRegister(options.types, this);
}
inherits(Worker, EventEmitter);

Worker.prototype.taskReady    = function(task) {
  queue.taskLock(this.id, task.id)

  .then(function(task) {

    this.emit(task.name, this.id, task);

  }.bind(this))

  // Ignore lock acquisition errors.
  .catch(LockError, function() {});
}

module.exports  = Worker;
<commit_msg>implement single listener event handlers<commit_after>var LockError     = require('lock/exception.js');

/**
 * Initialize and Register a new worker to the given queue.
 * --------------------------------------------------------
 * @constructor
 * @param {Queue} queue
 * @param {Object} options {
 *    types: {Array.<string>}
 * }
 */
function Worker(queue, options) {
  this.id = queue.workerRegister(options.types, this);
  this.listeners  = {};
}

Worker.prototype.taskReady    = function(task) {
  queue.taskLock(this.id, task.id)

  .then(function(task) {

    this.emit(task.name, this.id, task);

  }.bind(this))

  // Ignore lock acquisition errors.
  .catch(LockError, function() {});
}

Worker.prototype.hasListenerFor(evName) {
  return this.listeners.hasOwnProperty(evName);
}

Worker.prototype.emit = function (evName) {
  cbArgs  = Array.prototype.slice.call(arguments, 1);

  if(this.hasListenerFor(evName)) {
    this.listeners[evName].apply(null, cbArgs);
  }
  return this;
};

Worker.prototype.on = function(evName, handler) {
  if(this.hasListenerFor(evName)) {
    throw new Error('DuplicateListener');
  }
  this.listeners[evName]  = handler;

  return this;
};

module.exports  = Worker;
<|endoftext|>


<commit_before>var cluster = require('cluster'),
    http    = require('http'),
    logfmt  = require('./logfmt');

module.exports = function(handler, options) {
  logfmt.log({ evt: 'starting worker' });

  var server = http.createServer(handler);
  server.listen(options.port);

  setupSignalHandlers();
};

function setupSignalHandlers() {
  process.on('SIGINT', function() {
    logfmt.log({ evt: 'received SIGINT, sending myself SIGTERM' });
    process.kill(process.pid, 'SIGTERM');
  });

  process.on('SIGTERM', function() {
    logfmt.log({ evt: 'ignoring SIGTERM, waiting for master to disconnect' });
  });
}
<commit_msg>remove unused cluster module from worker<commit_after>var http   = require('http'),
    logfmt = require('./logfmt');

module.exports = function(handler, options) {
  logfmt.log({ evt: 'starting worker' });

  var server = http.createServer(handler);
  server.listen(options.port);

  setupSignalHandlers();
};

function setupSignalHandlers() {
  process.on('SIGINT', function() {
    logfmt.log({ evt: 'received SIGINT, sending myself SIGTERM' });
    process.kill(process.pid, 'SIGTERM');
  });

  process.on('SIGTERM', function() {
    logfmt.log({ evt: 'ignoring SIGTERM, waiting for master to disconnect' });
  });
}
<|endoftext|>


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

  var overpassUrl = "http://overpass-api.de/api/interpreter?data=[out:json][timeout:25];";
  var overpassOutputParams = ';out body;>;out skel qt;';

  getLocation();

  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(usePosition);
      } else {
          alert("Geolocation is not supported by this browser.");
      }
  }

  function usePosition(position) {
      console.log("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
      console.log("Distance: " + getDistanceBetween(position.coords, position.coords))
      $.getJSON('http://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node["leisure"="playground"](48.113047481277384,11.541824340820312,48.163566497754275,11.60207748413086);way["leisure"="playground"](48.113047481277384,11.541824340820312,48.163566497754275,11.60207748413086););out body;>;out skel qt;',
      function( data ) {
        console.log(data);
      });
  }

  function degreesToRadians(deg) {
    return deg * (Math.PI/180);
  }

  //dist = arccos(sin(lat1) · sin(lat2) + cos(lat1) · cos(lat2) · cos(lon1 - lon2)) · R
  function getDistanceBetween(coords_1, coords_2) {
    var earthRad = 6371,
        lat1 = degreesToRadians(coords_1.latitude),
        lon1 = degreesToRadians(coords_1.longitude),
        lat2 = degreesToRadians(coords_2.latitude),
        lon2 = degreesToRadians(coords_2.longitude);

    var dist = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)) * earthRad;

    return dist;
  }

  function getBoundingBoxFor(coords, distance) {

  }

})();
<commit_msg>Calculating current boundingBox for OSM Query<commit_after>(function () {
  'use strict';

  var overpassUrl = 'http://overpass-api.de/api/interpreter?data=[out:json][timeout:25];';
  var overpassOutputParams = ';out body;>;out skel qt;';

  getLocation();

  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(usePosition);
      } else {
          alert('Geolocation is not supported by this browser.');
      }
  }

  function usePosition(position) {
      console.log('Latitude: ' + position.coords.latitude + ' Longitude: ' + position.coords.longitude);
      console.log('Distance: ' + getDistanceBetween(position.coords, position.coords));
      console.log(getBoundingBoxFor(position.coords, 1000));

      var boundingBox = getBoundingBoxFor(position.coords, 1000)

      var boundingBoxStr = '(' + boundingBox.latMin + ',' + boundingBox.lonMin + ',' + boundingBox.latMax + ',' + boundingBox.lonMax + ')'

      $.getJSON(overpassUrl + '(node["leisure"="playground"](48.113047481277384,11.541824340820312,48.163566497754275,11.60207748413086);way["leisure"="playground"](48.113047481277384,11.541824340820312,48.163566497754275,11.60207748413086););out body;>;out skel qt;',
      function( data ) {
        console.log(data);
      });
  }

  function degToRad(deg) {
    return deg * (Math.PI/180);
  }

  function radToDeg(rad) {
    return rad * (180/Math.PI);
  }

  //dist = arccos(sin(lat1) · sin(lat2) + cos(lat1) · cos(lat2) · cos(lon1 - lon2)) · R
  function getDistanceBetween(coords1, coords2) {
    var earthRad = 6371,
        lat1 = degToRad(coords1.latitude),
        lon1 = degToRad(coords1.longitude),
        lat2 = degToRad(coords2.latitude),
        lon2 = degToRad(coords2.longitude);

    var dist = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)) * earthRad;

    return dist;
  }

  //Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
  //http://en.wikipedia.org/wiki/Earth_radius
  function wgs84EarthRadius(lat){
    // Semi-axes of WGS-84 geoidal reference
    var wgs84_a = 6378137.0,
        wgs84_b = 6356752.3;

    var an = wgs84_a*wgs84_a * Math.cos(lat);
    var bn = wgs84_b*wgs84_b * Math.sin(lat);
    var ad = wgs84_a * Math.cos(lat);
    var bd = wgs84_b * Math.sin(lat);
    return Math.sqrt((an*an + bn*bn)/(ad*ad + bd*bd));
  }

  function getBoundingBoxFor(coords, distance) {
    var lat = degToRad(coords.latitude),
        lon = degToRad(coords.longitude);

    // Radius of Earth at given latitude
    var radius = wgs84EarthRadius(lat);
    // Radius of the parallel at given latitude
    var pradius = radius*Math.cos(lat);

    var result = {};

    result.latMin = radToDeg(lat - distance/radius);
    result.latMax = radToDeg(lat + distance/radius);
    result.lonMin = radToDeg(lon - distance/pradius);
    result.lonMax = radToDeg(lon + distance/pradius);

    return result;
  }

})();
<|endoftext|>


<commit_before>exports.XQLint = function (source, opts) {
    'use strict';

    opts = opts ? opts : {};

    var JSONiqParser = require('./parsers/JSONiqParser').JSONiqParser;
    var XQueryParser = require('./parsers/XQueryParser').XQueryParser;
    var JSONParseTreeHandler = require('./parsers/JSONParseTreeHandler').JSONParseTreeHandler;
    var Translator = require('./compiler/translator').Translator;
    var StyleChecker = require('./formatter/style_checker').StyleChecker;
    var StaticContext = require('./compiler/static_context').StaticContext;
    var completer = require('../lib/completion/completer');

    var defaults = function(current, def){
        if(!current) {
            return def;
        }
        Object.keys(def).forEach(function(key){
            if(current[key] === undefined){
                current[key] = def[key];
            }
        });
        return current;
    };

    opts = defaults(opts, { styleCheck: false });

    this.createStaticContext = function(){
        return new StaticContext();
    };

    var ast;
    this.getAST = function () {
        return ast;
    };

    var markers = [];
    this.getMarkers = function () {
        return markers;
    };

    this.getErrors = function(){
        var errors = [];
        markers.forEach(function(marker){
            if(marker.type === 'error') {
                errors.push(marker);
            }
        });
        return errors;
    };

    this.getWarnings = function(){
        var warnings = [];
        markers.forEach(function(marker){
            if(marker.type === 'warning') {
                warnings.push(marker);
            }
        });
        return warnings;
    };

    this.getCompletions = function(pos){
        return completer.complete(source, ast, sctx, pos);
    };

    var syntaxError = false;
    this.hasSyntaxError = function () {
        return syntaxError;
    };

    var convertPosition = function (code, begin, end) {
        var before = code.substring(0, begin);
        var after = code.substring(0, end);
        var startline = before.split('\n').length;
        var startcolumn = begin - before.lastIndexOf('\n');
        var endline = after.split('\n').length;
        var endcolumn = end - after.lastIndexOf('\n');
        var pos = {
            sl: startline - 1,
            sc: startcolumn - 1,
            el: endline - 1,
            ec: endcolumn - 1
        };
        return pos;
    };

    var sctx = opts.staticContext ? opts.staticContext : new StaticContext();
    var file = opts.fileName ? opts.fileName : '';
    var isJSONiq = ((file.substring(file.length - '.jq'.length).indexOf('.jq') !== -1) && source.indexOf('xquery version') !== 0) || source.indexOf('jsoniq version') === 0;
    var h = new JSONParseTreeHandler(source);
    var parser = isJSONiq ? new JSONiqParser(source, h) : new XQueryParser(source, h);
    try {
        parser.parse_XQuery();
    } catch (e) {
        if (e instanceof parser.ParseException) {
            syntaxError = true;
            h.closeParseTree();
            var pos = convertPosition(source, e.getBegin(), e.getEnd());
            var message = parser.getErrorMessage(e);
            if (pos.sc === pos.ec) {
                pos.ec++;
            }
            markers.push({
                pos: pos,
                type: 'error',
                level: 'error',
                message: message
            });
        } else {
            throw e;
        }
    }
    ast = h.getParseTree();
    if(opts.styleCheck) {
        markers = markers.concat(new StyleChecker(ast, source).getMarkers());
    }
    var translator = new Translator(sctx, ast);
    markers = markers.concat(translator.getMarkers());
};
<commit_msg>Fix build<commit_after>'use strict';

var createStaticContext = exports.createStaticContext = function(){
    var StaticContext = require('./compiler/static_context').StaticContext;
    return new StaticContext();
};

exports.XQLint = function (source, opts) {

    opts = opts ? opts : {};

    var JSONiqParser = require('./parsers/JSONiqParser').JSONiqParser;
    var XQueryParser = require('./parsers/XQueryParser').XQueryParser;
    var JSONParseTreeHandler = require('./parsers/JSONParseTreeHandler').JSONParseTreeHandler;
    var Translator = require('./compiler/translator').Translator;
    var StyleChecker = require('./formatter/style_checker').StyleChecker;
    var completer = require('../lib/completion/completer');

    var defaults = function(current, def){
        if(!current) {
            return def;
        }
        Object.keys(def).forEach(function(key){
            if(current[key] === undefined){
                current[key] = def[key];
            }
        });
        return current;
    };

    opts = defaults(opts, { styleCheck: false });

    var ast;
    this.getAST = function () {
        return ast;
    };

    var markers = [];
    this.getMarkers = function () {
        return markers;
    };

    this.getErrors = function(){
        var errors = [];
        markers.forEach(function(marker){
            if(marker.type === 'error') {
                errors.push(marker);
            }
        });
        return errors;
    };

    this.getWarnings = function(){
        var warnings = [];
        markers.forEach(function(marker){
            if(marker.type === 'warning') {
                warnings.push(marker);
            }
        });
        return warnings;
    };

    this.getCompletions = function(pos){
        return completer.complete(source, ast, sctx, pos);
    };

    var syntaxError = false;
    this.hasSyntaxError = function () {
        return syntaxError;
    };

    var convertPosition = function (code, begin, end) {
        var before = code.substring(0, begin);
        var after = code.substring(0, end);
        var startline = before.split('\n').length;
        var startcolumn = begin - before.lastIndexOf('\n');
        var endline = after.split('\n').length;
        var endcolumn = end - after.lastIndexOf('\n');
        var pos = {
            sl: startline - 1,
            sc: startcolumn - 1,
            el: endline - 1,
            ec: endcolumn - 1
        };
        return pos;
    };

    var sctx = opts.staticContext ? opts.staticContext : createStaticContext();
    var file = opts.fileName ? opts.fileName : '';
    var isJSONiq = ((file.substring(file.length - '.jq'.length).indexOf('.jq') !== -1) && source.indexOf('xquery version') !== 0) || source.indexOf('jsoniq version') === 0;
    var h = new JSONParseTreeHandler(source);
    var parser = isJSONiq ? new JSONiqParser(source, h) : new XQueryParser(source, h);
    try {
        parser.parse_XQuery();
    } catch (e) {
        if (e instanceof parser.ParseException) {
            syntaxError = true;
            h.closeParseTree();
            var pos = convertPosition(source, e.getBegin(), e.getEnd());
            var message = parser.getErrorMessage(e);
            if (pos.sc === pos.ec) {
                pos.ec++;
            }
            markers.push({
                pos: pos,
                type: 'error',
                level: 'error',
                message: message
            });
        } else {
            throw e;
        }
    }
    ast = h.getParseTree();
    if(opts.styleCheck) {
        markers = markers.concat(new StyleChecker(ast, source).getMarkers());
    }
    var translator = new Translator(sctx, ast);
    markers = markers.concat(translator.getMarkers());
};
<|endoftext|>


<commit_before>"use strict";

var express   = require('express');
var tinycolor = require('tinycolor2');

var config = require('../configuration');
var log = require('../logger');
var Eventer = require('../eventer');

var Blink1Service = require('./blink1Service');
var PatternsService = require('./patternsService');

var app = express();
app.set('json spaces', 2);
var myLogger = function (req, res, next) {
  // log.msg("ApiServer", req.url);
  Eventer.addStatus( {type:'info', source:'api', id:req.ip, text:req.url} );
  next();
};
app.use(myLogger);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function (req, res) {
    res.send("Blink1Control2 API server\n\n");
});
app.get('/blink1(/id)?', function(req,res) {
    res.json({
        blink1_serialnums: Blink1Service.getAllSerials(),
        blink1_id: Blink1Service.getIftttKey(),
        status: "blink1 id"
    });
});
app.get('/blink1/off', function(req,res) {
    var blink1_id = Number(req.query.blink1_id);
    PatternsService.stopAllPatterns();
    Blink1Service.fadeToColor(0.1, '#000000', 0, blink1_id); // turn off everyone
    res.json({
        status: "blink1 off"
    });
});
app.get('/blink1/on', function(req,res) {
    var blink1_id = Number(req.query.blink1_id);
    PatternsService.stopAllPatterns();
    Blink1Service.fadeToColor(0.1, '#ffffff', 0, blink1_id); // turn off everyone
    res.json({
        status: "blink1 on"
    });
});
app.get('/blink1/fadeToRGB', function(req, res) {
    var color = tinycolor(req.query.rgb);
    var secs = Number(req.query.time) || 0.1;
    var ledn = Number(req.query.ledn) || 0;
    var blink1_id = Number(req.query.blink1_id);  // undefined means all blink1 devices

    // var blink1_id = req.query.blink1_id || '';
    var status = "success";

    if( color.isValid() ) {
        status = Blink1Service.fadeToColor( secs*1000, color, ledn, blink1_id );
    }
    else {
        status = "bad hex color specified " + req.query.rgb;
    }
    res.json( {
        // blink1Connected: blink1 !== null,
        blink1Serials: Blink1Service.getAllSerials(),
        lastColor: color.toHexString(),
        lastTime: secs,
        lastLedn: ledn,
        cmd: "fadeToRGB",
        status: status
    });
});

app.get('/blink1/lastColor', function(req, res) {
  var status = "success";
  var ledn = Number(req.query.ledn) || 0;
  var blink1_id = Number(req.query.blink1_id) || 0;  // undefined means all blink1 devices

  var color = Blink1Service.getCurrentColor(blink1_id, ledn);

  res.json( {
      blink1Serials: Blink1Service.getAllSerials(),
      lastColor: color.toHexString(),
      // lastTime: secs,
      lastLedn: ledn,
      cmd: "lastColor",
      status: status
  });
});

app.get('/blink1/pattern(s)?', function(req,res) {
    res.json({
        status: "pattern results",
        patterns: PatternsService.getAllPatternsForOutput()
    });
});
app.get('/blink1/pattern/queue', function(req,res) {
    res.json({
        status: "pattern queue results",
        // patterns: PatternsService.getAllPatternsForOutput()
        queue: PatternsService.getPlayingQueueForOutput()
    });
});

app.get('/blink1/pattern/:type(play|stop)', function(req,res) {
    var status = 'pattern '+req.params.type+': no pattern with that name';
    var patt_name = req.query.pname || req.query.name || '';
    var blink1_id = req.query.blink1_id || 0;

    if( req.params.type === 'play' ) {
        if( patt_name ) {
            // returns true on found pattern // FIXME: go back to using 'findPattern'
            if( PatternsService.playPatternFrom( 'api', patt_name, blink1_id ) ) {
                status = 'pattern play: playing ' +patt_name;
            }
        }
    }
    else { // stop
        if( !patt_name ) {
            PatternsService.stopAllPatterns();
            status = 'pattern stop: stopping all patterns';
        }
        else {
            var id = PatternsService.getIdForName( patt_name );
            if( !id ) { id = patt_name; }

            if( PatternsService.stopPattern( id ) ) {
                status = 'pattern stop: stopping ' +patt_name;
            }
        }
    }

    res.json({
        // id: patt_id,
        status: status,
        pname: patt_name,
        blink1_id: blink1_id
    });
});
app.get('/blink1/pattern/add', function(req,res) {
    var status = 'pattern add: no pattern added';
    var patt_name = req.query.pname || req.query.name || '';
    var pattout = '';
    if( ! patt_name && ! req.query.pattern ) {
        status = "must specify 'name' and 'pattern' string";
    }
    else {
        var patt = PatternsService.newPatternFromString( patt_name, req.query.pattern);
        if( patt ) { PatternsService.savePattern(patt); }
        pattout = PatternsService.formatPatternForOutput(patt);
        status = "pattern add: pattern '"+patt_name+"' added";
    }
    res.json({
        pattern: pattout,
        status: status
    });
});
app.get('/blink1/pattern/del', function(req,res) {
    var status = 'pattern del: no pattern deleted';
    var patt_name = req.query.pname || req.query.name || ''; // hmmmm
    var id = req.query.id || '';
    if( patt_name ) {
        id = PatternsService.getIdForName( patt_name );
        if( !id ) { id = patt_name; }
    }
    if( id ) {
        PatternsService.deletePattern( id );
        status = "pattern '"+id+"' deleted";
    }
    else {
        status = "must specify 'name' or 'id'";
    }
    res.json({
        status: status
    });
});
//
app.get('/blink1/input', function(req,res) {
    var status = 'event inputs';
    var rules = config.readSettings('eventRules');
    res.json({
        status: status,
        inputs: rules
    });
});

var apiServer = {
    server: null,
    config: {},
    // init: function() { // FIXME: bad name
    // 	// config.saveSettings("apiServer:port",8934);
    // 	// config.saveSettings("apiServer:enabled", false);
    // 	// config.saveSettings("apiServer:host", 'localhost');
    // },

    reloadConfig: function() {
        this.stop();
        this.start();
    },

    start: function() {
        this.config = config.readSettings('apiServer');
        if( !this.config ) { // if no config, make sensible defaults & save them
            this.config = {};
            this.config.port = 8934;
            this.config.host = 'localhost';
            this.config.enabled = false;
            config.saveSettings('apiServer', this.config);
        }
        if( !this.config.enabled ) {
            return;
        }
        var port = this.config.port || 8934;
        var host = this.config.host || 'localhost';
        if( host === 'any' ) {
            this.server = app.listen(port);
        }
        else {
            this.server = app.listen( port, host );
        }
    },

    stop: function() {
        if( this.server ) {
            this.server.close();
        }
        // config.saveSettings("apiServer:enabled", false);
    },

};

module.exports = apiServer;
<commit_msg>apiServer: add /blink1/enumerate, cleanup blink1_id parsing<commit_after>"use strict";

var express   = require('express');
var tinycolor = require('tinycolor2');

var config = require('../configuration');
var log = require('../logger');
var Eventer = require('../eventer');

var Blink1Service = require('./blink1Service');
var PatternsService = require('./patternsService');

var app = express();
app.set('json spaces', 2);
var myLogger = function (req, res, next) {
  // log.msg("ApiServer", req.url);
  Eventer.addStatus( {type:'info', source:'api', id:req.ip, text:req.url} );
  next();
};
app.use(myLogger);

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/', function (req, res) {
    res.send("Blink1Control2 API server\n\n");
});
app.get('/blink1(/id)?', function(req,res) {
    res.json({
        blink1_serialnums: Blink1Service.getAllSerials(),
        blink1_id: Blink1Service.getIftttKey(),
        status: "blink1 id"
    });
});
app.get('/blink1/enumerate', function(req,res) {
    Blink1Service.reloadConfig();
    res.json({
        blink1_serialnums: Blink1Service.getAllSerials(),
        blink1_id: Blink1Service.getIftttKey(),
        status: "blink1 enumerate"
    });
});
app.get('/blink1/off', function(req,res) {
    var blink1_id = req.query.blink1_id;
    PatternsService.stopAllPatterns();
    Blink1Service.fadeToColor(0.1, '#000000', 0, blink1_id); // turn off everyone
    res.json({
        status: "blink1 off"
    });
});
app.get('/blink1/on', function(req,res) {
    var blink1_id = Number(req.query.blink1_id);
    PatternsService.stopAllPatterns();
    Blink1Service.fadeToColor(0.1, '#ffffff', 0, blink1_id); // turn off everyone
    res.json({
        status: "blink1 on"
    });
});
app.get('/blink1/fadeToRGB', function(req, res) {
    var color = tinycolor(req.query.rgb);
    var secs = Number(req.query.time) || 0.1;
    var ledn = Number(req.query.ledn) || 0;
    var blink1_id = req.query.blink1_id;
    console.log("*** fadeToRGB", blink1_id, req.query.blink1_id, color);
    var status = "success";

    if( color.isValid() ) {
        status = Blink1Service.fadeToColor( secs*1000, color, ledn, blink1_id );
    }
    else {
        status = "bad hex color specified " + req.query.rgb;
    }
    res.json( {
        // blink1Connected: blink1 !== null,
        blink1Serials: Blink1Service.getAllSerials(),
        lastColor: color.toHexString(),
        lastTime: secs,
        lastLedn: ledn,
        cmd: "fadeToRGB",
        status: status
    });
});

app.get('/blink1/lastColor', function(req, res) {
  var status = "success";
  var ledn = Number(req.query.ledn) || 0;
  var blink1_id = req.query.blink1_id;

  var color = Blink1Service.getCurrentColor(blink1_id, ledn);

  res.json( {
      blink1Serials: Blink1Service.getAllSerials(),
      lastColor: color.toHexString(),
      // lastTime: secs,
      lastLedn: ledn,
      cmd: "lastColor",
      status: status
  });
});

app.get('/blink1/pattern(s)?', function(req,res) {
    res.json({
        status: "pattern results",
        patterns: PatternsService.getAllPatternsForOutput()
    });
});
app.get('/blink1/pattern/queue', function(req,res) {
    res.json({
        status: "pattern queue results",
        // patterns: PatternsService.getAllPatternsForOutput()
        queue: PatternsService.getPlayingQueueForOutput()
    });
});

app.get('/blink1/pattern/:type(play|stop)', function(req,res) {
    var status = 'pattern '+req.params.type+': no pattern with that name';
    var patt_name = req.query.pname || req.query.name || '';
    var blink1_id = req.query.blink1_id;

    if( req.params.type === 'play' ) {
        if( patt_name ) {
            // returns true on found pattern // FIXME: go back to using 'findPattern'
            if( PatternsService.playPatternFrom( 'api', patt_name, blink1_id ) ) {
                status = 'pattern play: playing ' +patt_name;
            }
        }
    }
    else { // stop
        if( !patt_name ) {
            PatternsService.stopAllPatterns();
            status = 'pattern stop: stopping all patterns';
        }
        else {
            var id = PatternsService.getIdForName( patt_name );
            if( !id ) { id = patt_name; }

            if( PatternsService.stopPattern( id ) ) {
                status = 'pattern stop: stopping ' +patt_name;
            }
        }
    }

    res.json({
        // id: patt_id,
        status: status,
        pname: patt_name,
        blink1_id: blink1_id
    });
});
app.get('/blink1/pattern/add', function(req,res) {
    var status = 'pattern add: no pattern added';
    var patt_name = req.query.pname || req.query.name || '';
    var pattout = '';
    if( ! patt_name && ! req.query.pattern ) {
        status = "must specify 'name' and 'pattern' string";
    }
    else {
        var patt = PatternsService.newPatternFromString( patt_name, req.query.pattern);
        if( patt ) { PatternsService.savePattern(patt); }
        pattout = PatternsService.formatPatternForOutput(patt);
        status = "pattern add: pattern '"+patt_name+"' added";
    }
    res.json({
        pattern: pattout,
        status: status
    });
});
app.get('/blink1/pattern/del', function(req,res) {
    var status = 'pattern del: no pattern deleted';
    var patt_name = req.query.pname || req.query.name || ''; // hmmmm
    var id = req.query.id || '';
    if( patt_name ) {
        id = PatternsService.getIdForName( patt_name );
        if( !id ) { id = patt_name; }
    }
    if( id ) {
        PatternsService.deletePattern( id );
        status = "pattern '"+id+"' deleted";
    }
    else {
        status = "must specify 'name' or 'id'";
    }
    res.json({
        status: status
    });
});
//
app.get('/blink1/input', function(req,res) {
    var status = 'event inputs';
    var rules = config.readSettings('eventRules');
    res.json({
        status: status,
        inputs: rules
    });
});

var apiServer = {
    server: null,
    config: {},
    // init: function() { // FIXME: bad name
    // 	// config.saveSettings("apiServer:port",8934);
    // 	// config.saveSettings("apiServer:enabled", false);
    // 	// config.saveSettings("apiServer:host", 'localhost');
    // },

    reloadConfig: function() {
        this.stop();
        this.start();
    },

    start: function() {
        this.config = config.readSettings('apiServer');
        if( !this.config ) { // if no config, make sensible defaults & save them
            this.config = {};
            this.config.port = 8934;
            this.config.host = 'localhost';
            this.config.enabled = false;
            config.saveSettings('apiServer', this.config);
        }
        if( !this.config.enabled ) {
            return;
        }
        var port = this.config.port || 8934;
        var host = this.config.host || 'localhost';
        if( host === 'any' ) {
            this.server = app.listen(port);
        }
        else {
            this.server = app.listen( port, host );
        }
    },

    stop: function() {
        if( this.server ) {
            this.server.close();
        }
        // config.saveSettings("apiServer:enabled", false);
    },

};

module.exports = apiServer;
<|endoftext|>


<commit_before>var zeller = {
  convertMonth : function(m) {
    return (m === 1) ? 13 :
           (m === 2) ? 14 :
           m;
  },
  decodeDay : function(d) {
    return (d === 0) ? 7 : d;
  },
  decodeMonth : function(m) {
    return (m === 13 || m === 14) ? (m - 12) : m;
  },
  decodeYear : function(m,y) {
    return (m === 13 || m === 14) ? (y + 1) : y;
  },
  weekday : function(y,m,d) {
    m = this.convertMonth(m);
    var K = this.yearOfTheCentury(y),
        J = this.zeroBasedCentury(y);
    var encodedWeekday = (
      d
      + Math.floor( (13*(m+1)) / 5 )
      + K
      + Math.floor( K / 4 )
      + Math.floor( J / 4 )
      - 2*J
    ) % 7;
    return this.decodeDay(encodedWeekday);
  },
  yearOfTheCentury : function(y) {
    return y % 100;
  },
  zeroBasedCentury : function(y) {
    return Math.floor(y / 100);
  },
};

module.exports = zeller;
<commit_msg>Importing maths library into zeller module<commit_after>var path = require('path');
var math = require(path.join(process.cwd(),'/lib/maths'));

var zeller = {
  convertMonth : function(m) {
    return (m === 1) ? 13 :
           (m === 2) ? 14 :
           m;
  },
  decodeDay : function(d) {
    return (d === 0) ? 7 : d;
  },
  decodeMonth : function(m) {
    return (m === 13 || m === 14) ? (m - 12) : m;
  },
  decodeYear : function(m,y) {
    return (m === 13 || m === 14) ? (y + 1) : y;
  },
  weekday : function(y,m,d) {
    m = this.convertMonth(m);
    var K = this.yearOfTheCentury(y),
        J = this.zeroBasedCentury(y);
    var encodedWeekday = (
      d
      + Math.floor( (13*(m+1)) / 5 )
      + K
      + Math.floor( K / 4 )
      + Math.floor( J / 4 )
      - 2*J
    ) % 7;
    return this.decodeDay(encodedWeekday);
  },
  yearOfTheCentury : function(y) {
    return y % 100;
  },
  zeroBasedCentury : function(y) {
    return Math.floor(y / 100);
  },
};

module.exports = zeller;
<|endoftext|>


<commit_before>// adding row to table
function addRow(container){
  var dt = new Date();
  var time = dt.getHours() + ":" + ("0"+dt.getMinutes()).slice(-2);
  var count = $(container+' > .row').length - 1 ;
  var row_name =  container.replace("-rows","-row-") + count.toString();
  $(container).last().append('\

\

\
        <input type="text" class="form-control clockpicker text-center btn btn-link" name="from" value="'+time+'">\

\

\
        <input type="text" class="form-control clockpicker text-center btn btn-link" name="to" value="'+time+'">\

\

\
        <input type="text" class="form-control text-center btn btn-link" name="temp" value="20:00">\

\

\
        <button class="btn btn-danger" onclick="removeRow(\''+row_name+'\')">\
          \
        </button>\

\

 ');
  $('.clockpicker').clockpicker({
    placement: "bottom",
    autoclose: "true"
  });
}

function removeRow(row){
  console.log(row);
  $(row).remove();
};

/*function update_value(field_id,rate) {
  (setTimeout( function () {
  $.ajax({
        url: '/dashboard/get_data',
        dataType: "json",
        method: "POST",
        success: function(result){
            $(document.getElementById(field_id)).text(result[field_id])
        }})
},rate*1000)());
};*/

function new_schedule(csrf_token){
    //'/schedule/change'
    var data = {};
    var json = [];
    $('#work_day-table tbody tr').each(function(){
        var obj = {};
        var $td=$(this).find('td');
        var val = [parseInt($td.eq(0).find('span').eq(0).text()),
                   parseInt($td.eq(0).find('span').eq(1).text())];
        obj['from'] = val;
        val = [parseInt($td.eq(1).find('span').eq(0).text()),
               parseInt($td.eq(1).find('span').eq(1).text())];
        obj['to'] = val;
        val = parseFloat( $td.eq(2).text() ).toFixed(2);
        obj['temp'] = val;
        json.push(obj);
    });
    data['work'] = json;
    json = [];
    $('#free_day-table tbody tr').each(function(){
        var obj = {};
        var $td=$(this).find('td');
        obj['from'] = [$td.eq(0).find('span').eq(0).text(),
                       $td.eq(0).find('span').eq(1).text()];
        obj['to']   = [$td.eq(1).find('span').eq(0).text(),
                       $td.eq(1).find('span').eq(1).text()];
        obj['temp'] =  parseFloat($td.eq(2).text());
        json.push(obj);
    });
    data['free'] = json;
    data['other'] = parseFloat($('#work_day-table tfoot tr').find('td').eq(2).text());
    data['week'] = [0,0,0,0,0,1,1];
    console.log(JSON.stringify(data));
    $.post('/schedule/change',JSON.stringify(data),"json");
    /*$.ajax({
        type : "POST",
        contentType: "application/json; charset=utf-8",
        url: '/schedule/change',
        data : data,
        dataType : "json"}); */
};
<commit_msg>Schedule: client-side json composer (new version)<commit_after>// adding row to table
function addRow(container){
  var dt = new Date();
  var time = dt.getHours() + ":" + ("0"+dt.getMinutes()).slice(-2);
  var count = $(container+' > .row').length - 1 ;
  var row_name =  container.replace("-rows","-row-") + count.toString();
  $(container).last().append('\

\

\
        <input type="text" class="form-control clockpicker text-center btn btn-link" name="from" value="'+time+'">\

\

\
        <input type="text" class="form-control clockpicker text-center btn btn-link" name="to" value="'+time+'">\

\

\
        <input type="text" class="form-control text-center btn btn-link" name="temp" value="20.0">\

\

\
        <button class="btn btn-danger" onclick="removeRow(\''+row_name+'\')">\
          \
        </button>\

\

 ');
  $('.clockpicker').clockpicker({
    placement: "bottom",
    autoclose: "true"
  });
}

function removeRow(row){
  console.log(row);
  $(row).remove();
};

/*function update_value(field_id,rate) {
  (setTimeout( function () {
  $.ajax({
        url: '/dashboard/get_data',
        dataType: "json",
        method: "POST",
        success: function(result){
            $(document.getElementById(field_id)).text(result[field_id])
        }})
},rate*1000)());
};*/

function new_schedule(csrf_token){
    //'/schedule/change'
    var data = {};
    var json = [];
    $('#work_day-rows > .row-schedule').each(function(){
        var obj = {};
        var $fields=$(":input", this);
        obj['from'] = $fields.eq(0).val();
        obj['to'] = $fields.eq(1).val();
        obj['temp'] = $fields.eq(2).val();
        json.push(obj);
    });
    data['work'] = json;
    json = [];
    $('#free_day-rows > .row-schedule').each(function(){
        var obj = {};
        var $fields=$(":input", this);
        obj['from'] = $fields.eq(0).val();
        obj['to'] = $fields.eq(1).val();
        obj['temp'] = $fields.eq(2).val();
        json.push(obj);
    });
    data['free'] = json;
    data['other'] = $('#change_default').val();
    data['week'] = [0,0,0,0,0,1,1];
    console.log(JSON.stringify(data));
    $.post('/schedule/change',JSON.stringify(data),"json");
    /*$.ajax({
        type : "POST",
        contentType: "application/json; charset=utf-8",
        url: '/schedule/change',
        data : data,
        dataType : "json"}); */
};
<|endoftext|>


<commit_before>window.onload = function() {
    const clients_country = getClientCountry();

    toggleMobileMenu();
    hashRouter();
    collapseNavbar();
    signUpInit();

    dataLayer.push({ language: getLanguage().toUpperCase() });
    dataLayer.push({ event: 'page_load' });

    function switchView(path) {
        document.getElementById('faq').classList[path === 'faq' ? 'remove' : 'add']('invisible');
        document.getElementById('home').classList[path === 'faq' ? 'add' : 'remove']('invisible');
    }

    function hashRouter() {
        const hash = window.location.hash.substr(1);

        if (/done/.test(hash)) {
            dataLayer.push({ bom_country_abbrev: clients_country || '' });
            dataLayer.push({ event: 'ico_success' });
            clearHash();
            for (let i = 0; i < 2; i++) {
                document.querySelectorAll('.notice-msg')[i].classList.remove('invisible');
                document.getElementsByTagName('form')[i].classList.add('invisible');
            }
            let navbarHeight = checkWidth();
            const to = document.getElementById('coming-soon').offsetTop - navbarHeight;
            scrollTo(to);
        }

        if (/faq/.test(hash)) {
            switchView('faq');
            scrollTo(0);
            window.location.hash = '#faq';
        }

        if (!hash) {
            switchView('home');
            scrollTo(0);
            clearHash();
        }
    }

    // Set language fields
    const language = getLanguage();
    const el_langs = document.getElementsByClassName('frm-language');
    for (let i = 0; i < el_langs.length; i++) {
        el_langs[i].value = language;
    }

    const el_language_dropdown = document.getElementsByClassName('language-dropdown')[0];
    setLanguage(el_language_dropdown, getLanguage());
    document.addEventListener('click', function(e) {
        // Scroll to section
        if (e.target.classList.contains('page-scroll')) {
            e.preventDefault();
            switchView('home');
            clearHash();
            const target = e.target.getAttribute('href').substr(1);
            const offset = /who-we-are|page-top/.test(target) ? 55 : 0;
            const navbarHeight = checkWidth();
            const to = document.getElementById(target).offsetTop - navbarHeight - offset;
            scrollTo(to);
        }

        // Show / hide language dropdown
        if (e.target.parentNode.id === 'lang') {
            e.preventDefault();
            e.target.parentNode.parentNode.classList.toggle('show');
        } else if (/show/.test(el_language_dropdown.classList)) {
            el_language_dropdown.classList.remove('show');
        }
    });

    el_language_dropdown.addEventListener('click', function(e) {
        e.preventDefault();
        if (e.target.nodeName !== 'LI') return;
        const lang = e.target.getAttribute('class');
        if (lang === getLanguage()) return;
        el_language_dropdown.classList.add('invisible'); // hide on change
        document.location = urlForLanguage(lang);
    });

    for (let i = 0; i < 2; i++) {
        document.getElementsByClassName('howto-btn')[i].addEventListener('click', function(e) {
            e.preventDefault();
            window.open(getDocumentUrl(getLanguage().toLowerCase()), '_blank');
        });
    }
    window.onresize = checkWidth;
    window.onscroll = collapseNavbar;
    window.addEventListener('hashchange', hashRouter);

    // News slider configuration
    const slider = tns({
        container: '.my-slider',
        slideBy: 'page',
        rewind: true,
        controls: true,
        autoplay: true,
        autoplayHoverPause: true,
        speed: 600,
        items: 2,   // start with mobile config
        gutter: 5,
        responsive: {
            900: {  // desktop config
                items: 4,
                gutter: 20,
            },
            640: {  // tablet config
                items: 3,
                gutter: 15,
            },
        },
        onInit: function() {
            window.dispatchEvent(new Event('resize')); // trigger resize event
            document.getElementsByClassName('slider-container')[0].classList.remove('invisible');
        }
    });

    setupCrowdin();
};

function clearHash() {
    if (window.history.pushState) {
        window.history.pushState('', '/', window.location.pathname);
    } else {
        window.location.hash = '';
    }
}

function signUpInit() {
    var el_email   = document.getElementById('email');
    var el_signup  = document.getElementById('signup');
    var el_success = document.getElementById('success');

    var ws = wsConnect();

    function sendVerifyEmail() {
        var trimmed_email = trimEmail(el_email.value);
        wsSend(ws, {
            verify_email: trimmed_email,
            type        : 'account_opening'
        });
    }

    function verifySubmit(msg) {
        var response = JSON.parse(msg.data);
        setValidationStyle(el_email, response.error);
        if (!response.error) {
            el_signup.classList.add('invisible');
            el_success.classList.remove('invisible');
        }
    }

    function trimEmail(str) {
        return str.replace(/\s/g, "");
    }

    var validation_set = false; // To prevent validating before submit

    document.getElementById('frm_verify_email').addEventListener('submit', function (evt) {
        evt.preventDefault();

        if (!validateEmail(trimEmail(el_email.value))) {
            if (!validation_set) {
                ['input', 'change'].forEach(function (evt) {
                    el_email.addEventListener(evt, function () {
                        setValidationStyle(el_email, !validateEmail(trimEmail(el_email.value)));
                    });
                });
                setValidationStyle(el_email, !validateEmail(trimEmail(el_email.value)));
                validation_set = true;
            }
            return false;
        }

        if (ws.readyState === 1) {
            sendVerifyEmail();
        } else {
            ws = wsConnect();
            ws.onopen = sendVerifyEmail;
            ws.onmessage = verifySubmit;
        }
    });

    ws.onmessage = verifySubmit;

    // Store gclid
    var gclid = getParamValue(document.referrer, 'gclid');
    if (gclid) {
        localStorage.setItem('gclid', gclid);
    }
}

function validateEmail(email) {
    return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/.test(email);
}

function setValidationStyle(element, has_error) {
    var error_class = 'error-field';
    var invisible_class = 'invisible';
    element.classList[has_error ? 'add' : 'remove'](error_class);
    if (element.value.length < 1) {
        document.getElementById('error_no_email').classList[has_error ? 'remove' : 'add'](invisible_class);
        document.getElementById('error_validate_email').classList[has_error ? 'add' : 'remove'](invisible_class);
    }
    else if (element.value.length >= 1) {
        document.getElementById('error_validate_email').classList[has_error ? 'remove' : 'add'](invisible_class);
        document.getElementById('error_no_email').classList[has_error ? 'add' : 'remove'](invisible_class);
    }
    if (!has_error) {
        document.getElementById('error_validate_email').classList.add(invisible_class);
        document.getElementById('error_no_email').classList.add(invisible_class);
    }
}

function getClientCountry() {
    let clients_country = sessionStorage.getItem('clients_country');
    let residence_list  = sessionStorage.getItem('residence_list');

    // Try to get residence from client's info if logged-in
    if (!clients_country) {
        const accounts = JSON.parse(localStorage.getItem('client.accounts') || null);
        if (accounts) {
            Object.keys(accounts).some(function (loginid) {
                if (accounts[loginid].residence) {
                    clients_country = accounts[loginid].residence;
                    setSession('clients_country', clients_country);
                    return true;
                }
            });
        }
    }

    // Get required info from WebSocket
    const ws = wsConnect();

    function sendRequests() {
        if (!clients_country) wsSend(ws, { website_status: 1 });
        if (!residence_list)  wsSend(ws, { residence_list: 1 });
        wsSend(ws, { time: 1 });
    }

    if (ws.readyState === 1) {
        sendRequests();
    } else {
        ws.onopen = sendRequests;
    }

    ws.onmessage = function (msg) {
        const response = JSON.parse(msg.data);
        if (response.website_status) {
            clients_country = response.website_status.clients_country;
            setSession('clients_country', clients_country);
        } else if (response.residence_list) {
            setSession('residence_list', JSON.stringify(response.residence_list));
        } else if (response.time) {
            initCountdown(response.time);
        }
    };

    return clients_country;
}

// Collapse navbar on scroll
function collapseNavbar() {
    const navbarFixedTopEl = document.getElementsByClassName('navbar-fixed-top');
    navbarFixedTopEl[0].classList[window.scrollY < 50 ? 'add' : 'remove']('top-nav-collapse');
}

function initCountdown(start_epoch) {
    const ico_start    = Date.parse(new Date('2017-11-15T00:00:00Z'));
    const ico_end      = Date.parse(new Date('2017-12-25T00:00:00Z'));
    const date_diff    = Date.parse(new Date()) - start_epoch * 1000;

    const el_container = document.getElementById('status_container');
    const hidden_class = 'invisible';
    const elements     = {};
    let remaining      = 0;
    let countdownd_interval,
        is_before_start,
        is_started,
        end_date;

    function updateStatus() {
        is_before_start = calcRemainingTime(ico_start, date_diff).total > 0;
        is_started      = calcRemainingTime(ico_end,   date_diff).total > 0 && !is_before_start;
        end_date        = is_before_start ? ico_start : ico_end;

        const display_class = 'status-' + (is_before_start ? 'before-start' : is_started ? 'started' : 'ended');
        el_container.querySelectorAll('.status-toggle').forEach(function(el) {
            el.classList[el.classList.contains(display_class) ? 'remove' : 'add'](hidden_class);
        });

        document.getElementById('status_loading').classList.add(hidden_class);
        el_container.classList.remove(hidden_class);

        if (!is_before_start) {
            document.getElementById('ico_subscribe_section').classList.add(hidden_class);
            if (!is_started) { // is_ended
                clearInterval(countdownd_interval);
            }
        }
    }

    updateStatus();

    if (!is_before_start && !is_started) return; // no countdown when already ended

    // Get all elements only once
    ['days', 'hours', 'minutes', 'seconds'].forEach(function (id) {
        const item = el_container.querySelector('#cd_' + id);
        elements[id] = {
            value    : item.querySelector('.cd-value'),
            arcs     : item.querySelectorAll('.arc_q'),
            arc_cover: item.querySelector('.arc_cover'),
        };
    });

    function updateCountdown() {
        remaining = calcRemainingTime(end_date, date_diff);

        arc(elements.days,    remaining.days,    is_before_start ? 20 : 40);
        arc(elements.hours,   remaining.hours,   24);
        arc(elements.minutes, remaining.minutes, 60);
        arc(elements.seconds, remaining.seconds, 60);

        if (remaining.total <= 0) {
            updateStatus();
        }
    }

    updateCountdown();

    if (remaining.total > 0) {
        countdownd_interval = setInterval(updateCountdown, 1000);
    }
}

function calcRemainingTime(end_date, date_diff) {
    const total   = Math.floor(end_date - Date.parse(new Date()) + date_diff) / 1000;
    const seconds = Math.floor(total % 60);
    const minutes = Math.floor((total / 60) % 60);
    const hours   = Math.floor((total / (60 * 60)) % 24);
    const days    = Math.floor(total / (60 * 60 * 24));

    return {
        total  : total,
        days   : days,
        hours  : hours,
        minutes: minutes,
        seconds: seconds,
    };
}

function arc(el, value, scale) {
    el.value.innerHTML = ('0' + value).slice(-2);

    const angle = value * 360 / scale;
    el.arcs.forEach(function(arc, idx) {
        const arc_angle = Math.min((idx + 1) * 90, angle) - 135;
        arc.setAttribute('style', ['-webkit-', '-moz-', '-o-', '-ms-', '', ''].join('transform: rotate(' + arc_angle + 'deg); '));
    });
    el.arc_cover.classList[angle > 90 ? 'add' : 'remove']('invisible');
}

function urlForLanguage(lang, url) {
    if (url === undefined) {
        url = window.location.href;
    }
    let curr_lang = getLanguage();
    return url.replace(new RegExp('/' + curr_lang + '/', 'i'), '/' + lang.trim().toLowerCase() + '/');
}

function setLanguage(el, name) {
    const all_languages = {
        ach  : 'Translations',
        en   : 'English',
        de   : 'Deutsch',
        es   : 'Español',
        fr   : 'Français',
        id   : 'Indonesia',
        it   : 'Italiano',
        ja   : '日本語',
        pl   : 'Polish',
        pt   : 'Português',
        ru   : 'Русский',
        th   : 'Thai',
        vi   : 'Tiếng Việt',
        zh_cn: '简体中文',
        zh_tw: '繁體中文',
    };
    const el_navbar_nav = document.getElementsByClassName('navbar-nav')[0];

    if (/pt|vi|id/.test(name)) {
        el_navbar_nav.classList.add('word-wrap'); // wrap long words
    }

    document.getElementById('selected-lang').textContent = all_languages[name];
    document.getElementsByClassName(name)[0].classList.add('invisible');

    el_navbar_nav.classList.remove('invisible');
    el.classList.remove('invisible');
}

function setupCrowdin() {
    const all_languages = [
        'ACH', 'EN', 'DE', 'ES',
        'FR', 'ID', 'IT', 'JA',
        'PL', 'PT', 'RU', 'TH',
        'VI', 'ZH_CN', 'ZH_TW',
    ];

    const isInContextEnvironment = () => {
        const lang_regex = new RegExp(`^(${all_languages.join('|')})$`, 'i');
        const url_params = window.location.href.split('/').slice(3);
        const language   = (url_params.find(lang => lang_regex.test(lang)) || '');

        return /^https:\/\/staging\.binary\.com\/translations\//i.test(window.location.href) &&
        /ach/i.test(language)
    };

    if (isInContextEnvironment()) {
        document.getElementById('language').style.display = 'none';
        /* eslint-disable no-underscore-dangle */
        window._jipt = [];
        window._jipt.push(['project', 'binary-static']);
        /* eslint-enable no-underscore-dangle */
        if (document.body) {
            const crowdinScript = document.createElement('script');
            crowdinScript.setAttribute('src', `${document.location.protocol}//cdn.crowdin.com/jipt/jipt.js`);
            crowdinScript.setAttribute('type', 'text/javascript');
            document.body.appendChild(crowdinScript);
        }
    }
}

function getDocumentUrl(lang = 'en') {
    return `https://marketing.binary.com/crypto/${lang}/Binary.com_HowToParticipateInICO.pdf`;
}
<commit_msg>Revert<commit_after>window.onload = function() {
    const clients_country = getClientCountry();

    toggleMobileMenu();
    hashRouter();
    collapseNavbar();
    signUpInit();

    dataLayer.push({ language: getLanguage().toUpperCase() });
    dataLayer.push({ event: 'page_load' });

    function switchView(path) {
        document.getElementById('faq').classList[path === 'faq' ? 'remove' : 'add']('invisible');
        document.getElementById('home').classList[path === 'faq' ? 'add' : 'remove']('invisible');
    }

    function hashRouter() {
        const hash = window.location.hash.substr(1);

        if (/done/.test(hash)) {
            dataLayer.push({ bom_country_abbrev: clients_country || '' });
            dataLayer.push({ event: 'ico_success' });
            clearHash();
            for (let i = 0; i < 2; i++) {
                document.querySelectorAll('.notice-msg')[i].classList.remove('invisible');
                document.getElementsByTagName('form')[i].classList.add('invisible');
            }
            let navbarHeight = checkWidth();
            const to = document.getElementById('coming-soon').offsetTop - navbarHeight;
            scrollTo(to);
        }

        if (/faq/.test(hash)) {
            switchView('faq');
            scrollTo(0);
            window.location.hash = '#faq';
        }

        if (!hash) {
            switchView('home');
            scrollTo(0);
            clearHash();
        }
    }

    // Set language fields
    const language = getLanguage();
    const el_langs = document.getElementsByClassName('frm-language');
    for (let i = 0; i < el_langs.length; i++) {
        el_langs[i].value = language;
    }

    const el_language_dropdown = document.getElementsByClassName('language-dropdown')[0];
    setLanguage(el_language_dropdown, getLanguage());
    document.addEventListener('click', function(e) {
        // Scroll to section
        if (e.target.classList.contains('page-scroll')) {
            e.preventDefault();
            switchView('home');
            clearHash();
            const target = e.target.getAttribute('href').substr(1);
            const offset = /who-we-are|page-top/.test(target) ? 55 : 0;
            const navbarHeight = checkWidth();
            const to = document.getElementById(target).offsetTop - navbarHeight - offset;
            scrollTo(to);
        }

        // Show / hide language dropdown
        if (e.target.parentNode.id === 'lang') {
            e.preventDefault();
            e.target.parentNode.parentNode.classList.toggle('show');
        } else if (/show/.test(el_language_dropdown.classList)) {
            el_language_dropdown.classList.remove('show');
        }
    });

    el_language_dropdown.addEventListener('click', function(e) {
        e.preventDefault();
        if (e.target.nodeName !== 'LI') return;
        const lang = e.target.getAttribute('class');
        if (lang === getLanguage()) return;
        el_language_dropdown.classList.add('invisible'); // hide on change
        document.location = urlForLanguage(lang);
    });

    for (let i = 0; i < 2; i++) {
        document.getElementsByClassName('howto-btn')[i].addEventListener('click', function(e) {
            e.preventDefault();
            window.open(getDocumentUrl(getLanguage().toLowerCase()), '_blank');
        });
    }
    window.onresize = checkWidth;
    window.onscroll = collapseNavbar;
    window.addEventListener('hashchange', hashRouter);

    // News slider configuration
    const slider = tns({
        container: '.my-slider',
        slideBy: 'page',
        rewind: true,
        controls: true,
        autoplay: true,
        autoplayHoverPause: true,
        speed: 600,
        items: 2,   // start with mobile config
        gutter: 5,
        responsive: {
            900: {  // desktop config
                items: 4,
                gutter: 20,
            },
            640: {  // tablet config
                items: 3,
                gutter: 15,
            },
        },
        onInit: function() {
            window.dispatchEvent(new Event('resize')); // trigger resize event
            document.getElementsByClassName('slider-container')[0].classList.remove('invisible');
        }
    });

    setupCrowdin();
};

function clearHash() {
    if (window.history.pushState) {
        window.history.pushState('', '/', window.location.pathname);
    } else {
        window.location.hash = '';
    }
}

function signUpInit() {
    var el_email   = document.getElementById('email');
    var el_signup  = document.getElementById('signup');
    var el_success = document.getElementById('success');

    var ws = wsConnect();

    function sendVerifyEmail() {
        var trimmed_email = trimEmail(el_email.value);
        wsSend(ws, {
            verify_email: trimmed_email,
            type        : 'account_opening'
        });
    }

    function verifySubmit(msg) {
        var response = JSON.parse(msg.data);
        setValidationStyle(el_email, response.error);
        if (!response.error) {
            el_signup.classList.add('invisible');
            el_success.classList.remove('invisible');
        }
    }

    function trimEmail(str) {
        return str.replace(/\s/g, "");
    }

    var validation_set = false; // To prevent validating before submit

    document.getElementById('frm_verify_email').addEventListener('submit', function (evt) {
        evt.preventDefault();

        if (!validateEmail(trimEmail(el_email.value))) {
            if (!validation_set) {
                ['input', 'change'].forEach(function (evt) {
                    el_email.addEventListener(evt, function () {
                        setValidationStyle(el_email, !validateEmail(trimEmail(el_email.value)));
                    });
                });
                setValidationStyle(el_email, !validateEmail(trimEmail(el_email.value)));
                validation_set = true;
            }
            return false;
        }

        if (ws.readyState === 1) {
            sendVerifyEmail();
        } else {
            ws = wsConnect();
            ws.onopen = sendVerifyEmail;
            ws.onmessage = verifySubmit;
        }
    });

    ws.onmessage = verifySubmit;

    // Store gclid
    var gclid = getParamValue(document.referrer, 'gclid');
    if (gclid) {
        localStorage.setItem('gclid', gclid);
    }
}

function validateEmail(email) {
    return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/.test(email);
}

function setValidationStyle(element, has_error) {
    var error_class = 'error-field';
    var invisible_class = 'invisible';
    element.classList[has_error ? 'add' : 'remove'](error_class);
    if (element.value.length < 1) {
        document.getElementById('error_no_email').classList[has_error ? 'remove' : 'add'](invisible_class);
        document.getElementById('error_validate_email').classList[has_error ? 'add' : 'remove'](invisible_class);
    }
    else if (element.value.length >= 1) {
        document.getElementById('error_validate_email').classList[has_error ? 'remove' : 'add'](invisible_class);
        document.getElementById('error_no_email').classList[has_error ? 'add' : 'remove'](invisible_class);
    }
    if (!has_error) {
        document.getElementById('error_validate_email').classList.add(invisible_class);
        document.getElementById('error_no_email').classList.add(invisible_class);
    }
}

function getClientCountry() {
    let clients_country = sessionStorage.getItem('clients_country');
    let residence_list  = sessionStorage.getItem('residence_list');

    // Try to get residence from client's info if logged-in
    if (!clients_country) {
        const accounts = JSON.parse(localStorage.getItem('client.accounts') || null);
        if (accounts) {
            Object.keys(accounts).some(function (loginid) {
                if (accounts[loginid].residence) {
                    clients_country = accounts[loginid].residence;
                    setSession('clients_country', clients_country);
                    return true;
                }
            });
        }
    }

    // Get required info from WebSocket
    const ws = wsConnect();

    function sendRequests() {
        if (!clients_country) wsSend(ws, { website_status: 1 });
        if (!residence_list)  wsSend(ws, { residence_list: 1 });
        wsSend(ws, { time: 1 });
    }

    if (ws.readyState === 1) {
        sendRequests();
    } else {
        ws.onopen = sendRequests;
    }

    ws.onmessage = function (msg) {
        const response = JSON.parse(msg.data);
        if (response.website_status) {
            clients_country = response.website_status.clients_country;
            setSession('clients_country', clients_country);
        } else if (response.residence_list) {
            setSession('residence_list', JSON.stringify(response.residence_list));
        } else if (response.time) {
            initCountdown(response.time);
        }
    };

    return clients_country;
}

// Collapse navbar on scroll
function collapseNavbar() {
    const navbarFixedTopEl = document.getElementsByClassName('navbar-fixed-top');
    navbarFixedTopEl[0].classList[window.scrollY < 50 ? 'add' : 'remove']('top-nav-collapse');
}

function initCountdown(start_epoch) {
    const ico_start    = Date.parse(new Date('2017-11-15T00:00:00Z'));
    const ico_end      = Date.parse(new Date('2017-12-25T00:00:00Z'));
    const date_diff    = Date.parse(new Date()) - start_epoch * 1000;

    const el_container = document.getElementById('status_container');
    const hidden_class = 'invisible';
    const elements     = {};
    let remaining      = 0;
    let countdownd_interval,
        is_before_start,
        is_started,
        end_date;

    function updateStatus() {
        is_before_start = calcRemainingTime(ico_start, date_diff).total > 0;
        is_started      = calcRemainingTime(ico_end,   date_diff).total > 0 && !is_before_start;
        end_date        = is_before_start ? ico_start : ico_end;

        const display_class = 'status-' + (is_before_start ? 'before-start' : is_started ? 'started' : 'ended');
        el_container.querySelectorAll('.status-toggle').forEach(function(el) {
            el.classList[el.classList.contains(display_class) ? 'remove' : 'add'](hidden_class);
        });

        document.getElementById('status_loading').classList.add(hidden_class);
        el_container.classList.remove(hidden_class);

        if (!is_before_start) {
            document.getElementById('ico_subscribe_section').classList.add(hidden_class);
            if (!is_started) { // is_ended
                clearInterval(countdownd_interval);
            }
        }
    }

    updateStatus();

    if (!is_before_start && !is_started) return; // no countdown when already ended

    // Get all elements only once
    ['days', 'hours', 'minutes', 'seconds'].forEach(function (id) {
        const item = el_container.querySelector('#cd_' + id);
        elements[id] = {
            value    : item.querySelector('.cd-value'),
            arcs     : item.querySelectorAll('.arc_q'),
            arc_cover: item.querySelector('.arc_cover'),
        };
    });

    function updateCountdown() {
        remaining = calcRemainingTime(end_date, date_diff);

        arc(elements.days,    remaining.days,    is_before_start ? 20 : 40);
        arc(elements.hours,   remaining.hours,   24);
        arc(elements.minutes, remaining.minutes, 60);
        arc(elements.seconds, remaining.seconds, 60);

        if (remaining.total <= 0) {
            updateStatus();
        }
    }

    updateCountdown();

    if (remaining.total > 0) {
        countdownd_interval = setInterval(updateCountdown, 1000);
    }
}

function calcRemainingTime(end_date, date_diff) {
    const total   = Math.floor(end_date - Date.parse(new Date()) + date_diff) / 1000;
    const seconds = Math.floor(total % 60);
    const minutes = Math.floor((total / 60) % 60);
    const hours   = Math.floor((total / (60 * 60)) % 24);
    const days    = Math.floor(total / (60 * 60 * 24));

    return {
        total  : total,
        days   : days,
        hours  : hours,
        minutes: minutes,
        seconds: seconds,
    };
}

function arc(el, value, scale) {
    el.value.innerHTML = ('0' + value).slice(-2);

    const angle = value * 360 / scale;
    el.arcs.forEach(function(arc, idx) {
        const arc_angle = Math.min((idx + 1) * 90, angle) - 135;
        arc.setAttribute('style', ['-webkit-', '-moz-', '-o-', '-ms-', '', ''].join('transform: rotate(' + arc_angle + 'deg); '));
    });
    el.arc_cover.classList[angle > 90 ? 'add' : 'remove']('invisible');
}

function urlForLanguage(lang, url) {
    if (url === undefined) {
        url = window.location.href;
    }
    let curr_lang = getLanguage();
    return url.replace(new RegExp('/' + curr_lang + '/', 'i'), '/' + lang.trim().toLowerCase() + '/');
}

function setLanguage(el, name) {
    const all_languages = {
        ach  : 'Translations',
        en   : 'English',
        de   : 'Deutsch',
        es   : 'Español',
        fr   : 'Français',
        id   : 'Indonesia',
        it   : 'Italiano',
        ja   : '日本語',
        pl   : 'Polish',
        pt   : 'Português',
        ru   : 'Русский',
        th   : 'Thai',
        vi   : 'Tiếng Việt',
        zh_cn: '简体中文',
        zh_tw: '繁體中文',
    };
    const el_navbar_nav = document.getElementsByClassName('navbar-nav')[0];

    if (/pt|vi|id/.test(name)) {
        el_navbar_nav.classList.add('word-wrap'); // wrap long words
    }

    document.getElementById('selected-lang').textContent = all_languages[name];
    document.getElementsByClassName(name)[0].classList.add('invisible');

    el_navbar_nav.classList.remove('invisible');
    el.classList.remove('invisible');
}

function setupCrowdin() {
    const all_languages = [
        'ACH', 'EN', 'DE', 'ES',
        'FR', 'ID', 'IT', 'JA',
        'PL', 'PT', 'RU', 'TH',
        'VI', 'ZH_CN', 'ZH_TW',
    ];

    const isInContextEnvironment = () => {
        const lang_regex = new RegExp(`^(${all_languages.join('|')})$`, 'i');
        const url_params = window.location.href.split('/').slice(3);
        const language   = (url_params.find(lang => lang_regex.test(lang)) || '');

        return /^https:\/\/staging\.binary\.com\/translations\//i.test(window.location.href) &&
        /ach/i.test(language)
    };

    if (isInContextEnvironment()) {
        document.getElementById('language').style.display = 'none';
        /* eslint-disable no-underscore-dangle */
        window._jipt = [];
        window._jipt.push(['project', 'binary-static']);
        /* eslint-enable no-underscore-dangle */
        if (document.body) {
            const crowdinScript = document.createElement('script');
            crowdinScript.setAttribute('src', `${document.location.protocol}//cdn.crowdin.com/jipt/jipt.js`);
            crowdinScript.setAttribute('type', 'text/javascript');
            document.body.appendChild(crowdinScript);
        }
    }
}

function getDocumentUrl(lang = 'en') {
    if (/^(ru)$/i.test(lang)) {
        return `https://ico_documents.binary.com/howto_ico_${lang}.pdf`;
    }
    return 'https://ico_documents.binary.com/howto_ico.pdf';
}
<|endoftext|>