<commit_before>var ENEMY_DX = 1;
var ENEMY_DY = 20;

Object.prototype.isEmpty = function() {
    for (var prop in this) if (this.hasOwnProperty(prop)) return false;
    return true;
};

// Enemy Class
var Enemy = function(posX, posY, num) {
    this.x = posX;
    this.y = posY;
    this.dy = 0;
    this.dx = 1;
    this.num = num;
    this.population = 56;
    this.width = 65;
    this.height = 70;
    this.display = true;
    this.sprite = 'images/enemy1.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    var movement = (ENEMY_DX * this.population) * dt;
    this.x += movement;
    this.y += this.dy * dt;

    if (this.x >= 1200 - 91 || this.x <= 0) {
        ENEMY_DX = -ENEMY_DX;
        allEnemies.forEach(function(allEnemy) {
        allEnemy.y += ENEMY_DY;
        allEnemy.x += ENEMY_DX;
        });
    }

	// Enemies will come out of alignment due to position not updating
	// at exacty the same time. This will keep them aligned
    if (this.num > 7) {
        this.x = allEnemies[this.num - 8].x;
    }

    if (this.num % 8 > 0) {
        this.x = allEnemies[this.num - 1].x + 135
    }

	// Balance enemy shooting by having each enemy only have a small
	// chance of firing
    var rand = Math.floor((Math.random() * 2500) + 1);
	if (rand === this.num && this.display === true) {
        this.shoot();
	}
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    if (this.display === true) {
        ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
    }
};

Enemy.prototype.move = function() {

};

Enemy.prototype.shoot = function() {
     bullets.push(new Bullet(this.x,this.y,"enemy",bullets.length));
};

Enemy.prototype.testCollision = function(enemy) {

    var collisionNum = -1

    bullets.forEach(function(bullet) {

        if (bullet.type === "player" && enemy.display === true) {

            if (collisionTest(enemy,bullet)) {
                enemy.display = false;
                collisionNum = bullet.num;
            }
        }

        if (enemy.y > (725 - enemy.height) && enemy.display === true) {
            barriers.forEach(function(barrier) {

                if (collisionTest(enemy,barrier) && barrier.display === true) {
                    enemy.display = false;
                    barrier.health -= 1;
                }
            });
        }

    });

    if (collisionTest(enemy,player)) {
        enemy.display = false;
        player.live -= 1;
    }

    return collisionNum;
}

var calcHeight = function (count) {
   if (count <= 8) {
    return 50;
   } else if (count <= 16) {
    return 70 + 81;
   } else if (count <= 24) {
    return 90 + (2 * 81);
   } else if (count <= 32) {
    return 110 + (3 * 81);
   } else if (count <= 40) {
    return 130 + (4 * 81);
   } else if (count <= 48) {
    return 150 + (5 * 81);
   }
}

// Player Class
var Player = function() {
    this.sprite = 'images/player.png';
    this.x = 600;
    this.y = 820;
    this.dx = 0;
    this.dy = 0;
    this.width = 77;
    this.height = 52;
    this.lives = 3;
    this.score = 0;
};

Player.prototype.update = function(dt) {
    this.x += this.dx * dt;
    if (this.x < 20) {
        this.x = 20;
    } else if (this.x > 1060) {
        this.x = 1060;
    }
};

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Player.prototype.handleInput = function(input) {
    if (keyboard['\%']) {
        this.dx = -100;
    } else if (keyboard["'"]) {
        this.dx = 100;
    } else if (keyboard.isEmpty) {
        this.dx = 0;
    }

    if (input === 'ctrl') {
        this.shoot();
    }
};

Player.prototype.shoot = function() {
    bullets.push(new Bullet(this.x + this.width / 2,this.y - this.height,"player", bullets.length));
};

// Bullet class
var Bullet = function(posX,posY,type, num) {
    this.x = posX;
    this.y = posY;
    this.dx = 0;
    this.dy = 0;
    this.width = 5;
    this.height = 66;
    this.type = type;
    this.num = num;
    this.sprite = 'images/bullet.png';
};

Bullet.prototype.update = function(dt) {
    this.y += this.dy * dt;
};

Bullet.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite),this.x, this.y);
};

Bullet.prototype.move = function() {
    if (this.type === "player") {
        this.dy = -200;
    } else if (this.type === "enemy") {
        this.dy = 200;
    }
}

Bullet.prototype.testCollision = function(bullet) {

    var collisionNum = -1;

    if (bullet.y > 900 || bullet.y < 0) {
        collisionNum = bullet.num;
    }

    if (bullet.type === 'enemy' && bullet.y > 700) {

        if (collisionTest(player,bullet)) {
            player.lives -= 1;
            collisionNum = bullet.num;
        }
    }

    if (bullet.y > 650) {

        barriers.forEach(function(barrier) {

            if (collisionTest(bullet,barrier) && barrier.display === true) {
                barrier.health -= 1;
                collisionNum = bullet.num;
            }
        });
    }

    return collisionNum;
}

// Barrier class
var Barrier = function(posX, posY) {
    this.x = posX
    this.y = posY;
    this.width = 92;
    this.height = 69;
    this.health = 10;
    this.display = true;
    this.sprite = 'images/barrier_full.png';

};

Barrier.prototype.update = function() {
    if (this.health === 0) {
        this.display = false;
    }else if (this.health <= 2) {
        this.sprite = 'images/barrier_most.png';
        this.width = 90;
        this.height = 52;
    } else if (this.health <= 4) {
        this.sprite = 'images/barrier_serious.png';
        this.width = 90;
        this.height = 57;
    } else if (this.health <= 6) {
        this.sprite = 'images/barrier_more.png';
    } else if (this.health <= 8) {
        this.sprite = 'images/barrier_slight.png';
    }
};

Barrier.prototype.render= function() {
    if (this.display === true) {
        // we take the difference between the current and original dimensions in order
        // to stop them from shifting around
        ctx.drawImage(Resources.get(this.sprite),this.x + (92 - this.width), this.y + (69 - this.height));
    }
};

// HUD class
var HUD = function() {
    this.score = score;
    this.lives = lives;

};

HUD.prototype.update = function() {

};

HUD.prototype.render = function() {

};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [];
var barriers = [];
var bullets = []

var player = new Player();
//var hud = new HUD();

for (var x = 0; x < 49; x++) { allEnemies[x] = new Enemy(91 + 135 * (allEnemies.length % 8), calcHeight(x), x); }
for (var x = 0; x < 3; x++) {barriers[x] = new Barrier(230 + (x * 300),725)}

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keydown', function(e) {
    var allowedKeys = {
        17: 'ctrl',
        37: 'left',
        39: 'right'

    };

    player.handleInput(allowedKeys[e.keyCode]);
});

// keyboard_module by RobKohr
// Properly handles when a key is held down and then released
function keyboard_module(onUpdate){
    var kb = {};
    var unicode_mapping = {};
    document.onkeydown = function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        kb[key] = true;
        if(onUpdate){
            onUpdate(kb);
        }
    }

    document.onkeyup = function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        delete kb[key];
        if(onUpdate){
            onUpdate(kb);
        }
    }

    function getKey(unicode){
        if(unicode_mapping[unicode]){
            var key = unicode_mapping[unicode];
        }else{
            var key= unicode_mapping[unicode] = String.fromCharCode(unicode);
        }
        return key;
    }
    return kb;
}

function testing(kb){
    //console.log('These are the down keys', kb);
}

