<commit_before>const master = require("cluster");
const cluster = require("./cluster.js");
const numCPUs = require('os').cpus().length;
const logger = require("../utils/logger.js");
const EventEmitter = require("events");
class ClusterManager extends EventEmitter {
    constructor(token, mainFile, options) {
        super();
        this.shardCount = 0;
        this.token = token;
        this.clusters = new Map();
        this.maxShards = 0;
        this.mainFile = mainFile;
        this.firstShardID = -1;
        this.shardSetupStart = 0;
        if (options.stats === true) {
            this.stats = {
                stats: {
                    guilds: 0,
                    users: 0,
                    totalRam: 0,
                    clusters: []
                },
                clustersCounted: 0
            }
        }

        this.launch();
        if (this.stats) {
            this.startStats();
        }
    }

    startStats() {

        let self = this;
        setInterval(function () {
            self.stats.stats.guilds = 0;
            self.stats.stats.users = 0;
            self.stats.stats.totalRam = 0;
            self.stats.stats.clusters = [];
            self.stats.clustersCounted = 0;
            for (let cluster of self.clusters) {
                cluster.worker.send({ message: "stats" });
            }

        }, 5 * 1000);
    }

    start(amount, numSpawned) {
        if (numSpawned === amount) {
            logger.info("Cluster Manager", "Clusters have been started!");
        } else {
            let worker = master.fork();
            this.clusters.set(worker.id, { worker: worker });

            numSpawned = numSpawned + 1;
            let self = this;
            setTimeout(function () {
                self.start(amount, numSpawned);
            }, 1000);
        }
    }

    async launch() {

        logger.info("General", "Cluster Manager has started!");
        const Discord = require("eris");
        let client = new Discord(this.token);
        client.getBotGateway().then(result => {
            this.shardCount = result.shards;
            this.maxShards = this.shardCount;
            logger.info("Cluster Manager", `Need ${this.shardCount} shard(s)!`);
        });

        if (master.isMaster) {

            master.setupMaster({
                silent: true
            });
            // Fork workers.
            await this.start(numCPUs, 0);
            let self = this;
            setTimeout(function () {
                self.roundRobinParser(master.workers);
            }, 5000);

        } else if (master.isWorker) {
            const Cluster = new cluster();
            Cluster.spawn();
        }

        master.on('message', (worker, message, handle) => {
            if (message.type && message.type === "log") {
                logger.log(`Cluster ${worker.id}`, `${message.msg}`)
            }
            if (message.type && message.type === "debug") {
                logger.debug(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "info") {
                logger.info(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "warn") {
                logger.warn(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "error") {
                logger.error(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "shardsStarted") {
                this.startupShards(this.shardSetupStart);
            }
            if (message.type && message.type === "stats") {
                this.stats.stats.guilds += message.stats.guilds;
                this.stats.stats.users += message.stats.users;
                this.stats.stats.totalRam += message.stat.ram;
                let ram = message.stats.ram / 1000000;
                this.stats.stats.clusters.push({ cluster: worker.id, ram: ram, uptime: message.stats.uptime });
                this.stats.clustersCounted += 1;
                if (this.stats.clustersCounted === this.clusters.size) {
                    this.emit("stats", {
                        guilds: this.stats.stats.guilds,
                        users: this.stats.stats.users,
                        totalRam: this.stats.stats.totalRam / 1000000,
                        clusters: this.stats.stats.clusters
                    });
                }
            }
        });

        master.on('exit', (worker, code, signal) => {
            logger.warn("Cluster Manager", `cluster ${worker.id} died. Restarting.`);
            let id = worker.id;
            let cluster = this.clusters.get(id);
            let shards = cluster.shardCount;
            let worker1 = master.fork();
            worker1.send({
                message: "shards",
                type: "reboot",
                shards: shards,
                firstShardID: cluster.firstShardID,
                lastShardID: cluster.lastShardID,
                maxShards: this.maxShards,
                token: this.token,
                file: this.mainFile
            });
            this.clusters.delete(worker1.id);
            this.clusters.set(worker1.id, worker1);
            let newCluster = this.clusters.get(worker1.id);
            newCluster.shardCount = shards;
            newCluster.firstShardID = cluster.firstShardID;
            newCluster.lastShardID = cluster.lastShardID;
        });
    }

    roundRobinParser(clusters) {
        let clusters1 = Object.entries(clusters);
        this.roundRobin(clusters1, 0);
    }

    roundRobin(clusters, start) {
        if (this.shardCount > 0) {
            let cluster = clusters[start];
            if (!cluster) {
                start = 0;
                let cluster = clusters[start];
                let c = cluster[1];
                //ic = internal cluster
                let ic = this.clusters.get(c.id);
                let shards = this.shardCount;
                c.send({
                    message: "shards",
                    type: "round-robin",
                    shards: 1
                });
                if (ic.shardCount) {
                    ic.shardCount = ic.shardCount + 1;
                } else {
                    ic.shardCount = 1;
                }
                this.shardCount = shards - 1;
                let self = this;
                setTimeout(function () {
                    self.roundRobin(clusters, start + 1);
                }, 250);

            } else {
                let c = cluster[1];
                let shards = this.shardCount;
                let ic = this.clusters.get(c.id);
                c.send({
                    message: "shards",
                    type: "round-robin",
                    shards: 1
                });
                if (ic.shardCount) {
                    ic.shardCount = ic.shardCount + 1;
                } else {
                    ic.shardCount = 1;
                }
                this.shardCount = shards - 1;
                let self = this;
                setTimeout(function () {
                    start = start + 1
                    self.roundRobin(clusters, this.shardSetupStart);
                }, 500);
            }
        } else {
            console.log("No shards left to round-robin. Starting to connect");
            this.startupShards(0);
        }
    }

    startupShards(start) {
        let cluster = this.clusters.get(start + 1);
        if (cluster) {
            let firstShardID = this.firstShardID + 1;
            cluster.worker.send({ message: "connect", firstShardID: firstShardID, lastShardID: firstShardID + cluster.shardCount - 1, maxShards: this.maxShards, token: this.token, file: this.mainFile });
            this.firstShardID = firstShardID + cluster.shardCount;
            this.shardSetupStart += 1;
            cluster.firstShardID = firstShardID;
            cluster.lastShardID = firstShardID + cluster.shardCount;
        }
    }
}

module.exports = ClusterManager;<commit_msg>another small fix<commit_after>const master = require("cluster");
const cluster = require("./cluster.js");
const numCPUs = require('os').cpus().length;
const logger = require("../utils/logger.js");
const EventEmitter = require("events");
class ClusterManager extends EventEmitter {
    constructor(token, mainFile, options) {
        super();
        this.shardCount = 0;
        this.token = token;
        this.clusters = new Map();
        this.maxShards = 0;
        this.mainFile = mainFile;
        this.firstShardID = -1;
        this.shardSetupStart = 0;
        if (options.stats === true) {
            this.stats = {
                stats: {
                    guilds: 0,
                    users: 0,
                    totalRam: 0,
                    clusters: []
                },
                clustersCounted: 0
            }
        }

        this.launch();
    }

    startStats() {

        let self = this;
        setInterval(function () {
            self.stats.stats.guilds = 0;
            self.stats.stats.users = 0;
            self.stats.stats.totalRam = 0;
            self.stats.stats.clusters = [];
            self.stats.clustersCounted = 0;
            for (let cluster of self.clusters) {
                cluster.worker.send({ message: "stats" });
            }

        }, 5 * 1000);
    }

    start(amount, numSpawned) {
        if (numSpawned === amount) {
            logger.info("Cluster Manager", "Clusters have been started!");
        } else {
            let worker = master.fork();
            this.clusters.set(worker.id, { worker: worker });

            numSpawned = numSpawned + 1;
            let self = this;
            setTimeout(function () {
                self.start(amount, numSpawned);
            }, 1000);
        }
    }

    async launch() {

        logger.info("General", "Cluster Manager has started!");
        const Discord = require("eris");
        let client = new Discord(this.token);
        client.getBotGateway().then(result => {
            this.shardCount = result.shards;
            this.maxShards = this.shardCount;
            logger.info("Cluster Manager", `Need ${this.shardCount} shard(s)!`);
        });

        if (master.isMaster) {

            master.setupMaster({
                silent: true
            });
            // Fork workers.
            await this.start(numCPUs, 0);
            let self = this;
            setTimeout(function () {
                self.roundRobinParser(master.workers);
            }, 5000);

        } else if (master.isWorker) {
            const Cluster = new cluster();
            Cluster.spawn();
        }

        master.on('message', (worker, message, handle) => {
            if (message.type && message.type === "log") {
                logger.log(`Cluster ${worker.id}`, `${message.msg}`)
            }
            if (message.type && message.type === "debug") {
                logger.debug(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "info") {
                logger.info(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "warn") {
                logger.warn(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "error") {
                logger.error(`Cluster ${worker.id}`, `${message.msg}`);
            }
            if (message.type && message.type === "shardsStarted") {
                this.startupShards(this.shardSetupStart);
            }
            if (message.type && message.type === "stats") {
                this.stats.stats.guilds += message.stats.guilds;
                this.stats.stats.users += message.stats.users;
                this.stats.stats.totalRam += message.stat.ram;
                let ram = message.stats.ram / 1000000;
                this.stats.stats.clusters.push({ cluster: worker.id, ram: ram, uptime: message.stats.uptime });
                this.stats.clustersCounted += 1;
                if (this.stats.clustersCounted === this.clusters.size) {
                    this.emit("stats", {
                        guilds: this.stats.stats.guilds,
                        users: this.stats.stats.users,
                        totalRam: this.stats.stats.totalRam / 1000000,
                        clusters: this.stats.stats.clusters
                    });
                }
            }
        });

        master.on('exit', (worker, code, signal) => {
            logger.warn("Cluster Manager", `cluster ${worker.id} died. Restarting.`);
            let id = worker.id;
            let cluster = this.clusters.get(id);
            let shards = cluster.shardCount;
            let worker1 = master.fork();
            worker1.send({
                message: "shards",
                type: "reboot",
                shards: shards,
                firstShardID: cluster.firstShardID,
                lastShardID: cluster.lastShardID,
                maxShards: this.maxShards,
                token: this.token,
                file: this.mainFile
            });
            this.clusters.delete(worker1.id);
            this.clusters.set(worker1.id, worker1);
            let newCluster = this.clusters.get(worker1.id);
            newCluster.shardCount = shards;
            newCluster.firstShardID = cluster.firstShardID;
            newCluster.lastShardID = cluster.lastShardID;
        });
    }

    roundRobinParser(clusters) {
        let clusters1 = Object.entries(clusters);
        this.roundRobin(clusters1, 0);
    }

    roundRobin(clusters, start) {
        if (this.shardCount > 0) {
            let cluster = clusters[start];
            if (!cluster) {
                start = 0;
                let cluster = clusters[start];
                let c = cluster[1];
                //ic = internal cluster
                let ic = this.clusters.get(c.id);
                let shards = this.shardCount;
                c.send({
                    message: "shards",
                    type: "round-robin",
                    shards: 1
                });
                if (ic.shardCount) {
                    ic.shardCount = ic.shardCount + 1;
                } else {
                    ic.shardCount = 1;
                }
                this.shardCount = shards - 1;
                let self = this;
                setTimeout(function () {
                    self.roundRobin(clusters, start + 1);
                }, 250);

            } else {
                let c = cluster[1];
                let shards = this.shardCount;
                let ic = this.clusters.get(c.id);
                c.send({
                    message: "shards",
                    type: "round-robin",
                    shards: 1
                });
                if (ic.shardCount) {
                    ic.shardCount = ic.shardCount + 1;
                } else {
                    ic.shardCount = 1;
                }
                this.shardCount = shards - 1;
                let self = this;
                setTimeout(function () {
                    start = start + 1
                    self.roundRobin(clusters, this.shardSetupStart);
                }, 500);
            }
        } else {
            console.log("No shards left to round-robin. Starting to connect");
            this.startupShards(0);
            if (this.stats) {
                this.startStats();
            }
        }
    }

    startupShards(start) {
        let cluster = this.clusters.get(start + 1);
        if (cluster) {
            let firstShardID = this.firstShardID + 1;
            cluster.worker.send({ message: "connect", firstShardID: firstShardID, lastShardID: firstShardID + cluster.shardCount - 1, maxShards: this.maxShards, token: this.token, file: this.mainFile });
            this.firstShardID = firstShardID + cluster.shardCount;
            this.shardSetupStart += 1;
            cluster.firstShardID = firstShardID;
            cluster.lastShardID = firstShardID + cluster.shardCount;
        }
    }
}

module.exports = ClusterManager;<|endoftext|>


<commit_before>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;

    // useless too? this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

function boosta(){
}
/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;
BaseAvatar.prototype.velocity = 16;
/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */
 BaseAvatar.prototype.speed = false;

 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 if(!doneTheStuff){
	 BaseAvatar.prototype.velocity = 56;
	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
	 if(!doneTheStuff){
	 BaseAvatar.prototype.velocity = 16;
	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();
};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{

    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
	var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	boosta();
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<commit_msg>asfasfa<commit_after>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;

    // useless too? this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

function boosta(){
}
/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;
BaseAvatar.prototype.velocity = 16;
/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */
 BaseAvatar.prototype.speed = false;

 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 if(!doneTheStuff){
	 BaseAvatar.prototype.velocity = 56;
	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
	 if(!doneTheStuff){
	 BaseAvatar.prototype.velocity = 16;
	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();
};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{

    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
	var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	console.log(BaseAvatar.prototype.velocity);
	boosta();
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<|endoftext|>


<commit_before>var onSelected;
var required;

function AutoComplete(){}

function initAutoComplete() {
	var arrayInputs = $('.typeahead.input-autocomplete');
	jQuery.each(arrayInputs, function(i, input) {
		if(input !== undefined) {
			var jQueryTarget = $(input);
			if(isTypeaheadActive(jQueryTarget)){
				var targetArray = [];
				var url = jQueryTarget.attr('data-url');
				var parameters = jQueryTarget.attr('data-parameters');
				var hasParameters = false;

				if(parameters != null || parameters !== undefined) {
				   	url = url.concat(parameters);
				 	hasParameters = true;
				}

				targetArray['object']     =   jQueryTarget.attr('data-object');
				targetArray['list']       =   jQueryTarget.attr('data-list');
				targetArray['onSelected'] =   jQueryTarget.attr('data-onSelected');
				targetArray['idHidden']   =   jQueryTarget.attr('data-idHidden');
				hasParameters =   parameters != null;
				var fncName   =   jQueryTarget.attr('data-fncName');

				AutoComplete.prototype.autocomplete(url, targetArray, fncName, hasParameters);
			}
		}
	});
}

AutoComplete.prototype.autocomplete = function(vurl, target, fncName, hasParameters){
	 var idHidden = target['idHidden'];
	 AutoComplete.prototype.bloodHound = new Bloodhound({
		datumTokenizer: function(d) {
			return Bloodhound.tokenizers.whitespace(d.val);
		},
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		limit: 100,
		remote: {
			url: vurl,
            replace: function (url, query) {
            	idHidden = target['idHidden'];
            	onSelected = target['onSelected'];
            	required = target['required'];
            	url = hasParameters ? url.replace('%QUERY',query+"&") : url.replace('%QUERY',query);

                if(hasParameters) {
	                var parameters = url.indexOf('&');
	                var param = url.substr(parameters+1);
	                var arr = param.split(",");
	                url = url.substr(0,parameters);

		            for(var i in arr) {
		                url += '&';
		                var v = arr[i].split("=");
		                url += v[0]+"=";
		                url +=eval(v[1]);
		            }
                }

                return url;
            },
            filter: function ( response ) {
        	    return $.map(response, window[fncName]);
            }
		}
	});

	var promise = AutoComplete.prototype.bloodHound.initialize();

	promise.fail(function() { console.log('err!'); });

	$('#'+target['object']).blur(function(){
		if(this.value === '') {
			$('#'+idHidden).val('');
			if($(this).required()) {
				$(this.form).bootstrapValidator('revalidateField', $('#'+idHidden).prop('name'));
			}
		}
	});

	$('#'+target['object']).typeahead(
		{
			minLength: 3,
			highlight: true
		},
		{
			name: target['list'],
			source: AutoComplete.prototype.bloodHound.ttAdapter()
		}
	)
	.on('typeahead:opened', onOpened2)
	.on('typeahead:autocompleted', onAutocompleted2)
	.on('typeahead:selected', function ($e, datum){
		$('#'+idHidden).data(datum);
		$('#'+idHidden).val(eval(onSelected));
	 	if($(this).required()){
			$(this.form).bootstrapValidator('revalidateField', $('#'+idHidden).prop('name'));
		}
	});
};

function onOpened2($e) {}

function onAutocompleted2($e, datum) {}

function limparCampo(campo){
	$("#"+campo).typeahead('val', '');
}

function setarValor(campo,valor){
	$("#"+campo).typeahead('val', valor);
}

function isTypeaheadActive($element){
	return $element.data('ttTypeahead') ? true:false;
}<commit_msg>Correcao autocomplete<commit_after>var onSelected;
var required;

function AutoComplete(){}

function initAutoComplete() {
	var arrayInputs = $('.typeahead.input-autocomplete');
	jQuery.each(arrayInputs, function(i, input) {
		if(input !== undefined) {
			var jQueryTarget = $(input);
			if(!isTypeaheadActive(jQueryTarget)){
				var targetArray = [];
				var url = jQueryTarget.attr('data-url');
				var parameters = jQueryTarget.attr('data-parameters');
				var hasParameters = false;

				if(parameters != null || parameters !== undefined) {
				   	url = url.concat(parameters);
				 	hasParameters = true;
				}

				targetArray['object']     =   jQueryTarget.attr('data-object');
				targetArray['list']       =   jQueryTarget.attr('data-list');
				targetArray['onSelected'] =   jQueryTarget.attr('data-onSelected');
				targetArray['idHidden']   =   jQueryTarget.attr('data-idHidden');
				hasParameters =   parameters != null;
				var fncName   =   jQueryTarget.attr('data-fncName');

				AutoComplete.prototype.autocomplete(url, targetArray, fncName, hasParameters);
			}
		}
	});
}

AutoComplete.prototype.autocomplete = function(vurl, target, fncName, hasParameters){
	 var idHidden = target['idHidden'];
	 AutoComplete.prototype.bloodHound = new Bloodhound({
		datumTokenizer: function(d) {
			return Bloodhound.tokenizers.whitespace(d.val);
		},
		queryTokenizer: Bloodhound.tokenizers.whitespace,
		limit: 100,
		remote: {
			url: vurl,
            replace: function (url, query) {
            	idHidden = target['idHidden'];
            	onSelected = target['onSelected'];
            	required = target['required'];
            	url = hasParameters ? url.replace('%QUERY',query+"&") : url.replace('%QUERY',query);

                if(hasParameters) {
	                var parameters = url.indexOf('&');
	                var param = url.substr(parameters+1);
	                var arr = param.split(",");
	                url = url.substr(0,parameters);

		            for(var i in arr) {
		                url += '&';
		                var v = arr[i].split("=");
		                url += v[0]+"=";
		                url +=eval(v[1]);
		            }
                }

                return url;
            },
            filter: function ( response ) {
        	    return $.map(response, window[fncName]);
            }
		}
	});

	var promise = AutoComplete.prototype.bloodHound.initialize();

	promise.fail(function() { console.log('err!'); });

	$('#'+target['object']).blur(function(){
		if(this.value === '') {
			$('#'+idHidden).val('');
			if($(this).required()) {
				$(this.form).bootstrapValidator('revalidateField', $('#'+idHidden).prop('name'));
			}
		}
	});

	$('#'+target['object']).typeahead(
		{
			minLength: 3,
			highlight: true
		},
		{
			name: target['list'],
			source: AutoComplete.prototype.bloodHound.ttAdapter()
		}
	)
	.on('typeahead:opened', onOpened2)
	.on('typeahead:autocompleted', onAutocompleted2)
	.on('typeahead:selected', function ($e, datum){
		$('#'+idHidden).data(datum);
		$('#'+idHidden).val(eval(onSelected));
	 	if($(this).required()){
			$(this.form).bootstrapValidator('revalidateField', $('#'+idHidden).prop('name'));
		}
	});
};

function onOpened2($e) {}

function onAutocompleted2($e, datum) {}

function limparCampo(campo){
	$("#"+campo).typeahead('val', '');
}

function setarValor(campo,valor){
	$("#"+campo).typeahead('val', valor);
}

function isTypeaheadActive($element){
	return $element.data('ttTypeahead') ? true:false;
}<|endoftext|>


<commit_before>Panvista = {};
Panvista.Domain = typeof(environmentBridge) == "object" ? environmentBridge.getSiteURL() : null;
Panvista.ApiVersion = '1.2';

Panvista.Sections = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param  function callback
         */
        list : function(callback) {
            PvRequest.load('/api/site/sections', function (xml) {
                if (xml == null || xml.getElementsByTagName("sections")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(Panvista.Sections._parseSectionData(xml.getElementsByTagName("sections")[0].childNodes));
            });
        },
        _parseSectionData : function(sectionList) {
            var sections = new Array();

            for (var i=0; i < sectionList.length; i++)
            {
                sections[i]          = {};
                sections[i].type     = sectionList[i].nodeName;
                sections[i].label    = sectionList[i].getAttribute("label");
                sections[i].id       = sectionList[i].getAttribute("id");
                sections[i].url      = sectionList[i].getAttribute("url");
                sections[i].children = new Array();

                if (sectionList[i].childNodes.length > 0) {
                    sections[i].children = Panvista.Sections._parseSectionData(sectionList[i].childNodes);
                }
            }

            return sections;
        }
    };
})();

Panvista.Articles = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param string     id       The id of the article list section
         * @param dictionary options
         * @param function   callback
         */
        list : function(id, options, callback) {
            var url = '/xml/mobile/list/categoryId/' + id + '?';

            if (!isNaN(parseInt(options.page))) {
                url += 'pageNumber=' + parseInt(options.page) + '&';
            }

            if (!isNaN(parseInt(options.limit))) {
                url += 'pageLimit=' + parseInt(options.limit) + '&';
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("item").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var articles         = {};
                articles.items       = Panvista.Articles._parseArticleData(xml.getElementsByTagName('item'));
                articles.total       = xml.getElementsByTagName('pagination')[0].getAttribute('totalItemCount');
                articles.currentPage = xml.getElementsByTagName('pagination')[0].getAttribute('pageNumber');
                articles.totalPages  = xml.getElementsByTagName('pagination')[0].getAttribute('pageCount');
                articles.limit       = xml.getElementsByTagName('pagination')[0].getAttribute('pageLimit');
                callback(articles);
            });
        },
        /**
         * Get the requested article
         *
         * @param  string   id       The id of the article
         * @param  function callback
         */
        get : function(id, callback) {
            PvRequest.load('/xml/mobile/article?id=' + id + '&format=xml', function (xml) {
                if (xml == null || xml.getElementsByTagName("webView").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var article     = {};
                article.id      = id;
                article.section = {id: xml.getElementsByTagName('category')[0].getAttribute('id'),
                                   label: xml.getElementsByTagName('category')[0].getAttribute('label')};
                article.title   = xml.getElementsByTagName("rawView")[0].getAttribute('title');
                article.date    = xml.getElementsByTagName("rawView")[0].getAttribute('publishDate');
                article.content = xml.getElementsByTagName("rawView")[0].firstChild.data;
                callback(article);
            });
        },
        _parseArticleData : function(items) {
            var articles = new Array();

            for (var i=0; i < items.length; i++)
            {
                articles[i]             = {};
                articles[i].id          = items[i].getAttribute('id');
                articles[i].title       = items[i].getAttribute('title');
                articles[i].image       = items[i].getAttribute('imageUrl');
                articles[i].previewText = items[i].getElementsByTagName('p')[0].textContent;
                articles[i].images      = new Array();

                var imgNodes = items[i].getElementsByTagName('img');

                for (var x = 0; x < imgNodes.length; x++) {;
                    articles[i].images[x] = {'src'   : imgNodes[x].getAttribute('src'),
                                             'width' : imgNodes[x].getAttribute('width'),
                                             'height': imgNodes[x].getAttribute('height')};
                }
            }

            return articles;
        }
    };
})();

Panvista.Util = (function() {
    "use strict";

    return {
        device : null,
        paramKey : 'panvista-param-',
        params : new Object(),
        init : function() {
            for (var i = 0; i < localStorage.length; i++) {
                if (localStorage.key(i).substring(0, Panvista.Util.paramKey.length) == Panvista.Util.paramKey) {
                    Panvista.Util.params[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
                }
            }
            for (var key in Panvista.Util.params) {
                localStorage.removeItem(key);
            }
        },
        /**
         * Get a list of sections.
         *
         * @param  object    object
         * @param  function  callback
         */
        each : function(object, callback) {
            for (var key in object) {
                if (object.hasOwnProperty(key)) {
                    callback(object[key]);
                }
            }
        },
        /**
         * Get the current device
         *
         * @return string|null
         */
        getDevice : function() {
            if (Panvista.Util.device != null) {
                return Panvista.Util.device;
            }
            if(navigator.userAgent.match(/Android/i)) {
                return 'android';
            }
            if(navigator.userAgent.match(/iPad/i)) {
                return 'ipad';
            }
            if(navigator.userAgent.match(/iPhone|iPod/i)) {
                return 'iphone';
            }
            return null;
        },
        /**
         * Set the current device for the reqeust
         *
         * @param string
         */
        setDevice : function(device) {
            Panvista.Util.device = device;
        },
        /**
         * Set a parameter to be passed through to the next page
         *
         * @param string key
         * @param mixed  value
         */
        setParam : function(key, value) {
            localStorage.setItem(Panvista.Util.paramKey + key, value);
        },
        /**
         * Get a parameter that was passed through from the previous page
         *
         * @param  string key
         * @return mixed
         */
        getParam : function(key) {
            key = Panvista.Util.paramKey + key;
            if (key in Panvista.Util.params) {
                return Panvista.Util.params[key];
            }
            return null;
        }
    };
})();
Panvista.Util.init();

PvRequest = (function() {
    "use strict";

    return {
        load : function(endpoint, callback) {
            var xml = null;

            switch (endpoint) {
                case '/api/site/sections':
                    xml = typeof(sectionsBridge) == "object" ? (new window.DOMParser()).parseFromString(sectionsBridge.getSections(), "text/xml") : null;
                break;
            }

            if (xml) {
                callback(xml);
                return;
            }

            var request = new XMLHttpRequest();
            var url     = Panvista.Domain + endpoint + (endpoint.indexOf('?') == '-1' ? '?' : '&') + 'version=' + Panvista.ApiVersion + '&device=' + Panvista.Util.getDevice();

            function responseCallback() {
                if(request.readyState < 4) {
                    return;
                }

                if(request.status == 200 && request.readyState === 4) {
                    callback(request.responseXML ? request.responseXML : request.responseText);
                    return;
                }

                console.error("Unable to load %s", url);
                callback(null);
            }

            request.onreadystatechange = responseCallback;
            request.open('GET', url, true);
            request.setRequestHeader('X-JSMobileApp-Id', 'PVJSApi');
            request.setRequestHeader('X-JSMobileApp-Version', '0.7');

            if (endpoint.substring(0, 5) == '/xml/') {
                request.setRequestHeader('X-JSMobileApp-Api', '6');
            }

            request.send();
        }
    }
})();<commit_msg>Integration with the articles bridge<commit_after>Panvista = {};
Panvista.Domain = typeof(environmentBridge) == "object" ? environmentBridge.getSiteURL() : null;
Panvista.ApiVersion = '1.2';

Panvista.Sections = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param  function callback
         */
        list : function(callback) {
            PvRequest.load('/api/site/sections', function (xml) {
                if (xml == null || xml.getElementsByTagName("sections")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(Panvista.Sections._parseSectionData(xml.getElementsByTagName("sections")[0].childNodes));
            });
        },
        _parseSectionData : function(sectionList) {
            var sections = new Array();

            for (var i=0; i < sectionList.length; i++)
            {
                sections[i]          = {};
                sections[i].type     = sectionList[i].nodeName;
                sections[i].label    = sectionList[i].getAttribute("label");
                sections[i].id       = sectionList[i].getAttribute("id");
                sections[i].url      = sectionList[i].getAttribute("url");
                sections[i].children = new Array();

                if (sectionList[i].childNodes.length > 0) {
                    sections[i].children = Panvista.Sections._parseSectionData(sectionList[i].childNodes);
                }
            }

            return sections;
        }
    };
})();

Panvista.Articles = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param string     id       The id of the article list section
         * @param dictionary options
         * @param function   callback
         */
        list : function(id, options, callback) {
            var url = '/xml/mobile/list/categoryId/' + id;

            if (options.length > 0) {
                url += '?';
            }

            if (!isNaN(parseInt(options.page))) {
                url += 'pageNumber=' + parseInt(options.page) + '&';
            }

            if (!isNaN(parseInt(options.limit))) {
                url += 'pageLimit=' + parseInt(options.limit) + '&';
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("item").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var articles         = {};
                articles.items       = Panvista.Articles._parseArticleData(xml.getElementsByTagName('item'));
                articles.total       = xml.getElementsByTagName('pagination')[0].getAttribute('totalItemCount');
                articles.currentPage = xml.getElementsByTagName('pagination')[0].getAttribute('pageNumber');
                articles.totalPages  = xml.getElementsByTagName('pagination')[0].getAttribute('pageCount');
                articles.limit       = xml.getElementsByTagName('pagination')[0].getAttribute('pageLimit');
                callback(articles);
            });
        },
        /**
         * Get the requested article
         *
         * @param  string   id       The id of the article
         * @param  function callback
         */
        get : function(id, callback) {
            PvRequest.load('/xml/mobile/article?id=' + id + '&format=xml', function (xml) {
                if (xml == null || xml.getElementsByTagName("webView").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var article     = {};
                article.id      = id;
                article.section = {id: xml.getElementsByTagName('category')[0].getAttribute('id'),
                                   label: xml.getElementsByTagName('category')[0].getAttribute('label')};
                article.title   = xml.getElementsByTagName("rawView")[0].getAttribute('title');
                article.date    = xml.getElementsByTagName("rawView")[0].getAttribute('publishDate');
                article.content = xml.getElementsByTagName("rawView")[0].firstChild.data;
                callback(article);
            });
        },
        _parseArticleData : function(items) {
            var articles = new Array();

            for (var i=0; i < items.length; i++)
            {
                articles[i]             = {};
                articles[i].id          = items[i].getAttribute('id');
                articles[i].title       = items[i].getAttribute('title');
                articles[i].image       = items[i].getAttribute('imageUrl');
                articles[i].previewText = items[i].getElementsByTagName('p')[0].textContent;
                articles[i].images      = new Array();

                var imgNodes = items[i].getElementsByTagName('img');

                for (var x = 0; x < imgNodes.length; x++) {;
                    articles[i].images[x] = {'src'   : imgNodes[x].getAttribute('src'),
                                             'width' : imgNodes[x].getAttribute('width'),
                                             'height': imgNodes[x].getAttribute('height')};
                }
            }

            return articles;
        }
    };
})();

Panvista.Util = (function() {
    "use strict";

    return {
        device : null,
        paramKey : 'panvista-param-',
        params : new Object(),
        init : function() {
            for (var i = 0; i < localStorage.length; i++) {
                if (localStorage.key(i).substring(0, Panvista.Util.paramKey.length) == Panvista.Util.paramKey) {
                    Panvista.Util.params[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
                }
            }
            for (var key in Panvista.Util.params) {
                localStorage.removeItem(key);
            }
        },
        /**
         * Get a list of sections.
         *
         * @param  object    object
         * @param  function  callback
         */
        each : function(object, callback) {
            for (var key in object) {
                if (object.hasOwnProperty(key)) {
                    callback(object[key]);
                }
            }
        },
        /**
         * Get the current device
         *
         * @return string|null
         */
        getDevice : function() {
            if (Panvista.Util.device != null) {
                return Panvista.Util.device;
            }
            if(navigator.userAgent.match(/Android/i)) {
                return 'android';
            }
            if(navigator.userAgent.match(/iPad/i)) {
                return 'ipad';
            }
            if(navigator.userAgent.match(/iPhone|iPod/i)) {
                return 'iphone';
            }
            return null;
        },
        /**
         * Set the current device for the reqeust
         *
         * @param string
         */
        setDevice : function(device) {
            Panvista.Util.device = device;
        },
        /**
         * Set a parameter to be passed through to the next page
         *
         * @param string key
         * @param mixed  value
         */
        setParam : function(key, value) {
            localStorage.setItem(Panvista.Util.paramKey + key, value);
        },
        /**
         * Get a parameter that was passed through from the previous page
         *
         * @param  string key
         * @return mixed
         */
        getParam : function(key) {
            key = Panvista.Util.paramKey + key;
            if (key in Panvista.Util.params) {
                return Panvista.Util.params[key];
            }
            return null;
        },
        parseXml : function(xml) {
            return (new window.DOMParser()).parseFromString(xml, "text/xml");
        }
    };
})();
Panvista.Util.init();

PvRequest = (function() {
    "use strict";

    return {
        load : function(endpoint, callback) {
            var xml    = null,
                result = null;

            switch (endpoint) {
                case '/api/site/sections':
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getSections() : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
                default:
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getXmlData(endpoint) : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
            };

            if (xml) {
                callback(xml);
                return;
            }

            var request = new XMLHttpRequest();
            var url     = Panvista.Domain + endpoint + (endpoint.indexOf('?') == '-1' ? '?' : '&') + 'version=' + Panvista.ApiVersion + '&device=' + Panvista.Util.getDevice();

            function responseCallback() {
                if(request.readyState < 4) {
                    return;
                }

                if(request.status == 200 && request.readyState === 4) {
                    callback(request.responseXML ? request.responseXML : null);
                    return;
                }

                console.error("Unable to load %s", url);
                callback(null);
            }

            request.onreadystatechange = responseCallback;
            request.open('GET', url, true);
            request.setRequestHeader('X-JSMobileApp-Id', 'PVJSApi');
            request.setRequestHeader('X-JSMobileApp-Version', '0.7');

            if (endpoint.substring(0, 5) == '/xml/') {
                request.setRequestHeader('X-JSMobileApp-Api', '6');
            }

            request.send();
        }
    }
})();<|endoftext|>


<commit_before>Panvista = {};
Panvista.Domain = typeof(environmentBridge) == "object" ? environmentBridge.getSiteURL() : null;
Panvista.ApiVersion = '1.2';

Panvista.Sections = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param  function callback
         */
        list : function(callback) {
            PvRequest.load('/api/site/sections', function (xml) {
                if (xml == null || xml.getElementsByTagName("sections")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(Panvista.Sections._parseSectionData(xml.getElementsByTagName("sections")[0].childNodes));
            });
        },
        _parseSectionData : function(sectionList) {
            var sections = new Array();

            for (var i=0; i < sectionList.length; i++)
            {
                sections[i]          = {};
                sections[i].type     = sectionList[i].nodeName;
                sections[i].label    = sectionList[i].getAttribute("label");
                sections[i].id       = sectionList[i].getAttribute("id");
                sections[i].url      = sectionList[i].getAttribute("url");
                sections[i].children = new Array();

                if (sectionList[i].childNodes.length > 0) {
                    sections[i].children = Panvista.Sections._parseSectionData(sectionList[i].childNodes);
                }
            }

            return sections;
        }
    };
})();

Panvista.Articles = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param string     id       The id of the article list section
         * @param dictionary options
         * @param function   callback
         */
        list : function(id, options, callback) {
            var url = '/xml/mobile/list/categoryId/' + id;

            if (Object.keys(options).length > 0) {
                url += '?';
            }

            if (!isNaN(parseInt(options.page))) {
                url += 'pageNumber=' + parseInt(options.page) + '&';
            }

            if (!isNaN(parseInt(options.limit))) {
                url += 'pageLimit=' + parseInt(options.limit) + '&';
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("item").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var articles         = {};
                articles.items       = Panvista.Articles._parseArticleData(xml.getElementsByTagName('item'));
                articles.total       = xml.getElementsByTagName('pagination')[0].getAttribute('totalItemCount');
                articles.currentPage = xml.getElementsByTagName('pagination')[0].getAttribute('pageNumber');
                articles.totalPages  = xml.getElementsByTagName('pagination')[0].getAttribute('pageCount');
                articles.limit       = xml.getElementsByTagName('pagination')[0].getAttribute('pageLimit');
                callback(articles);
            });
        },
        /**
         * Get the requested article
         *
         * @param  string   id       The id of the article
         * @param  function callback
         */
        get : function(id, callback) {
            PvRequest.load('/xml/mobile/article?id=' + id + '&format=xml', function (xml) {
                if (xml == null || xml.getElementsByTagName("webView").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var article     = {};
                article.id      = id;
                article.section = {id: xml.getElementsByTagName('category')[0].getAttribute('id'),
                                   label: xml.getElementsByTagName('category')[0].getAttribute('label')};
                article.title   = xml.getElementsByTagName("rawView")[0].getAttribute('title');
                article.date    = xml.getElementsByTagName("rawView")[0].getAttribute('publishDate');
                article.content = xml.getElementsByTagName("rawView")[0].firstChild.data;
                callback(article);
            });
        },
        _parseArticleData : function(items) {
            var articles = new Array();

            for (var i=0; i < items.length; i++)
            {
                articles[i]             = {};
                articles[i].id          = items[i].getAttribute('id');
                articles[i].title       = items[i].getAttribute('title');
                articles[i].image       = items[i].getAttribute('imageUrl');
                articles[i].previewText = items[i].getElementsByTagName('p')[0].textContent;
                articles[i].images      = new Array();

                var imgNodes = items[i].getElementsByTagName('img');

                for (var x = 0; x < imgNodes.length; x++) {;
                    articles[i].images[x] = {'src'   : imgNodes[x].getAttribute('src'),
                                             'width' : imgNodes[x].getAttribute('width'),
                                             'height': imgNodes[x].getAttribute('height')};
                }
            }

            return articles;
        }
    };
})();