function collisionTest(obj1,obj2) {
    if (obj1.x < obj2.x + obj2.width &&
        obj1.x + obj1.width > obj2.x &&
        obj1.y < obj2.y + obj2.height &&
        obj1.height + obj1.y > obj2.y) {

            return true;
        }
    }

function deleteBullets(nums) {
    nums.forEach(function(num) {
        bullets.splice(num,1);
    });

    for (var i = 0; i < bullets.length; i++) {
        bullets[i].num = i;
    }
}

var keyboard = keyboard_module();

<commit_msg>bug: player can no longer spam bullets<commit_after>var ENEMY_DX = 1;
var ENEMY_DY = 20;

Object.prototype.isEmpty = function() {
    for (var prop in this) if (this.hasOwnProperty(prop)) return false;
    return true;
};

// Enemy Class
var Enemy = function(posX, posY, num) {
    this.x = posX;
    this.y = posY;
    this.dy = 0;
    this.dx = 1;
    this.num = num;
    this.population = 56;
    this.width = 65;
    this.height = 70;
    this.display = true;
    this.sprite = 'images/enemy1.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    var movement = (ENEMY_DX * this.population) * dt;
    this.x += movement;
    this.y += this.dy * dt;

    if (this.x >= 1200 - 91 || this.x <= 0) {
        ENEMY_DX = -ENEMY_DX;
        allEnemies.forEach(function(allEnemy) {
        allEnemy.y += ENEMY_DY;
        allEnemy.x += ENEMY_DX;
        });
    }

	// Enemies will come out of alignment due to position not updating
	// at exacty the same time. This will keep them aligned
    if (this.num > 7) {
        this.x = allEnemies[this.num - 8].x;
    }

    if (this.num % 8 > 0) {
        this.x = allEnemies[this.num - 1].x + 135
    }

	// Balance enemy shooting by having each enemy only have a small
	// chance of firing
    var rand = Math.floor((Math.random() * 2500) + 1);
	if (rand === this.num && this.display === true) {
        this.shoot();
	}
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    if (this.display === true) {
        ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
    }
};

Enemy.prototype.move = function() {

};

Enemy.prototype.shoot = function() {
     bullets.push(new Bullet(this.x,this.y,"enemy",bullets.length));
};

Enemy.prototype.testCollision = function(enemy) {

    var collisionNum = -1

    bullets.forEach(function(bullet) {

        if (bullet.type === "player" && enemy.display === true) {

            if (collisionTest(enemy,bullet)) {
                player.shot = false;
                enemy.display = false;
                collisionNum = bullet.num;
            }
        }

        if (enemy.y > (725 - enemy.height) && enemy.display === true) {
            barriers.forEach(function(barrier) {

                if (collisionTest(enemy,barrier) && barrier.display === true) {
                    enemy.display = false;
                    barrier.health -= 1;
                }
            });
        }

    });

    if (collisionTest(enemy,player)) {
        enemy.display = false;
        player.live -= 1;
    }

    return collisionNum;
}

var calcHeight = function (count) {
   if (count <= 8) {
    return 50;
   } else if (count <= 16) {
    return 70 + 81;
   } else if (count <= 24) {
    return 90 + (2 * 81);
   } else if (count <= 32) {
    return 110 + (3 * 81);
   } else if (count <= 40) {
    return 130 + (4 * 81);
   } else if (count <= 48) {
    return 150 + (5 * 81);
   }
}

// Player Class
var Player = function() {
    this.sprite = 'images/player.png';
    this.x = 600;
    this.y = 820;
    this.dx = 0;
    this.dy = 0;
    this.width = 77;
    this.height = 52;
    this.lives = 3;
    this.score = 0;
    this.shot = false;
};

Player.prototype.update = function(dt) {
    this.x += this.dx * dt;
    if (this.x < 20) {
        this.x = 20;
    } else if (this.x > 1060) {
        this.x = 1060;
    }
};

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Player.prototype.handleInput = function(input) {
    if (keyboard['\%']) {
        this.dx = -100;
    } else if (keyboard["'"]) {
        this.dx = 100;
    } else if (keyboard.isEmpty) {
        this.dx = 0;
    }

    if (input === 'ctrl') {
        this.shoot();
    }
};

Player.prototype.shoot = function() {
    if (this.shot === false) {
        console.log(this.shot);
        bullets.push(new Bullet(this.x + this.width / 2,this.y - this.height,"player", bullets.length));
        this.shot = true;
    }
};

// Bullet class
var Bullet = function(posX,posY,type, num) {
    this.x = posX;
    this.y = posY;
    this.dx = 0;
    this.dy = 0;
    this.width = 5;
    this.height = 66;
    this.type = type;
    this.num = num;
    this.sprite = 'images/bullet.png';
};

Bullet.prototype.update = function(dt) {
    this.y += this.dy * dt;
};

Bullet.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite),this.x, this.y);
};

Bullet.prototype.move = function() {
    if (this.type === "player") {
        this.dy = -200;
    } else if (this.type === "enemy") {
        this.dy = 200;
    }
}

Bullet.prototype.testCollision = function(bullet) {

    var collisionNum = -1;

    if (bullet.y > 900 || bullet.y < 0) {
        collisionNum = bullet.num;

        if (bullet.type === "player") {
            player.shot = false;
        }
    }

    if (bullet.type === 'enemy' && bullet.y > 700) {

        if (collisionTest(player,bullet)) {
            player.lives -= 1;
            collisionNum = bullet.num;
        }
    }

    if (bullet.y > 650) {

        barriers.forEach(function(barrier) {

            if (collisionTest(bullet,barrier) && barrier.display === true) {
                barrier.health -= 1;
                collisionNum = bullet.num;
                console.log(this.type);
                if (bullet.type === "player") {
                    player.shot = false;
                 }
            }
        });
    }

    return collisionNum;
}

// Barrier class
var Barrier = function(posX, posY) {
    this.x = posX
    this.y = posY;
    this.width = 92;
    this.height = 69;
    this.health = 10;
    this.display = true;
    this.sprite = 'images/barrier_full.png';

};

Barrier.prototype.update = function() {
    if (this.health === 0) {
        this.display = false;
    }else if (this.health <= 2) {
        this.sprite = 'images/barrier_most.png';
        this.width = 90;
        this.height = 52;
    } else if (this.health <= 4) {
        this.sprite = 'images/barrier_serious.png';
        this.width = 90;
        this.height = 57;
    } else if (this.health <= 6) {
        this.sprite = 'images/barrier_more.png';
    } else if (this.health <= 8) {
        this.sprite = 'images/barrier_slight.png';
    }
};

Barrier.prototype.render= function() {
    if (this.display === true) {
        // we take the difference between the current and original dimensions in order
        // to stop them from shifting around
        ctx.drawImage(Resources.get(this.sprite),this.x + (92 - this.width), this.y + (69 - this.height));
    }
};

// HUD class
var HUD = function() {
    this.score = score;
    this.lives = lives;

};

HUD.prototype.update = function() {

};

HUD.prototype.render = function() {

};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [];
var barriers = [];
var bullets = []

var player = new Player();
//var hud = new HUD();

for (var x = 0; x < 49; x++) { allEnemies[x] = new Enemy(91 + 135 * (allEnemies.length % 8), calcHeight(x), x); }
for (var x = 0; x < 3; x++) {barriers[x] = new Barrier(230 + (x * 300),725)}

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keydown', function(e) {
    var allowedKeys = {
        17: 'ctrl',
        37: 'left',
        39: 'right'

    };

    player.handleInput(allowedKeys[e.keyCode]);
});