Panvista.Content = (function() {
    "use strict";

    return {
        list : function(id, options, callback) {
            var url = '/api/content/list?id=' + id;

            if (!isNaN(parseInt(options.page))) {
                url += '&page=' + parseInt(options.page);
            }

            if (!isNaN(parseInt(options.limit))) {
                url += '&limit=' + parseInt(options.limit);
            }

            if (typeof(options.filter) == "object") {
                url += '&filter=' + encodeURIComponent(JSON.stringify(options.filter));
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("documents")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(xml.getElementsByTagName("documents")[0]);
            });
        },
        get : function(section_id, id, callback) {
            var url = '/api/content/document?section_id=' + section_id + '&id=' + id;

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("document")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(xml.getElementsByTagName("document")[0]);
            });
        }
    }
})();

Panvista.Util = (function() {
    "use strict";

    return {
        device : null,
        paramKey : 'panvista-param-',
        params : new Object(),
        init : function() {
            for (var i = 0; i < localStorage.length; i++) {
                if (localStorage.key(i).substring(0, Panvista.Util.paramKey.length) == Panvista.Util.paramKey) {
                    Panvista.Util.params[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
                }
            }
            for (var key in Panvista.Util.params) {
                localStorage.removeItem(key);
            }
        },
        /**
         * Get a list of sections.
         *
         * @param  object    object
         * @param  function  callback
         */
        each : function(object, callback) {
            for (var key in object) {
                if (object.hasOwnProperty(key)) {
                    callback(object[key]);
                }
            }
        },
        /**
         * Get the current device
         *
         * @return string|null
         */
        getDevice : function() {
            if (Panvista.Util.device != null) {
                return Panvista.Util.device;
            }
            if(navigator.userAgent.match(/Android/i)) {
                return 'android';
            }
            if(navigator.userAgent.match(/iPad/i)) {
                return 'ipad';
            }
            if(navigator.userAgent.match(/iPhone|iPod/i)) {
                return 'iphone';
            }
            return null;
        },
        /**
         * Set the current device for the reqeust
         *
         * @param string
         */
        setDevice : function(device) {
            Panvista.Util.device = device;
        },
        /**
         * Set a parameter to be passed through to the next page
         *
         * @param string key
         * @param mixed  value
         */
        setParam : function(key, value) {
            localStorage.setItem(Panvista.Util.paramKey + key, value);
        },
        /**
         * Get a parameter that was passed through from the previous page
         *
         * @param  string key
         * @return mixed
         */
        getParam : function(key) {
            key = Panvista.Util.paramKey + key;
            if (key in Panvista.Util.params) {
                return Panvista.Util.params[key];
            }
            return null;
        },
        parseXml : function(xml) {
            return (new window.DOMParser()).parseFromString(xml, "text/xml");
        }
    };
})();
Panvista.Util.init();

PvRequest = (function() {
    "use strict";

    return {
        load : function(endpoint, callback) {
            var xml    = null,
                result = null;

            switch (endpoint) {
                case '/api/site/sections':
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getSections() : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
                default:
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getXmlData(endpoint) : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
            };

            if (xml && result.length != 0) {
                callback(xml);
                return;
            }

            var request = new XMLHttpRequest();
            var url     = Panvista.Domain + endpoint + (endpoint.indexOf('?') == '-1' ? '?' : '&') + 'version=' + Panvista.ApiVersion + '&device=' + Panvista.Util.getDevice();

            function responseCallback() {
                if(request.readyState < 4) {
                    return;
                }

                if(request.status == 200 && request.readyState === 4) {
                    callback(request.responseXML ? request.responseXML : null);
                    return;
                }

                console.error("Unable to load %s", url);
                callback(null);
            }

            request.onreadystatechange = responseCallback;
            request.open('GET', url, true);
            request.setRequestHeader('X-JSMobileApp-Id', 'PVJSApi');
            request.setRequestHeader('X-JSMobileApp-Version', '0.7');

            if (endpoint.substring(0, 5) == '/xml/') {
                request.setRequestHeader('X-JSMobileApp-Api', '6');
            }

            request.send();
        }
    }
})();<commit_msg>Ability to search through content<commit_after>Panvista = {};
Panvista.Domain = typeof(environmentBridge) == "object" ? environmentBridge.getSiteURL() : null;
Panvista.ApiVersion = '1.2';

Panvista.Sections = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param  function callback
         */
        list : function(callback) {
            PvRequest.load('/api/site/sections', function (xml) {
                if (xml == null || xml.getElementsByTagName("sections")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(Panvista.Sections._parseSectionData(xml.getElementsByTagName("sections")[0].childNodes));
            });
        },
        _parseSectionData : function(sectionList) {
            var sections = new Array();

            for (var i=0; i < sectionList.length; i++)
            {
                sections[i]          = {};
                sections[i].type     = sectionList[i].nodeName;
                sections[i].label    = sectionList[i].getAttribute("label");
                sections[i].id       = sectionList[i].getAttribute("id");
                sections[i].url      = sectionList[i].getAttribute("url");
                sections[i].children = new Array();

                if (sectionList[i].childNodes.length > 0) {
                    sections[i].children = Panvista.Sections._parseSectionData(sectionList[i].childNodes);
                }
            }

            return sections;
        }
    };
})();

Panvista.Articles = (function() {
    "use strict";

    return {
        /**
         * Get a list of sections.
         *
         * @param string     id       The id of the article list section
         * @param dictionary options
         * @param function   callback
         */
        list : function(id, options, callback) {
            var url = '/xml/mobile/list/categoryId/' + id;

            if (Object.keys(options).length > 0) {
                url += '?';
            }

            if (!isNaN(parseInt(options.page))) {
                url += 'pageNumber=' + parseInt(options.page) + '&';
            }

            if (!isNaN(parseInt(options.limit))) {
                url += 'pageLimit=' + parseInt(options.limit) + '&';
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("item").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var articles         = {};
                articles.items       = Panvista.Articles._parseArticleData(xml.getElementsByTagName('item'));
                articles.total       = xml.getElementsByTagName('pagination')[0].getAttribute('totalItemCount');
                articles.currentPage = xml.getElementsByTagName('pagination')[0].getAttribute('pageNumber');
                articles.totalPages  = xml.getElementsByTagName('pagination')[0].getAttribute('pageCount');
                articles.limit       = xml.getElementsByTagName('pagination')[0].getAttribute('pageLimit');
                callback(articles);
            });
        },
        /**
         * Get the requested article
         *
         * @param  string   id       The id of the article
         * @param  function callback
         */
        get : function(id, callback) {
            PvRequest.load('/xml/mobile/article?id=' + id + '&format=xml', function (xml) {
                if (xml == null || xml.getElementsByTagName("webView").length < 0) {
                    callback({error: true}); //Return an empty object
                    return;
                }

                var article     = {};
                article.id      = id;
                article.section = {id: xml.getElementsByTagName('category')[0].getAttribute('id'),
                                   label: xml.getElementsByTagName('category')[0].getAttribute('label')};
                article.title   = xml.getElementsByTagName("rawView")[0].getAttribute('title');
                article.date    = xml.getElementsByTagName("rawView")[0].getAttribute('publishDate');
                article.content = xml.getElementsByTagName("rawView")[0].firstChild.data;
                callback(article);
            });
        },
        _parseArticleData : function(items) {
            var articles = new Array();

            for (var i=0; i < items.length; i++)
            {
                articles[i]             = {};
                articles[i].id          = items[i].getAttribute('id');
                articles[i].title       = items[i].getAttribute('title');
                articles[i].image       = items[i].getAttribute('imageUrl');
                articles[i].previewText = items[i].getElementsByTagName('p')[0].textContent;
                articles[i].images      = new Array();

                var imgNodes = items[i].getElementsByTagName('img');

                for (var x = 0; x < imgNodes.length; x++) {;
                    articles[i].images[x] = {'src'   : imgNodes[x].getAttribute('src'),
                                             'width' : imgNodes[x].getAttribute('width'),
                                             'height': imgNodes[x].getAttribute('height')};
                }
            }

            return articles;
        }
    };
})();