// keyboard_module by RobKohr
// Properly handles when a key is held down and then released
function keyboard_module(onUpdate){
    var kb = {};
    var unicode_mapping = {};
    document.onkeydown = function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        kb[key] = true;
        if(onUpdate){
            onUpdate(kb);
        }
    }

    document.onkeyup = function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        delete kb[key];
        if(onUpdate){
            onUpdate(kb);
        }
    }

    function getKey(unicode){
        if(unicode_mapping[unicode]){
            var key = unicode_mapping[unicode];
        }else{
            var key= unicode_mapping[unicode] = String.fromCharCode(unicode);
        }
        return key;
    }
    return kb;
}

function testing(kb){
    //console.log('These are the down keys', kb);
}

function collisionTest(obj1,obj2) {
    if (obj1.x < obj2.x + obj2.width &&
        obj1.x + obj1.width > obj2.x &&
        obj1.y < obj2.y + obj2.height &&
        obj1.height + obj1.y > obj2.y) {

            return true;
        }
    }

function deleteBullets(nums) {
    nums.forEach(function(num) {
        bullets.splice(num,1);
    });

    for (var i = 0; i < bullets.length; i++) {
        bullets[i].num = i;
    }
}

var keyboard = keyboard_module();

<|endoftext|>


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

"use strict"

define(['config', 'extensions', 'backbone', 'underscore', 'models/dropbox', 'models/loops', 'views/alerts', 'views/navbar', 'views/createform', 'views/controls', 'views/loops', 'views/looputilitybuttons', 'views/status'], function(Config, Extensions, Backbone, _, Dropbox, Loops, AlertsView, NavBarView, CreateFormView, ControlsView, LoopsView, LoopUtilityButtonsView, StatusView) {

    var App = function() {

        this.config = Config;
        this.views = {};
        this.models = {};
        this.dispatcher = _.clone(Backbone.Events);
        this.dispatcher.on('all', function(eventName) {
            console.log(eventName + ' triggered');
        });

        /**
         * The app start.
         */
        this.start = function() {
            var app = this;
            var extensions = new Extensions();

            /**
             * Apply extensions.
             */
            extensions.backbone(app);

            /**
             * The necessary models.
             */
            app.models.dropBox = new Dropbox({key: app.config.dropboxAPIKey, receiverURL: app.config.oAuthReceiverURL});

            /**
             * The necessary views.
             */
            app.views.navbar = new NavBarView({model: app.models.dropBox});
            app.views.createForm = new CreateFormView({attributes: {dropboxDropinKey: app.config.dropboxDropinKey}});
            app.views.controls = new ControlsView();
            app.views.alerts = new AlertsView();
            app.views.loops = new LoopsView({model: new Loops()});
            app.views.looputilitybuttons = new LoopUtilityButtonsView();
            app.views.status = new StatusView();

            // authenticate to Dropbox without interaction, in case the user has cached credentials
            app.models.dropBox.auth({interactive: false});
        };
    };

    return App;
});
<commit_msg>Changed to LooperSaveView in app view creations.<commit_after>/**
 *
 *
 *
 *
 */

"use strict"

define(['config', 'extensions', 'backbone', 'underscore', 'models/dropbox', 'models/loops', 'views/alerts', 'views/navbar', 'views/createform', 'views/controls', 'views/loops', 'views/loopersave', 'views/status'], function(Config, Extensions, Backbone, _, Dropbox, Loops, AlertsView, NavBarView, CreateFormView, ControlsView, LoopsView, LooperSaveView, StatusView) {

    var App = function() {

        this.config = Config;
        this.views = {};
        this.models = {};
        this.dispatcher = _.clone(Backbone.Events);
        this.dispatcher.on('all', function(eventName) {
            console.log(eventName + ' triggered');
        });

        /**
         * The app start.
         */
        this.start = function() {
            var app = this;
            var extensions = new Extensions();

            /**
             * Apply extensions.
             */
            extensions.backbone(app);

            /**
             * The necessary models.
             */
            app.models.dropBox = new Dropbox({key: app.config.dropboxAPIKey, receiverURL: app.config.oAuthReceiverURL});

            /**
             * The necessary views.
             */
            app.views.navbar = new NavBarView({model: app.models.dropBox});
            app.views.createForm = new CreateFormView({attributes: {dropboxDropinKey: app.config.dropboxDropinKey}});
            app.views.controls = new ControlsView();
            app.views.alerts = new AlertsView();
            app.views.loops = new LoopsView({model: new Loops()});
            app.views.loopersave = new LooperSaveView();
            app.views.status = new StatusView();

            // authenticate to Dropbox without interaction, in case the user has cached credentials
            app.models.dropBox.auth({interactive: false});
        };
    };

    return App;
});
<|endoftext|>


<commit_before>// Enemies our player must avoid
var Enemy = function(x, y, xSpeed) {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = x;
    this.y = y;
    this.xSpeed = xSpeed;

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.

        // Initialize the bug
        // - End of the screen (reset)

    if (this.x > 505)  {
        this.x = 0;
        this.xSpeed = randomSpeed();
        this.y = randomHeight();
    }
    this.x = this.x + this.xSpeed * dt ;
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.

var Player = function(x,y) {
    this.x = x;
    this.y = y;
    this.sprite = 'images/char-boy.png';
};

Player.prototype.update = function() {
    this.handleInput();
};

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Player.prototype.handleInput = function(_input) {
    // The max and the min are there to secure the limits of the canvas

    if (_input === 'left') {
        this.x = Math.max(this.x - 101, 0 );
    }

    if (_input === 'right') {
        this.x = Math.min(this.x + 101, 400);
    }

    if (_input === 'up') {
        this.y = Math.max(this.y - 83, 0 );
    }

    if (_input === 'down') {
        this.y = Math.min(this.y + 83, 405 );
    }

};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player

var allEnemies= []

var Enemy1 = new Enemy(0, randomHeight(), randomSpeed());
var Enemy2 = new Enemy(0, randomHeight(), randomSpeed());
var Enemy3 = new Enemy(0, randomHeight(), randomSpeed());

allEnemies.push(Enemy1);
allEnemies.push(Enemy2);
allEnemies.push(Enemy3);

var player = new Player(200, 405);

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});

// Randomize Speed and position of the bugs to make it less calculated

function randomSpeed() {
    var speed = Math.floor(Math.random()*16) * 12.5 + 150;

    return speed
}

function randomHeight() {
    var pos = Math.floor(Math.random()*3) * 80 + 60;

    return pos;
}

// Add the checkCollisions function
// Current status is simple restart the player position

function checkCollisions() {
    allEnemies.forEach(function(enemy){
        if ((Math.abs(player.x - enemy.x ) < 60) && (Math.abs(player.y - enemy.y) <40)) {
            player.x =  200;
            player.y =  405;

            // Check the amount of lives
        };
    });

    if (player.y <= 71) {
        player.x =  200;
        player.y =  405;
    }
} <commit_msg>Add scoring system (Rudimentary)<commit_after>// Enemies our player must avoid
var Enemy = function(x, y, xSpeed) {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = x;
    this.y = y;
    this.xSpeed = xSpeed;

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.

        // Initialize the bug
        // - End of the screen (reset)

    if (this.x > 505)  {
        this.x = 0;
        this.xSpeed = randomSpeed();
        this.y = randomHeight();
    }
    this.x = this.x + this.xSpeed * dt ;
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.

var Player = function(x,y) {
    this.x = x;
    this.y = y;

    this.score = 0;
    this.sprite = 'images/char-boy.png';
};

Player.prototype.update = function() {
    this.handleInput();

};

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);

    player.score = increaseScore(player.score);

};