Panvista.Content = (function() {
    "use strict";

    return {
        list : function(id, options, callback) {
            var url = '/api/content/list?id=' + id;

            if (!isNaN(parseInt(options.page))) {
                url += '&page=' + parseInt(options.page);
            }

            if (!isNaN(parseInt(options.limit))) {
                url += '&limit=' + parseInt(options.limit);
            }

            if (typeof(options.filter) == "object") {
                url += '&filter=' + encodeURIComponent(JSON.stringify(options.filter));
            }

            if (typeof(options.query) == "string") {
                url += '&query=' + encodeURIComponent(options.query);
            }

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("documents")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(xml.getElementsByTagName("documents")[0]);
            });
        },
        get : function(section_id, id, callback) {
            var url = '/api/content/document?section_id=' + section_id + '&id=' + id;

            PvRequest.load(url, function (xml) {
                if (xml == null || xml.getElementsByTagName("document")[0] == undefined) {
                    callback({error: true}); //Return an empty object
                    return;
                }
                callback(xml.getElementsByTagName("document")[0]);
            });
        }
    }
})();

Panvista.Util = (function() {
    "use strict";

    return {
        device : null,
        paramKey : 'panvista-param-',
        params : new Object(),
        init : function() {
            for (var i = 0; i < localStorage.length; i++) {
                if (localStorage.key(i).substring(0, Panvista.Util.paramKey.length) == Panvista.Util.paramKey) {
                    Panvista.Util.params[localStorage.key(i)] = localStorage.getItem(localStorage.key(i));
                }
            }
            for (var key in Panvista.Util.params) {
                localStorage.removeItem(key);
            }
        },
        /**
         * Get a list of sections.
         *
         * @param  object    object
         * @param  function  callback
         */
        each : function(object, callback) {
            for (var key in object) {
                if (object.hasOwnProperty(key)) {
                    callback(object[key]);
                }
            }
        },
        /**
         * Get the current device
         *
         * @return string|null
         */
        getDevice : function() {
            if (Panvista.Util.device != null) {
                return Panvista.Util.device;
            }
            if(navigator.userAgent.match(/Android/i)) {
                return 'android';
            }
            if(navigator.userAgent.match(/iPad/i)) {
                return 'ipad';
            }
            if(navigator.userAgent.match(/iPhone|iPod/i)) {
                return 'iphone';
            }
            return null;
        },
        /**
         * Set the current device for the reqeust
         *
         * @param string
         */
        setDevice : function(device) {
            Panvista.Util.device = device;
        },
        /**
         * Set a parameter to be passed through to the next page
         *
         * @param string key
         * @param mixed  value
         */
        setParam : function(key, value) {
            localStorage.setItem(Panvista.Util.paramKey + key, value);
        },
        /**
         * Get a parameter that was passed through from the previous page
         *
         * @param  string key
         * @return mixed
         */
        getParam : function(key) {
            key = Panvista.Util.paramKey + key;
            if (key in Panvista.Util.params) {
                return Panvista.Util.params[key];
            }
            return null;
        },
        parseXml : function(xml) {
            return (new window.DOMParser()).parseFromString(xml, "text/xml");
        }
    };
})();
Panvista.Util.init();

PvRequest = (function() {
    "use strict";

    return {
        load : function(endpoint, callback) {
            var xml    = null,
                result = null;

            switch (endpoint) {
                case '/api/site/sections':
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getSections() : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
                default:
                    result = typeof(sectionsBridge) == "object" ? sectionsBridge.getXmlData(endpoint) : undefined;
                    xml    = typeof(result) != "undefined" ? Panvista.Util.parseXml(result) : null;
                break;
            };

            if (xml && result.length != 0) {
                callback(xml);
                return;
            }

            var request = new XMLHttpRequest();
            var url     = Panvista.Domain + endpoint + (endpoint.indexOf('?') == '-1' ? '?' : '&') + 'version=' + Panvista.ApiVersion + '&device=' + Panvista.Util.getDevice();

            function responseCallback() {
                if(request.readyState < 4) {
                    return;
                }

                if(request.status == 200 && request.readyState === 4) {
                    callback(request.responseXML ? request.responseXML : null);
                    return;
                }

                console.error("Unable to load %s", url);
                callback(null);
            }

            request.onreadystatechange = responseCallback;
            request.open('GET', url, true);
            request.setRequestHeader('X-JSMobileApp-Id', 'PVJSApi');
            request.setRequestHeader('X-JSMobileApp-Version', '0.7');

            if (endpoint.substring(0, 5) == '/xml/') {
                request.setRequestHeader('X-JSMobileApp-Api', '6');
            }

            request.send();
        }
    }
})();<|endoftext|>