Player.prototype.handleInput = function(_input) {
    // The max and the min are there to secure the limits of the canvas

    if (_input === 'left') {
        this.x = Math.max(this.x - 101, 0 );
    }

    if (_input === 'right') {
        this.x = Math.min(this.x + 101, 400);
    }

    if (_input === 'up') {
        this.y = Math.max(this.y - 83, 0 );
    }

    if (_input === 'down') {
        this.y = Math.min(this.y + 83, 405 );
    }

};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player

var allEnemies= []

var Enemy1 = new Enemy(0, randomHeight(), randomSpeed());
var Enemy2 = new Enemy(0, randomHeight(), randomSpeed());
var Enemy3 = new Enemy(0, randomHeight(), randomSpeed());

allEnemies.push(Enemy1);
allEnemies.push(Enemy2);
allEnemies.push(Enemy3);

var player = new Player(200, 405);

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});

// Randomize Speed and position of the bugs to make it less calculated

function randomSpeed() {
    var speed = Math.floor(Math.random()*16) * 12.5 + 150;

    return speed
}

function randomHeight() {
    var pos = Math.floor(Math.random()*3) * 80 + 60;

    return pos;
}

// Add the checkCollisions function
// Current status is simple restart the player position

function checkCollisions() {
    allEnemies.forEach(function(enemy){
        if ((Math.abs(player.x - enemy.x ) < 60) && (Math.abs(player.y - enemy.y) <40)) {
            player.x =  200;
            player.y =  405;
            player.score = player.score - 5;

            // Check the amount of lives
        };
    });

    if (player.y <= 71) {
        player.x =  200;
        player.y =  405;
        player.score = player.score + 10;

    }
}

// Add a score

function increaseScore(_input){
    // no points if player on the grass (y >= 322)
    if (player.y < 322){
        _input = _input + 1/100;
    }

    // Change style color

    if(_input >=0 ) {
        ctx.fillStyle = "green";
    } else {
        ctx.fillStyle = "red";
    }

    ctx.font = "18pt Impact";

    ctx.fillText('Points: ' + Math.floor(_input), 10, 90);
    ctx.lineWidth = 2;
    ctx.strokeText('Points: ' + Math.floor(_input), 10, 90);

    return _input;

}
<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");
              //  $('ruleset-list').html(snippets.List_Rulesets_template());

              Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
              console.log(rids_json);

             // var keys = rids_json.sort(sortBy("rid"));
             // $.each(keys, format_rids_paint);// paint will call $('#ruleset-list').apend......

              //this is for a table
              /*
              var len = rids_json.length;
              var txt = "";
              if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+rids_json[i].rid+"	"+rids_json[i].uri+"	button
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").html(txt);
                        $("#ruleset-list").listview('refresh');
                  }
                else{
                    $("#ruleset-list").html("
 NONE 	 NONE 	");
                    $("#ruleset-list").listview('refresh');
                }
              } */

              //trying for a list

              console.log("attempting rough listview");

              var keys = rids_json.sort(sortBy("rid"));
              $.each(keys, paint_item);

              $('#manage-list').listview('refresh');
                });

          //var obj_json = '[{"rid":"b506607x0.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl"},{"rid_index":0,"last_modified":1418237853,"rid":"b506607x0.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl","prefix":"b506607"},{"rid":"b506607x1.dev","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":1,"last_modified":1418234018,"rid":"b506607x1.prod","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"last_modified":1422397298,"rid":"b506607x10.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":10,"last_modified":1423525230,"rid":"b506607x10.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"rid":"b506607x11.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":11,"last_modified":1418237853,"rid":"b506607x11.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"last_modified":1418234156,"rid":"b506607x12.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl"},{"rid_index":12,"rid":"b506607x12.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl","prefix":"b506607"},{"last_modified":1418238023,"rid":"b506607x13.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl"},{"rid_index":13,"rid":"b506607x13.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl","prefix":"b506607"},{"last_modified":1423689382,"rid":"b506607x14.dev","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl"},{"rid_index":14,"last_modified":1423525738,"rid":"b506607x14.prod","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl","prefix":"b506607"},{"last_modified":1412788749,"rid":"b506607x2.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":2,"last_modified":1418234018,"rid":"b506607x2.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"rid":"b506607x3.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl"},{"rid_index":3,"last_modified":1418237852,"rid":"b506607x3.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl","prefix":"b506607"},{"rid":"b506607x4.dev","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl"},{"rid_index":4,"last_modified":1418234018,"rid":"b506607x4.prod","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl","prefix":"b506607"},{"rid":"b506607x5.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes"},{"rid_index":5,"last_modified":1418234018,"rid":"b506607x5.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x6.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl"},{"rid_index":6,"last_modified":1421736146,"rid":"b506607x6.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl","prefix":"b506607"},{"rid":"b506607x7.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl"},{"rid_index":7,"last_modified":1418237852,"rid":"b506607x7.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl","prefix":"b506607"},{"rid":"b506607x8.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl"},{"rid_index":8,"last_modified":1418237852,"rid":"b506607x8.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x9.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl"},{"rid_index":9,"last_modified":1421862708,"rid":"b506607x9.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl","prefix":"b506607"}]';
          // var rids_json = JSON.parse(obj_json);
          // document.getElementById("List-Rulesets").innerHTML = obj;

            //$("#List-Rulesets").html("
"+ruleset_obj+"
");
            //$('#List-Rulesets').listview('refresh');

            //console.log(rids_json.rid);
            //console.log(ruleset_obj.rid);

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });
      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
        list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
	CloudOS.retrieveSession();
	// only put static stuff here...
	plant_authorize_button();

	$('.logout').off("tap").on("tap", function(event)
	   {
	       CloudOS.removeSession(true); // true for hard reset (log out of login server too)
	       $.mobile.changePage('#page-authorize', {
		   transition: 'slide'
	       }); // this will go to the authorization page.
	   });

	console.log("Choose page to show");

	try {
	    var authd = CloudOS.authenticatedSession();
	    if(authd) {
		console.log("Authorized");
		document.location.hash = "#home";
	    } else {
		console.log("Asking for authorization");
		document.location.hash = "#page-authorize";
	    }
	} catch (exception) {

	} finally {
	    $.mobile.initializePage();
	    $.mobile.loading("hide");
	}

    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);

    function paint_item(id, vehicle) {

          /*if (typeof vehicle === "undefined") {
        return;
          }*/

        $("#manage-list li:nth-child(1)" ).after( //was #manage-fleet prior
            snippets.list_rulesets_template(
              {"rid": vehicle.profileName,
               "uri": id,
               "description": status
              }));
    };