<commit_before>var Gificiency = (function() {
  'use strict';

  var searchField = $('.search'),
      items = $('li'),
      links = $('a');

  var search = function(filter) {
    links.each(function() {
      var elem = $(this);
      if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
        elem.hide();
      } else {
        elem.show();
      }
    });
  };

  var getHash = function() {
    var filter;
    if (window.location.hash != '') {
      filter = window.location.hash.substring(1);
    } else {
      filter = false;
    }
    return filter;
  };

  var clearImages = function() {
    $('img').each(function() {
      $(this).remove();
    });
  };

  var popup = function(image) {
    return $('');
  };

  var init = function() {
    if ( getHash() ) {
      search( getHash() );
    }
    events();
  };

  var events = function() {
    searchField.on('keyup', function() {
      search( $(this).val() );
    });

    items.on('mouseover', function() {
      var elem = $(this).find('a'), image = elem.attr('href');
      elem.parent().append( popup(image) );
    }).on('mouseout', function() {
      clearImages();
    });
  };

  var Gificiency = {
    init: init,
    events: events
  };

  return Gificiency;
})();
<commit_msg>Move the init/event methods to the private scope<commit_after>var Gificiency = (function() {
  'use strict';

  var searchField = $('.search'),
      items = $('li'),
      links = $('a');

  var init = function() {
    if ( getHash() ) {
      search( getHash() );
    }
    events();
  };

  var events = function() {
    searchField.on('keyup', function() {
      search( $(this).val() );
    });

    items.on('mouseover', function() {
      var elem = $(this).find('a'), image = elem.attr('href');
      elem.parent().append( popup(image) );
    }).on('mouseout', function() {
      clearImages();
    });
  };

  var search = function(filter) {
    links.each(function() {
      var elem = $(this);
      if (elem.text().search( new RegExp(filter, 'i') ) < 0) {
        elem.hide();
      } else {
        elem.show();
      }
    });
  };

  var getHash = function() {
    var filter;
    if (window.location.hash != '') {
      filter = window.location.hash.substring(1);
    } else {
      filter = false;
    }
    return filter;
  };

  var clearImages = function() {
    $('img').each(function() {
      $(this).remove();
    });
  };

  var popup = function(image) {
    return $('');
  };

  var Gificiency = {
    init: init
  };

  return Gificiency;
})();
<|endoftext|>


<commit_before>// @flow

import * as React from 'react';
import { View, StyleSheet } from 'react-native';

import { threadLabel } from 'lib/shared/thread-utils';
import type { ThreadType } from 'lib/types/thread-types';

import Pill from './pill.react';
import ThreadIcon from './thread-icon.react';

type Props = {|
  +threadType: ThreadType,
  +color: string,
|};
function ThreadVisibility(props: Props) {
  const { threadType, color } = props;
  const label = threadLabel(threadType);
  const icon = React.useMemo(
    () => <ThreadIcon threadType={threadType} color="white" />,
    [threadType],
  );

  return (
    <View style={styles.container}>
      <Pill icon={icon} label={label} backgroundColor={color} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flexDirection: 'row',
  },
});

export default ThreadVisibility;
<commit_msg>[native] Fix `thread-visibility` icon color<commit_after>// @flow

import * as React from 'react';
import { View, StyleSheet } from 'react-native';
import tinycolor from 'tinycolor2';

import { threadLabel } from 'lib/shared/thread-utils';
import type { ThreadType } from 'lib/types/thread-types';

import Pill from './pill.react';
import ThreadIcon from './thread-icon.react';

type Props = {|
  +threadType: ThreadType,
  +color: string,
|};
function ThreadVisibility(props: Props) {
  const { threadType, color } = props;
  const label = threadLabel(threadType);

  const iconColor = React.useMemo(
    () => (tinycolor(color).isDark() ? 'white' : 'black'),
    [color],
  );

  const icon = React.useMemo(
    () => <ThreadIcon threadType={threadType} color={iconColor} />,
    [iconColor, threadType],
  );

  return (
    <View style={styles.container}>
      <Pill icon={icon} label={label} backgroundColor={color} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flexDirection: 'row',
  },
});

export default ThreadVisibility;
<|endoftext|>


<commit_before>// @flow

import type { AppState } from '../redux/redux-setup';
import {
  type InputState,
  inputStatePropType,
  withInputState,
} from '../input/input-state';
import {
  type KeyboardState,
  keyboardStatePropType,
  withKeyboardState,
} from '../keyboard/keyboard-state';
import type { MediaLibrarySelection } from 'lib/types/media-types';

import * as React from 'react';
import PropTypes from 'prop-types';
import { TextInput } from 'react-native';
import { KeyboardAccessoryView } from 'react-native-keyboard-input';
import invariant from 'invariant';

import { connect } from 'lib/utils/redux-utils';

import { styleSelector } from '../themes/colors';
import { mediaGalleryKeyboardName } from '../media/media-gallery-keyboard.react';
import { activeMessageListSelector } from '../navigation/nav-selectors';
import {
  connectNav,
  type NavContextType,
} from '../navigation/navigation-context';

type Props = {|
  textInputRef: ?React.ElementRef<typeof TextInput>,
  // Redux state
  styles: typeof styles,
  activeMessageList: ?string,
  // withKeyboardState
  keyboardState: ?KeyboardState,
  // withInputState
  inputState: ?InputState,
|};
class KeyboardInputHost extends React.PureComponent<Props> {
  static propTypes = {
    textInputRef: PropTypes.instanceOf(TextInput),
    styles: PropTypes.objectOf(PropTypes.object).isRequired,
    activeMessageList: PropTypes.string,
    keyboardState: keyboardStatePropType,
    inputState: inputStatePropType,
  };

  componentDidUpdate(prevProps: Props) {
    if (
      prevProps.activeMessageList &&
      this.props.activeMessageList !== prevProps.activeMessageList
    ) {
      this.hideMediaGallery();
    }
  }

  static mediaGalleryOpen(props: Props) {
    const { keyboardState } = props;
    return !!(keyboardState && keyboardState.mediaGalleryOpen);
  }

  render() {
    const kbComponent = KeyboardInputHost.mediaGalleryOpen(this.props)
      ? mediaGalleryKeyboardName
      : null;
    return (
      <KeyboardAccessoryView
        kbInputRef={this.props.textInputRef}
        kbComponent={kbComponent}
        kbInitialProps={this.props.styles.kbInitialProps}
        onItemSelected={this.onMediaGalleryItemSelected}
        onKeyboardResigned={this.hideMediaGallery}
        manageScrollView={false}
      />
    );
  }