<commit_msg>sortBy is undefined<commit_after>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");
              //  $('ruleset-list').html(snippets.List_Rulesets_template());

              Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
              console.log(rids_json);

             // var keys = rids_json.sort(sortBy("rid"));
             // $.each(keys, format_rids_paint);// paint will call $('#ruleset-list').apend......

              //this is for a table
              /*
              var len = rids_json.length;
              var txt = "";
              if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+rids_json[i].rid+"	"+rids_json[i].uri+"	button
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").html(txt);
                        $("#ruleset-list").listview('refresh');
                  }
                else{
                    $("#ruleset-list").html("
 NONE 	 NONE 	");
                    $("#ruleset-list").listview('refresh');
                }
              } */

              //trying for a list

              console.log("attempting rough listview");

              var keys = rids_json; // .sort(sortBy("rid"));
              $.each(keys, paint_item);

              $('#manage-list').listview('refresh');
                });

          //var obj_json = '[{"rid":"b506607x0.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl"},{"rid_index":0,"last_modified":1418237853,"rid":"b506607x0.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl","prefix":"b506607"},{"rid":"b506607x1.dev","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":1,"last_modified":1418234018,"rid":"b506607x1.prod","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"last_modified":1422397298,"rid":"b506607x10.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":10,"last_modified":1423525230,"rid":"b506607x10.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"rid":"b506607x11.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":11,"last_modified":1418237853,"rid":"b506607x11.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"last_modified":1418234156,"rid":"b506607x12.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl"},{"rid_index":12,"rid":"b506607x12.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl","prefix":"b506607"},{"last_modified":1418238023,"rid":"b506607x13.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl"},{"rid_index":13,"rid":"b506607x13.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl","prefix":"b506607"},{"last_modified":1423689382,"rid":"b506607x14.dev","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl"},{"rid_index":14,"last_modified":1423525738,"rid":"b506607x14.prod","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl","prefix":"b506607"},{"last_modified":1412788749,"rid":"b506607x2.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":2,"last_modified":1418234018,"rid":"b506607x2.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"rid":"b506607x3.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl"},{"rid_index":3,"last_modified":1418237852,"rid":"b506607x3.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl","prefix":"b506607"},{"rid":"b506607x4.dev","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl"},{"rid_index":4,"last_modified":1418234018,"rid":"b506607x4.prod","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl","prefix":"b506607"},{"rid":"b506607x5.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes"},{"rid_index":5,"last_modified":1418234018,"rid":"b506607x5.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x6.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl"},{"rid_index":6,"last_modified":1421736146,"rid":"b506607x6.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl","prefix":"b506607"},{"rid":"b506607x7.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl"},{"rid_index":7,"last_modified":1418237852,"rid":"b506607x7.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl","prefix":"b506607"},{"rid":"b506607x8.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl"},{"rid_index":8,"last_modified":1418237852,"rid":"b506607x8.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x9.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl"},{"rid_index":9,"last_modified":1421862708,"rid":"b506607x9.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl","prefix":"b506607"}]';
          // var rids_json = JSON.parse(obj_json);
          // document.getElementById("List-Rulesets").innerHTML = obj;

            //$("#List-Rulesets").html("
"+ruleset_obj+"
");
            //$('#List-Rulesets').listview('refresh');

            //console.log(rids_json.rid);
            //console.log(ruleset_obj.rid);

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });
      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
        list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
	CloudOS.retrieveSession();
	// only put static stuff here...
	plant_authorize_button();

	$('.logout').off("tap").on("tap", function(event)
	   {
	       CloudOS.removeSession(true); // true for hard reset (log out of login server too)
	       $.mobile.changePage('#page-authorize', {
		   transition: 'slide'
	       }); // this will go to the authorization page.
	   });

	console.log("Choose page to show");

	try {
	    var authd = CloudOS.authenticatedSession();
	    if(authd) {
		console.log("Authorized");
		document.location.hash = "#home";
	    } else {
		console.log("Asking for authorization");
		document.location.hash = "#page-authorize";
	    }
	} catch (exception) {

	} finally {
	    $.mobile.initializePage();
	    $.mobile.loading("hide");
	}

    };

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);

    function paint_item(id, vehicle) {

          /*if (typeof vehicle === "undefined") {
        return;
          }*/

        $("#manage-list li:nth-child(1)" ).after( //was #manage-fleet prior
            snippets.list_rulesets_template(
              {"rid": vehicle.profileName,
               "uri": id,
               "description": status
              }));
    };

<|endoftext|>


<commit_before>'use strict';