  onMediaGalleryItemSelected = (
    keyboardName: string,
    selections: $ReadOnlyArray<MediaLibrarySelection>,
  ) => {
    const { keyboardState } = this.props;
    invariant(
      keyboardState,
      'keyboardState should be set in onMediaGalleryItemSelected',
    );
    keyboardState.dismissKeyboard();
    const mediaGalleryThreadID = keyboardState.getMediaGalleryThreadID();
    if (mediaGalleryThreadID === null || mediaGalleryThreadID === undefined) {
      return;
    }

    const { inputState } = this.props;
    invariant(
      inputState,
      'inputState should be set in onMediaGalleryItemSelected',
    );
    inputState.sendMultimediaMessage(mediaGalleryThreadID, selections);
  };

  hideMediaGallery = () => {
    const { keyboardState } = this.props;
    invariant(keyboardState, 'keyboardState should be initialized');
    keyboardState.hideMediaGallery();
  };
}

const styles = {
  kbInitialProps: {
    backgroundColor: 'listBackground',
  },
};
const stylesSelector = styleSelector(styles);

export default connect((state: AppState) => ({
  styles: stylesSelector(state),
}))(
  connectNav((context: ?NavContextType) => ({
    activeMessageList: activeMessageListSelector(context),
  }))(withKeyboardState(withInputState(KeyboardInputHost))),
);
<commit_msg>[native] Update TextInput PropType<commit_after>// @flow

import type { AppState } from '../redux/redux-setup';
import {
  type InputState,
  inputStatePropType,
  withInputState,
} from '../input/input-state';
import {
  type KeyboardState,
  keyboardStatePropType,
  withKeyboardState,
} from '../keyboard/keyboard-state';
import type { MediaLibrarySelection } from 'lib/types/media-types';

import * as React from 'react';
import PropTypes from 'prop-types';
import { TextInput } from 'react-native';
import { KeyboardAccessoryView } from 'react-native-keyboard-input';
import invariant from 'invariant';

import { connect } from 'lib/utils/redux-utils';

import { styleSelector } from '../themes/colors';
import { mediaGalleryKeyboardName } from '../media/media-gallery-keyboard.react';
import { activeMessageListSelector } from '../navigation/nav-selectors';
import {
  connectNav,
  type NavContextType,
} from '../navigation/navigation-context';

type Props = {|
  textInputRef: ?React.ElementRef<typeof TextInput>,
  // Redux state
  styles: typeof styles,
  activeMessageList: ?string,
  // withKeyboardState
  keyboardState: ?KeyboardState,
  // withInputState
  inputState: ?InputState,
|};
class KeyboardInputHost extends React.PureComponent<Props> {
  static propTypes = {
    textInputRef: PropTypes.object,
    styles: PropTypes.objectOf(PropTypes.object).isRequired,
    activeMessageList: PropTypes.string,
    keyboardState: keyboardStatePropType,
    inputState: inputStatePropType,
  };

  componentDidUpdate(prevProps: Props) {
    if (
      prevProps.activeMessageList &&
      this.props.activeMessageList !== prevProps.activeMessageList
    ) {
      this.hideMediaGallery();
    }
  }

  static mediaGalleryOpen(props: Props) {
    const { keyboardState } = props;
    return !!(keyboardState && keyboardState.mediaGalleryOpen);
  }

  render() {
    const kbComponent = KeyboardInputHost.mediaGalleryOpen(this.props)
      ? mediaGalleryKeyboardName
      : null;
    return (
      <KeyboardAccessoryView
        kbInputRef={this.props.textInputRef}
        kbComponent={kbComponent}
        kbInitialProps={this.props.styles.kbInitialProps}
        onItemSelected={this.onMediaGalleryItemSelected}
        onKeyboardResigned={this.hideMediaGallery}
        manageScrollView={false}
      />
    );
  }

  onMediaGalleryItemSelected = (
    keyboardName: string,
    selections: $ReadOnlyArray<MediaLibrarySelection>,
  ) => {
    const { keyboardState } = this.props;
    invariant(
      keyboardState,
      'keyboardState should be set in onMediaGalleryItemSelected',
    );
    keyboardState.dismissKeyboard();
    const mediaGalleryThreadID = keyboardState.getMediaGalleryThreadID();
    if (mediaGalleryThreadID === null || mediaGalleryThreadID === undefined) {
      return;
    }

    const { inputState } = this.props;
    invariant(
      inputState,
      'inputState should be set in onMediaGalleryItemSelected',
    );
    inputState.sendMultimediaMessage(mediaGalleryThreadID, selections);
  };

  hideMediaGallery = () => {
    const { keyboardState } = this.props;
    invariant(keyboardState, 'keyboardState should be initialized');
    keyboardState.hideMediaGallery();
  };
}

const styles = {
  kbInitialProps: {
    backgroundColor: 'listBackground',
  },
};
const stylesSelector = styleSelector(styles);

export default connect((state: AppState) => ({
  styles: stylesSelector(state),
}))(
  connectNav((context: ?NavContextType) => ({
    activeMessageList: activeMessageListSelector(context),
  }))(withKeyboardState(withInputState(KeyboardInputHost))),
);
<|endoftext|>


<commit_before>// Copyright 2015, Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var PNGImage = require('../index');

var image = PNGImage.readImageSync(__dirname + '/eye.png');

// Black-out an area
image.fillRect(17, 10, 15, 20, {
	red: 0, green: 0, blue: 0, alpha: 255
});

console.log('Modified!');

image.writeImageSync(__dirname + '/eye_ouput.png');

console.log('Done');
<commit_msg>Fix typo in example<commit_after>// Copyright 2015, Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var PNGImage = require('../index');

var image = PNGImage.readImageSync(__dirname + '/eye.png');

// Black-out an area
image.fillRect(17, 10, 15, 20, {
	red: 0, green: 0, blue: 0, alpha: 255
});

console.log('Modified!');

image.writeImageSync(__dirname + '/eye_output.png');

console.log('Done');
<|endoftext|>


<commit_before>function Ant(a_board) {
    this.row(5);
    this.column(5);
    this.direction('up');
    this.board(a_board);
}

accessor(Ant, "row");
accessor(Ant, "column");
accessor(Ant, "direction");
accessor(Ant, "board");

Ant.prototype.flip_color= function() {
    this.board().cell_color(this.row(), this.column(), 'black');
};

Ant.prototype.turn_right= function() {
    switch(this.direction()) {
    case 'up':
	this.direction('right');
	break;
    case 'left':
	this.direction('up');
	break;
    case 'down':
	this.direction('left');
	break;
    case 'right':
	this.direction('down');
	break;
    }
};

Ant.prototype.move_forward= function() {
    switch(this.direction()) {
    case 'up':
	this.row(4);
	break;
    case 'left':
	this.column(4);
	break;
    case 'down':
	this.row(6);
	break;
    case 'right':
	this.column(6);
	break;
    }
};

Ant.prototype.step= function() {
    this.flip_color();
    this.turn_right();
    this.move_forward();
};
<commit_msg>Specs pass.<commit_after>function Ant(a_board) {
    this.row(5);
    this.column(5);
    this.direction('up');
    this.board(a_board);
}

accessor(Ant, "row");
accessor(Ant, "column");
accessor(Ant, "direction");
accessor(Ant, "board");

Ant.prototype.flip_color= function() {
    this.board().cell_color(this.row(), this.column(), 'black');
};

Ant.prototype.turn_right= function() {
    switch(this.direction()) {
    case 'up':
	this.direction('right');
	break;
    case 'left':
	this.direction('up');
	break;
    case 'down':
	this.direction('left');
	break;
    case 'right':
	this.direction('down');
	break;
    }
};

Ant.prototype.move_forward= function() {
    switch(this.direction()) {
    case 'up':
	this.row(this.row() - 1);
	break;
    case 'left':
	this.column(this.column() - 1);
	break;
    case 'down':
	this.row(this.row() + 1);
	break;
    case 'right':
	this.column(this.column() + 1);
	break;
    }
};

Ant.prototype.step= function() {
    this.flip_color();
    this.turn_right();
    this.move_forward();
};
<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch'

export function fetchImages(page = 1, limit = 10) {
	return fetch(`http://gank.avosapps.com/api/data/%E7%A6%8F%E5%88%A9/${limit}/${page}`)
		.then(data => data.json())
}
<commit_msg>use https<commit_after>import fetch from 'isomorphic-fetch'

export function fetchImages(page = 1, limit = 10) {
	return fetch(`https://gank.avosapps.com/api/data/%E7%A6%8F%E5%88%A9/${limit}/${page}`)
		.then(data => data.json())
}
<|endoftext|>