(function() {
  function repoName() {
    return $('#repositoryName').val().toString();
  }

  function renderListView() {
    var repo = repoName();
    if(!repo || repo === "") {
      return;
    }
    var db = new PouchDB(repo);
    db.allDocs({ include_docs: true })
      .then(function(docs) {
        $(".issue-list").empty();
        var plainDocs = _.map(docs.rows, function(d) { return d.doc; });
        var views = _.map(plainDocs, renderIssueView);
        $(".issue-list").append(views);
      });

    function renderIssueView(issue) {
      var container = $("");
      var heading = $("

")
      container.attr('id', issue.id);
      heading.html(issue.title);
      container.append(heading);
      container.click(showIssueDetail);
      return container;
    }

    function showIssueDetail(ev) {
      var id = $(this).attr('id');
      var db = new PouchDB(repoName());
      db.get(id)
        .then(function(issue) {
          var container = $('.issue-detail');
          var backButton = $("
<button>Back</button>
");
          backButton.click(hideIssueDetails);
          container.append(backButton);

          var title = $("

"+ issue.title +"

");
          var issueNumber = $("

#"+ issue.number +"

");
          var text = $("

" + issue.body + "

");
          container.append(issueNumber);
          container.append(title);
          container.append($("
"));
          container.append(text);
          $(container).show();
          $(".issue-list").hide();
        })
        .catch(function(err) {
          console.log("ERR", err);
        });
    }

    function hideIssueDetails() {
      $(".issue-list").show();
      $(".issue-detail").hide();
      $(".issue-detail").empty();
    }
  }

  function fetchIssues(ev) {
    ev.preventDefault();
    var repo = repoName();
    if(!repo || repo === "") {
      return;
    }

    var gh = new GitHub();
    var issueHandle = gh.getIssues(repo);
    issueHandle.listIssues({}, function(_none, issues) {
      var db = new PouchDB(repo);
      db.bulkDocs(_.map(issues, setDocId))
      .then(function() {
          renderListView();
      })
      .catch(function(err){
        console.log("ERR", err);
      });
    });

    function setDocId(issue) {
      issue['_id'] = issue.id.toString();
      return issue;
    }
  }

  function registerServiceWorker() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js').then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      }).catch(function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
      });
    }
  }

  function loadAvailableRepositories() {
    PouchDB.allDbs().then(function (dbs) {
      var dbEntries = dbs.map(function(db) {
        return $("" + db + "");
      });
      $(".repository-list").append(dbEntries);
    }).catch(function (err) {
      // handle err
      console.error("Failed to fetch all databases", err);
    });
  }

  $(document).ready(function() {
    registerServiceWorker();
    $('.fetch-issues').click(fetchIssues);
    loadAvailableRepositories();
    renderListView();
  });
})();<commit_msg>show issues from local pouchdb<commit_after>'use strict';

(function() {
  function repoName() {
    return $('#repositoryName').val().toString();
  }

  function renderListView(repoName) {
    if(!repoName) {
      throw new Error("expected repoName");
    }
    var db = new PouchDB(repoName);
    db.allDocs({ include_docs: true })
      .then(function(docs) {
        $(".issue-list").empty();
        var plainDocs = _.map(docs.rows, function(d) { return d.doc; });
        var views = _.map(plainDocs, renderIssueView);
        $(".issue-list").append(views);
      });

    function renderIssueView(issue) {
      var container = $("");
      var heading = $("

")
      container.attr('id', issue.id);
      heading.html(issue.title);
      container.append(heading);
      container.click(showIssueDetail);
      return container;
    }

    function showIssueDetail(ev) {
      var id = $(this).attr('id');
      var db = new PouchDB(repoName);
      db.get(id)
        .then(function(issue) {
          var container = $('.issue-detail');
          var backButton = $("
<button>Back</button>
");
          backButton.click(hideIssueDetails);
          container.append(backButton);

          var title = $("

"+ issue.title +"

");
          var issueNumber = $("

#"+ issue.number +"

");
          var text = $("

" + issue.body + "

");
          container.append(issueNumber);
          container.append(title);
          container.append($("
"));
          container.append(text);
          $(container).show();
          $(".issue-list").hide();
        })
        .catch(function(err) {
          console.log("ERR", err);
        });
    }

    function hideIssueDetails() {
      $(".issue-list").show();
      $(".issue-detail").hide();
      $(".issue-detail").empty();
    }
  }

  function fetchIssues(ev) {
    ev.preventDefault();
    var repo = repoName();
    if(!repo || repo === "") {
      return;
    }

    var gh = new GitHub();
    var issueHandle = gh.getIssues(repo);
    issueHandle.listIssues({}, function(_none, issues) {
      var db = new PouchDB(repo);
      db.bulkDocs(_.map(issues, setDocId))
      .then(function() {
          renderListView(repo);
      })
      .catch(function(err){
        console.log("ERR", err);
      });
    });

    function setDocId(issue) {
      issue['_id'] = issue.id.toString();
      return issue;
    }
  }

  function registerServiceWorker() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js').then(function(registration) {
        // Registration was successful
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      }).catch(function(err) {
        // registration failed :(
        console.log('ServiceWorker registration failed: ', err);
      });
    }
  }

  function loadAvailableRepositories() {
    PouchDB.allDbs().then(function (dbs) {
      var dbEntries = dbs.map(function(db) {
        var dbEntry = $("" + db + "");
        dbEntry.click(function(ev) {
          renderListView(db);
        });
        return dbEntry;
      });
      $(".repository-list").append(dbEntries);
    }).catch(function (err) {
      // handle err
      console.error("Failed to fetch all databases", err);
    });
  }

  $(document).ready(function() {
    registerServiceWorker();
    $('.fetch-issues').click(fetchIssues);
    loadAvailableRepositories();
  });
})();<|endoftext|>


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

    angular.module('ngApp', ['ngRoute', 'indexService', 'portfolioService', 'galleryService', 'linkService', 'contactService'])

    .controller('MainController', function ($scope, $route, $routeParams, $location) {
        $scope.$route = $route;
        $scope.$location = $location;
        $scope.$routeParams = $routeParams;
        $scope.currenDate = new Date();

        $scope.isActive = function (viewLocation) {
            var active = (viewLocation === $location.path());
            return active;
        };
    })

    .controller('BiographyController', function ($scope, $log) {
        //$log.info('BiographyController');
    })

    .controller('LegalNoticeController', function ($scope, $log) {
        //$log.info('LegalNoticeController');
    })

    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'includes/index.html',
                controller: 'IndexController'
            })
            .when('/portfolio', {
                templateUrl: 'includes/portfolio.html',
                controller: 'PortfolioController'
            })
            .when('/gallery/:category_id', {
                templateUrl: 'includes/gallery.html',
                controller: 'GalleryController'
            })
            .when('/contact', {
                templateUrl: 'includes/contact.html',
                controller: 'ContactController'
            })
            .when('/links', {
                templateUrl: 'includes/links.html',
                controller: 'LinksController'
            })
            .when('/biography', {
                templateUrl: 'includes/biography.html',
                controller: 'BiographyController'
            })
            .when('/legal_notice', {
                templateUrl: 'includes/legal_notice.html',
                controller: 'LegalNoticeController'
            })
            .otherwise({
                redirectTo: '/'
            });
    })

    .filter('objectToArray', function () {
        return function (input) {
            var out = [];
            for (var i in input) {
                out.push(input[i]);
            }
            return out;
        }
    });

})(window.angular);
<commit_msg>update mobile version to hide menu after selection<commit_after>(function (angular) {
    'use strict';

    angular.module('ngApp', ['ngRoute', 'indexService', 'portfolioService', 'galleryService', 'linkService', 'contactService'])

    .controller('MainController', function ($scope, $route, $routeParams, $location) {
        $scope.$route = $route;
        $scope.$location = $location;
        $scope.$routeParams = $routeParams;
        $scope.currenDate = new Date();

        $scope.isActive = function (viewLocation) {
            var active = (viewLocation === $location.path());
            return active;
        };
    })

    .controller('BiographyController', function ($scope, $log) {
        //$log.info('BiographyController');
    })

    .controller('LegalNoticeController', function ($scope, $log) {
        //$log.info('LegalNoticeController');
    })

    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'includes/index.html',
                controller: 'IndexController'
            })
            .when('/portfolio', {
                templateUrl: 'includes/portfolio.html',
                controller: 'PortfolioController'
            })
            .when('/gallery/:category_id', {
                templateUrl: 'includes/gallery.html',
                controller: 'GalleryController'
            })
            .when('/contact', {
                templateUrl: 'includes/contact.html',
                controller: 'ContactController'
            })
            .when('/links', {
                templateUrl: 'includes/links.html',
                controller: 'LinksController'
            })
            .when('/biography', {
                templateUrl: 'includes/biography.html',
                controller: 'BiographyController'
            })
            .when('/legal_notice', {
                templateUrl: 'includes/legal_notice.html',
                controller: 'LegalNoticeController'
            })
            .otherwise({
                redirectTo: '/'
            });
    })

    .filter('objectToArray', function () {
        return function (input) {
            var out = [];
            for (var i in input) {
                out.push(input[i]);
            }
            return out;
        }
    });

})(window.angular);

//Mobile navbar close on click
$(document).on('click','#navbar.in',function(e) {
    if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
        $(this).collapse('hide');
    }
});<|endoftext|>


<commit_before>var map, source, destination, router = new Router();

function findRoutes() {
    var hash  = location.hash.substr(1).split('-');
    var buses = router.findRoutes(hash[0], hash[1]);

    document.getElementById('output').innerHTML = buses.map(function(b, index) {
        return renderOption(b, index);
    }).join('\n');
}

/** load locations into hash */
function loadHash() {
    if(source && destination) {
        location.hash = source + '-' + destination;
    }
}

/** see if locations are stored in the hash */
function handleHashchange() {
    if(location.hash.length > 1) {
        findRoutes();
    }
}

window.onhashchange = handleHashchange;

function renderOption(route, index) {
    var output;
    if(route.changes.length == 0) {
        output = '
' +
            renderRoute(route.from, route.to, route.distance, route.routes[0].routes) + '
';
    }
    else if(route.changes.length == 1) {
        output = '
' +
            renderRoute(route.from, route.changes[0], route.routes[0].distance, route.routes[0].routes) +
        '

' +
            renderRoute(route.changes[0], route.to, route.routes[1].distance, route.routes[1].routes) +
        '
';
    }
    else if(route.changes.length == 2) {
        output = '
' +
            renderRoute(route.from, route.changes[0], route.routes[0].distance, route.routes[0].routes) +
        '

' +
            renderRoute(route.changes[0], route.changes[1], route.routes[1].distance, route.routes[1].routes) +
        '

' +
            renderRoute(route.changes[1], route.to, route.routes[2].distance, route.routes[2].routes) +
        '
';
    }

    if(index == 0) {
        output = '

' +
        ' Recommended Route

' +
        output;
    }
    else {
        output = '

' + output;
    }

    return output + '

Total Distance: ' +
        (route.distance / 1000.0).toFixed(2) + 'km

';
}

function renderRoute(from, to, distance, buses) {
    var from    = router.getPlaceDetails(from);
    var to      = router.getPlaceDetails(to);

    var details;
    var busmarkup = buses.map(function(r) {
        details = router.getRouteDetails(r);
        if(details) {
            return '#' + details.routeno +
                    ' (' + details.from + ' - ' + details.to + ')';
        }
    }).join('\n');

    return '
' +
        '

' +
        '' +
        from.name + ' to ' +
        to.name + ' (' + (distance / 1000.0).toFixed(2) + 'km)

' +
        '
' + busmarkup + '

';
}

/** geolocate code from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation */
function geolocate() {
    if (!navigator.geolocation) {
        $('#walk-warning').text('Sorry! Your browser does not support Geolocation.').removeClass('hide');
        return;
    }

    navigator.geolocation.getCurrentPosition(function(position) {
        /** on success */
        var nearest = router.getNearestPlace(position.coords.latitude, position.coords.longitude);
        if(nearest) {
            $('source').val(nearest.name);
            source = nearest.id;

            if(nearest.distance < 1000) {
                $('#walk-warning').addClass('hide');
            }
            else {
                $('#walk-warning').text('You might have to walk ' +
                    (nearest.distance / 1000.0).toFixed(2) + 'km').removeClass('hide');
            }
        }
        else {
            $('#walk-warning').text('Sorry! No bus stops found nearby.').removeClass('hide');
        }
    }, function() {
        /** on error */
        $('#walk-warning').text('Sorry! There was an error in getting your location.').removeClass('hide');
    });
}

/** load autocomplete on document.ready, and handle hash if present */
$(function() {

    handleHashchange();

    $('#source').autocomplete({
        lookup: router.getAllPlaces(),
        onSelect: function (suggestion) {
            source = suggestion.data;
        }
    });

    $('#destination').autocomplete({
        lookup: router.getAllPlaces(),
        onSelect: function (suggestion) {
            destination = suggestion.data;
        }
    });
});

/** Google Map code stolen off http://stackoverflow.com/a/26410438 */
function initMap(myCenter) {
    var marker = new google.maps.Marker({
        position: myCenter
    });

    var mapProp = {
        center: myCenter,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapProp);
    marker.setMap(map);
};

$('#map-modal').on('shown.bs.modal', function(e) {
    var element = $(e.relatedTarget);
    initMap(new google.maps.LatLng(element.data('lat'), element.data('lon')));
    $('#map-title').html(element.html());
});<commit_msg>minor bugfix<commit_after>var map, source, destination, router = new Router();

function findRoutes() {
    var hash  = location.hash.substr(1).split('-');
    var buses = router.findRoutes(hash[0], hash[1]);

    document.getElementById('output').innerHTML = buses.map(function(b, index) {
        return renderOption(b, index);
    }).join('\n');
}

/** load locations into hash */
function loadHash() {
    if(source && destination) {
        location.hash = source + '-' + destination;
    }
}

/** see if locations are stored in the hash */
function handleHashchange() {
    if(location.hash.length > 1) {
        findRoutes();
    }
}

window.onhashchange = handleHashchange;

function renderOption(route, index) {
    var output;
    if(route.changes.length == 0) {
        output = '
' +
            renderRoute(route.from, route.to, route.distance, route.routes[0].routes) + '
';
    }
    else if(route.changes.length == 1) {
        output = '
' +
            renderRoute(route.from, route.changes[0], route.routes[0].distance, route.routes[0].routes) +
        '

' +
            renderRoute(route.changes[0], route.to, route.routes[1].distance, route.routes[1].routes) +
        '
';
    }
    else if(route.changes.length == 2) {
        output = '
' +
            renderRoute(route.from, route.changes[0], route.routes[0].distance, route.routes[0].routes) +
        '

' +
            renderRoute(route.changes[0], route.changes[1], route.routes[1].distance, route.routes[1].routes) +
        '

' +
            renderRoute(route.changes[1], route.to, route.routes[2].distance, route.routes[2].routes) +
        '
';
    }

    if(index == 0) {
        output = '

' +
        ' Recommended Route

' +
        output;
    }
    else {
        output = '

' + output;
    }

    return output + '

Total Distance: ' +
        (route.distance / 1000.0).toFixed(2) + 'km

';
}

function renderRoute(from, to, distance, buses) {
    var from    = router.getPlaceDetails(from);
    var to      = router.getPlaceDetails(to);

    var details;
    var busmarkup = buses.map(function(r) {
        details = router.getRouteDetails(r);
        if(details) {
            return '#' + details.routeno +
                    ' (' + details.from + ' - ' + details.to + ')';
        }
    }).join('\n');

    return '
' +
        '

' +
        '' +
        from.name + ' to ' +
        to.name + ' (' + (distance / 1000.0).toFixed(2) + 'km)

' +
        '
' + busmarkup + '

';
}

/** geolocate code from MDN: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation */
function geolocate() {
    if (!navigator.geolocation) {
        $('#walk-warning').text('Sorry! Your browser does not support Geolocation.').removeClass('hide');
        return;
    }

    navigator.geolocation.getCurrentPosition(function(position) {
        /** on success */
        var nearest = router.getNearestPlace(position.coords.latitude, position.coords.longitude);
        if(nearest) {
            $('#source').val(nearest.name);
            source = nearest.id;

            if(nearest.distance < 1000) {
                $('#walk-warning').addClass('hide');
            }
            else {
                $('#walk-warning').text('You might have to walk ' +
                    (nearest.distance / 1000.0).toFixed(2) + 'km').removeClass('hide');
            }
        }
        else {
            $('#walk-warning').text('Sorry! No bus stops found nearby.').removeClass('hide');
        }
    }, function() {
        /** on error */
        $('#walk-warning').text('Sorry! There was an error in getting your location.').removeClass('hide');
    });
}

/** load autocomplete on document.ready, and handle hash if present */
$(function() {

    handleHashchange();

    $('#source').autocomplete({
        lookup: router.getAllPlaces(),
        onSelect: function (suggestion) {
            source = suggestion.data;
        }
    });

    $('#destination').autocomplete({
        lookup: router.getAllPlaces(),
        onSelect: function (suggestion) {
            destination = suggestion.data;
        }
    });
});

/** Google Map code stolen off http://stackoverflow.com/a/26410438 */
function initMap(myCenter) {
    var marker = new google.maps.Marker({
        position: myCenter
    });

    var mapProp = {
        center: myCenter,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapProp);
    marker.setMap(map);
};

$('#map-modal').on('shown.bs.modal', function(e) {
    var element = $(e.relatedTarget);
    initMap(new google.maps.LatLng(element.data('lat'), element.data('lon')));
    $('#map-title').html(element.html());
});<|endoftext|>


<commit_before>'use strict';

var app = angular.module('app', ['lheader']);

// Filter which convert whatever string in an hexadecimal color code
app.filter('color', function() {
    return function(str) {
        str = (str || '').toUpperCase();

        var i, hash;
        i = hash = 0;
        while (i < str.length) {
            hash = str.charCodeAt(i++) + ((hash << 5) - hash);
        }

        var colour = '#';
        for (i = 0; i < 3; ++i) {
            var part = (hash >> i * 8) & 0xFF;
            part = Math.max(Math.min(part, 300), 100);
            colour += ('00' + part.toString(16)).slice(-2);
        }
        return colour;
    };
});

app.controller('Ctrl', ['$scope', '$http', '$filter', '$timeout', '$sce', '$location', '$rootScope',
                        function($scope, $http, $filter, $timeout, $sce, $location, $rootScope) {
    var colors = [
        '#DF5A49', '#E27A3F', '#EFC94C', '#45B29D',
        '#334D5C', '#DFF2EF', '#4E7DA6', '#C42121',
        '#9E1D1D', '#6E1212', '#FF9D9D', '#FEE758',
        '#FFAD38', '#2C3E50', '#3E5101', '#839412',
        '#BDC032', '#D9A404', '#D96704'
    ];

    var allData;
    $scope.data = [];
    $scope.steps = [];
    $scope.currentStep = 0;

    $scope.legend = 'La taille des bulles correspond à l’audience : plus elles sont grosse, plus le titre est important. C’est une sélection des principaux titres des groupes de presse répartis en fonction des actionnaires majoritaires.';

    $scope.switches = [
        { label : 'En 2008' , value : '2008' },
        { label : 'En 2015' , value : '2015' }
    ];

    $scope.isFirstStep = function() {
        return $scope.currentStep === 0;
    };

    $scope.isLastStep = function() {
        return $scope.currentStep === $scope.steps.length - 1;
    };

    $scope.goToStep = (function() {
        var timeout;
        return function(index) {
            index = parseInt(index);
            if (index >= 0 && $scope.steps[index] != null) {
                $timeout.cancel(timeout);

                $scope.currentStep = index;

                $rootScope.$broadcast('bubbles:switchTo', '2008');
                if ($scope.isFirstStep()) {
                    $scope.data = _.clone(allData);
                } else {
                    $scope.data = _.filter(allData, function(d) {
                        return d.step === $scope.currentStep;
                    });
                    timeout = $timeout(function() {
                        $rootScope.$broadcast('bubbles:switchTo', '2015');
                    }, 1500);
                }
            }
        };
    })();

    $scope.goToPrevStep = function() {
        $scope.goToStep($scope.currentStep - 1);
    };

    $scope.goToNextStep = function() {
        $scope.goToStep($scope.currentStep + 1);
    };

    $http.get('data/steps.tsv').then(function(response) {
        $scope.steps = d3.tsv.parse(response.data, function(d) {
            d.text = $sce.trustAsHtml(d.text);
            return d;
        });

        $http.get('data/data.csv').then(function(response) {
            allData = _(d3.csv.parse(response.data, function(d, i) {
                var out = {
                    id : i,
                    name : d.Titre.trim(),
                    type : d.Type.trim(),
                    r : +(d['Hiérarchie'] || 1),
                    step : parseInt(d.Etape),
                };
                out[d['Année']] = d.Groupe.trim();
                return out;
            })).groupBy('name').map(function(d) {
                return _.merge(d[0], d[1], function(a, b, k) {
                    if (k === 'step') {
                        return (a === b) ? a : (_.isUndefined(a) || isNaN(a)) ? b : a;
                    }
                    return (a === b) ? a : _.isUndefined(a) ? b : a;
                });
            }).value();

            var groups = _(allData).pluck('2008').reject(_.isUndefined).uniq().value();

            _.each(allData, function(d) {
                d.fill = colors[groups.indexOf(d['2008'])];
            });

            var step = $location.search().step || 0;
            $scope.goToStep(step);
        });
    });

}]);<commit_msg>color from 2015 group if no group in 2008<commit_after>'use strict';

var app = angular.module('app', ['lheader']);

// Filter which convert whatever string in an hexadecimal color code
app.filter('color', function() {
    return function(str) {
        str = (str || '').toUpperCase();

        var i, hash;
        i = hash = 0;
        while (i < str.length) {
            hash = str.charCodeAt(i++) + ((hash << 5) - hash);
        }

        var colour = '#';
        for (i = 0; i < 3; ++i) {
            var part = (hash >> i * 8) & 0xFF;
            part = Math.max(Math.min(part, 300), 100);
            colour += ('00' + part.toString(16)).slice(-2);
        }
        return colour;
    };
});

app.controller('Ctrl', ['$scope', '$http', '$filter', '$timeout', '$sce', '$location', '$rootScope',
                        function($scope, $http, $filter, $timeout, $sce, $location, $rootScope) {
    var colors = [
        '#DF5A49', '#E27A3F', '#EFC94C', '#45B29D', '#334D5C', '#DFF2EF', '#4E7DA6',
        '#C42121', '#9E1D1D', '#6E1212', '#FF9D9D', '#FEE758', '#FFAD38', '#2C3E50',
        '#3E5101', '#839412', '#BDC032', '#D9A404', '#D96704'
    ];

    var allData;
    $scope.data = [];
    $scope.steps = [];
    $scope.currentStep = 0;

    $scope.legend = 'La taille des bulles correspond à l’audience : plus elles sont grosse, plus ' +
                    'le titre est important. C’est une sélection des principaux titres des ' +
                    'groupes de presse répartis en fonction des actionnaires majoritaires.';

    $scope.switches = [
        { label : 'En 2008' , value : '2008' }, { label : 'En 2015' , value : '2015' }
    ];

    $scope.isFirstStep = function() {
        return $scope.currentStep === 0;
    };

    $scope.isLastStep = function() {
        return $scope.currentStep === $scope.steps.length - 1;
    };

    $scope.goToStep = (function() {
        var timeout;
        return function(index) {
            index = parseInt(index);
            if (index >= 0 && $scope.steps[index] != null) {
                $timeout.cancel(timeout);

                $scope.currentStep = index;

                $rootScope.$broadcast('bubbles:switchTo', '2008');
                if ($scope.isFirstStep()) {
                    $scope.data = _.clone(allData);
                } else {
                    $scope.data = _.filter(allData, function(d) {
                        return d.step === $scope.currentStep;
                    });
                    timeout = $timeout(function() {
                        $rootScope.$broadcast('bubbles:switchTo', '2015');
                    }, 1500);
                }
            }
        };
    })();

    $scope.goToPrevStep = function() {
        $scope.goToStep($scope.currentStep - 1);
    };

    $scope.goToNextStep = function() {
        $scope.goToStep($scope.currentStep + 1);
    };

    $http.get('data/steps.tsv').then(function(response) {
        $scope.steps = d3.tsv.parse(response.data, function(d) {
            d.text = $sce.trustAsHtml(d.text);
            return d;
        });

        $http.get('data/data.csv').then(function(response) {
            allData = _(d3.csv.parse(response.data, function(d, i) {
                var out = {
                    id : i,
                    name : d.Titre.trim(),
                    type : d.Type.trim(),
                    r : +(d['Hiérarchie'] || 1),
                    step : parseInt(d.Etape),
                };
                out[d['Année']] = d.Groupe.trim();
                return out;
            })).groupBy('name').map(function(d) {
                return _.merge(d[0], d[1], function(a, b, k) {
                    if (k === 'step') {
                        return (a === b) ? a : (_.isUndefined(a) || isNaN(a)) ? b : a;
                    }
                    return (a === b) ? a : _.isUndefined(a) ? b : a;
                });
            }).value();

            var groups = _(allData).pluck('2008').reject(_.isUndefined).uniq().value();

            _.each(allData, function(d) {
                d.fill = colors[groups.indexOf(_.isUndefined(d['2008']) ? d['2015'] : d['2008'])];
            });

            var step = $location.search().step || 0;
            $scope.goToStep(step);
        });
    });

}]);<|endoftext|>


<commit_before><commit_msg>Content inside phone changes on scroll<commit_after>$(document).ready(function(){
  $(window).scroll(function(){
        if ($(this).scrollTop() >= $(".section-3").offset().top) {
           $(".inner-phone").css("background-color","blue");
        }else if($(this).scrollTop() >= $(".section-2").offset().top) {
          $(".inner-phone").css("background-color","yellow");
        } else {
          $(".inner-phone").css("background-color","green");
        }
    });
});<|endoftext|>