<commit_before>import PlayerTank from 'objects/PlayerTank';
import Projectile from 'objects/Projectile';

class GameState extends Phaser.State {

	constructor() {
		super();
		var platforms;
		var projectiles;

		var player;
		var player2;
		var cursors;
		var spaceKey;
		var turn;
		var land;
		var emitter;
		var map;
		var layer;
		var shadowTexture
		var lights;

		var timer;
		var timerEvent;

		var isProjAlive;
		var text;
		var player_text;
		var delay;
	}

	create() {
		this.startTimer();

		// enable physics
		this.game.world.setBounds(0,0,1600,600);
		this.game.physics.startSystem(Phaser.Physics.ARCADE);

		this.map = this.game.add.tilemap('map')
		this.map.addTilesetImage('ground_1x1');
	    this.map.addTilesetImage('walls_1x2');
	    this.map.addTilesetImage('tiles2');

	    this.layer = this.map.createLayer('Tile Layer 1');
	    //this.map.createLayer('Tile Layer 2');

	    this.layer.resizeWorld();
	    this.map.setCollisionBetween(1, 12);
	    //this.game.physics.convertTilemap(this.map, layer);
		// setup stage
		//this.game.add.sprite(0, 0, 'sky');

		// setup platforms + ground
		this.platforms = this.game.add.group();

		// Enable physics for the platforms group
		this.platforms.enableBody = true;

		// ALL LIGHTING STUFF

		this.LIGHT_RADIUS = 100;
		this.shadowTexture = this.game.add.bitmapData(1600, this.game.height);

		var lightSprite = this.game.add.image(0, 0, this.shadowTexture);
		this.lights = this.game.add.group();
		lightSprite.blendMode = Phaser.blendModes.MULTIPLY;
		// Create the ground
		// let ground = this.platforms.create(0, this.game.world.height-64, 'ground');
		// ground.scale.setTo(2, 2);
		// ground.body.immovable = true;

		// this.land = this.add.bitmapData(992, 480);
		// this.land.draw('ground');
		// this.land.update();
		// this.land.addToWorld();

        //  A small burst of particles when a target is hit
        this.emitter = this.add.emitter(0, 0, 0);
        this.emitter.makeParticles('flame');
        this.emitter.setXSpeed(-150, 150);
        this.emitter.setYSpeed(150, -150);
        this.emitter.setRotation();

		// Instantiate graphics
		this.graphics = this.game.add.graphics(0, 0);
        this.healthgraphics1 = this.game.add.graphics(0,0);
        this.healthgraphics2 = this.game.add.graphics(0,0);
        this.staminagraphics = this.game.add.graphics(0,0);
		// Initialize players

		let height = this.game.world.height;
		let center = this.game.world.width/2;

		// this.player = new PlayerTank(this.game, this, this.game.world.randomX, this.game.rnd.integerInRange(0, height-64), 1);
		// this.player2 = new PlayerTank(this.game, this, this.game.world.randomX, this.game.rnd.integerInRange(0, height-64), 2);
		this.player = new PlayerTank(this.game, this, this.game.rnd.integerInRange(64, center-128), this.game.rnd.integerInRange(0, height-64), 1);
		this.player2 = new PlayerTank(this.game, this, this.game.rnd.integerInRange(center+128, this.game.world.width-64), this.game.rnd.integerInRange(0, height-64), 2);
		this.player.tint = "0x33B2FF";
		this.player2.tint = "0xFF6B66";

		// Setup group for tracking projectiles
		this.projectiles = this.game.add.group();
		this.projectiles.classType = Projectile;

		// input handlers
		this.cursors = this.game.input.keyboard.createCursorKeys();
		//this.spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
		//this.spaceKey.onDown.add(this.toggleTurn, this);
		this.jumpKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
		this.turn = 0;

		this.game.camera.follow(this.player);
		this.player_text = this.game.add.text(125, 14,
               	"Player 1", {font: "20px Arial", fill: "#33B2FF", stroke: '#000000', strokeThickness: 3});
        this.player_text.anchor.setTo(0.5, 0.5);
        this.player_text.fixedToCamera = true;
	}

	startTimer() {
		this.timer = this.game.time.create();
		this.timerEvent = this.timer.add(Phaser.Timer.SECOND * 30, this.endTimer, this);
		this.timer.start();
	}

	render() {
		// If our timer is running, show the time in a nicely formatted way, else show 'Done!'
        if (this.timer.running) {
            this.game.debug.text(this.formatTime(Math.round((this.timerEvent.delay - this.timer.ms) / 1000)), 2, 14, "#ff0");
        	//this.game.debug.text("Done!", 2, 14, "#0f0");
        }
        else {
            this.game.debug.text("Done!", 2, 14, "#0f0");
        }
	}

	formatTime(s) {
        // Convert seconds (s) to a nicely formatted and padded time string
        var minutes = "0" + Math.floor(s / 60);
        var seconds = "0" + (s - minutes * 60);
        return minutes.substr(-2) + ":" + seconds.substr(-2);
    }

	endTimer() {
        // Stop the timer when the delayed event triggers
        this.timer.stop();
        if (!this.isProjAlive) {
        	this.delay = this.game.time.create();
        	var delayEvent = this.delay.add(Phaser.Timer.SECOND * 1.5, this.stopDelay, this);
        	this.delay.start();
    	}
    }

    stopDelay() {
		this.delay.stop();
    	this.toggleTurn();
        this.startTimer();
    }

	toggleTurn() {
		this.turn = 1 - this.turn;
		if (this.player_text)
			this.player_text.destroy();
		if (this.turn == 0) {
			this.player.didFireThisTurn = false;
			this.player.projectileSpeed = 100;
			this.player2.stamina = 60;
			this.game.camera.follow(this.player);
			if (this.text) this.text.destroy();
			this.player_text = this.game.add.text(125, 14,
               	"Player 1", {font: "20px Arial", fill: "#33B2FF", stroke: '#000000', strokeThickness: 3});
			this.player_text.anchor.setTo(0.5, 0.5);
        	this.player_text.fixedToCamera = true;
		}
		else {
			this.player2.didFireThisTurn = false;
			this.player2.projectileSpeed = 100;
			this.player.stamina = 60;
			this.game.camera.follow(this.player2);
			if (this.text) this.text.destroy();
			this.player_text = this.game.add.text(125, 14,
               	"Player 2", {font: "20px Arial", fill: "#FF6B66", stroke: '#000000', strokeThickness: 3});
			this.player_text.anchor.setTo(0.5, 0.5);
        	this.player_text.fixedToCamera = true;
		}
		// if (this.turn == 0) {
		// 	this.player.update();
		// 	this.player2.endTurn();
		// 	this.game.camera.follow(this.player);
		// }
		// else if (this.turn == 1) {
		// 	this.player2.update();
		// 	this.player.endTurn();
		// 	this.game.camera.follow(this.player2);
		// }
	}

	update() {

		var hitPlatform = this.game.physics.arcade.collide(this.player, this.layer);
		var hitPlatform2 = this.game.physics.arcade.collide(this.player2, this.layer);

        this.graphics.clear();
		if (this.turn == 0) {
			this.player.update(hitPlatform);
			this.player2.endTurn();
			//if (!this.isProjAlive) this.game.camera.follow(this.player);
		}
		else if (this.turn == 1) {
			this.player2.update(hitPlatform2);
			this.player.endTurn();
			//if (!this.isProjAlive) this.game.camera.follow(this.player2);
		}
		this.updateShadowTexture()
		this.player.drawHealthBar();
		this.player2.drawHealthBar();

	}
	updateShadowTexture() {
	    // This function updates the shadow texture (this.shadowTexture).
	    // First, it fills the entire texture with a dark shadow color.
	    // Then it draws a white circle centered on the pointer position.
	    // Because the texture is drawn to the screen using the MULTIPLY
	    // blend mode, the dark areas of the texture make all of the colors
	    // underneath it darker, while the white area is unaffected.

	    // Draw shadow
	    // change this to be 0,0,0 for it to become nothing
	    this.shadowTexture.context.fillStyle = 'rgb(0, 0, 0)';
	    this.shadowTexture.context.fillRect(0, 0, 1600, this.game.height);

	    // Iterate through each of the lights and draw the glow
	    this.lights.forEach(function(light) {
	        // Randomly change the radius each frame
	        var radius = this.LIGHT_RADIUS;

	        // Draw circle of light with a soft edge
	        var gradient =
	            this.shadowTexture.context.createRadialGradient(
	                light.x, light.y,this.LIGHT_RADIUS * 0.75,
	                light.x, light.y, radius);
	        gradient.addColorStop(0, 'rgba(255, 255, 255, 1.0)');
	        gradient.addColorStop(1, 'rgba(255, 255, 255, 0.0)');

	        this.shadowTexture.context.beginPath();
	        this.shadowTexture.context.fillStyle = gradient;
	        this.shadowTexture.context.arc(light.x, light.y, radius, 0, Math.PI*2);
	        this.shadowTexture.context.fill();
	    }, this);

	    // This just tells the engine it should update the texture cache
	    this.shadowTexture.dirty = true;
	};
}

export default GameState;<commit_msg>Reposition text<commit_after>import PlayerTank from 'objects/PlayerTank';
import Projectile from 'objects/Projectile';

class GameState extends Phaser.State {

	constructor() {
		super();
		var platforms;
		var projectiles;

		var player;
		var player2;
		var cursors;
		var spaceKey;
		var turn;
		var land;
		var emitter;
		var map;
		var layer;
		var shadowTexture
		var lights;

		var timer;
		var timerEvent;

		var isProjAlive;
		var text;
		var player_text;
		var delay;
	}

	create() {
		this.startTimer();

		// enable physics
		this.game.world.setBounds(0,0,1600,600);
		this.game.physics.startSystem(Phaser.Physics.ARCADE);

		this.map = this.game.add.tilemap('map')
		this.map.addTilesetImage('ground_1x1');
	    this.map.addTilesetImage('walls_1x2');
	    this.map.addTilesetImage('tiles2');

	    this.layer = this.map.createLayer('Tile Layer 1');
	    //this.map.createLayer('Tile Layer 2');

	    this.layer.resizeWorld();
	    this.map.setCollisionBetween(1, 12);
	    //this.game.physics.convertTilemap(this.map, layer);
		// setup stage
		//this.game.add.sprite(0, 0, 'sky');

		// setup platforms + ground
		this.platforms = this.game.add.group();

		// Enable physics for the platforms group
		this.platforms.enableBody = true;

		// ALL LIGHTING STUFF

		this.LIGHT_RADIUS = 100;
		this.shadowTexture = this.game.add.bitmapData(1600, this.game.height);

		var lightSprite = this.game.add.image(0, 0, this.shadowTexture);
		this.lights = this.game.add.group();
		lightSprite.blendMode = Phaser.blendModes.MULTIPLY;
		// Create the ground
		// let ground = this.platforms.create(0, this.game.world.height-64, 'ground');
		// ground.scale.setTo(2, 2);
		// ground.body.immovable = true;

		// this.land = this.add.bitmapData(992, 480);
		// this.land.draw('ground');
		// this.land.update();
		// this.land.addToWorld();

        //  A small burst of particles when a target is hit
        this.emitter = this.add.emitter(0, 0, 0);
        this.emitter.makeParticles('flame');
        this.emitter.setXSpeed(-150, 150);
        this.emitter.setYSpeed(150, -150);
        this.emitter.setRotation();

		// Instantiate graphics
		this.graphics = this.game.add.graphics(0, 0);
        this.healthgraphics1 = this.game.add.graphics(0,0);
        this.healthgraphics2 = this.game.add.graphics(0,0);
        this.staminagraphics = this.game.add.graphics(0,0);
		// Initialize players

		let height = this.game.world.height;
		let center = this.game.world.width/2;

		// this.player = new PlayerTank(this.game, this, this.game.world.randomX, this.game.rnd.integerInRange(0, height-64), 1);
		// this.player2 = new PlayerTank(this.game, this, this.game.world.randomX, this.game.rnd.integerInRange(0, height-64), 2);
		this.player = new PlayerTank(this.game, this, this.game.rnd.integerInRange(64, center-128), this.game.rnd.integerInRange(0, height-64), 1);
		this.player2 = new PlayerTank(this.game, this, this.game.rnd.integerInRange(center+128, this.game.world.width-64), this.game.rnd.integerInRange(0, height-64), 2);
		this.player.tint = "0x33B2FF";
		this.player2.tint = "0xFF6B66";

		// Setup group for tracking projectiles
		this.projectiles = this.game.add.group();
		this.projectiles.classType = Projectile;

		// input handlers
		this.cursors = this.game.input.keyboard.createCursorKeys();
		//this.spaceKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
		//this.spaceKey.onDown.add(this.toggleTurn, this);
		this.jumpKey = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
		this.turn = 0;

		this.game.camera.follow(this.player);
		this.player_text = this.game.add.text(140, 14,
               	"Player 1", {font: "20px Arial", fill: "#33B2FF", stroke: '#000000', strokeThickness: 3});
        this.player_text.anchor.setTo(0.5, 0.5);
        this.player_text.fixedToCamera = true;
	}

	startTimer() {
		this.timer = this.game.time.create();
		this.timerEvent = this.timer.add(Phaser.Timer.SECOND * 30, this.endTimer, this);
		this.timer.start();
	}

	render() {
		// If our timer is running, show the time in a nicely formatted way, else show 'Done!'
        if (this.timer.running) {
            this.game.debug.text(this.formatTime(Math.round((this.timerEvent.delay - this.timer.ms) / 1000)), 2, 14, "#ff0");
        	//this.game.debug.text("Done!", 2, 14, "#0f0");
        }
        else {
            this.game.debug.text("Time's up!", 2, 14, "#0f0");
        }
	}

	formatTime(s) {
        // Convert seconds (s) to a nicely formatted and padded time string
        var minutes = "0" + Math.floor(s / 60);
        var seconds = "0" + (s - minutes * 60);
        return minutes.substr(-2) + ":" + seconds.substr(-2);
    }

	endTimer() {
        // Stop the timer when the delayed event triggers
        this.timer.stop();
        if (!this.isProjAlive) {
        	this.delay = this.game.time.create();
        	var delayEvent = this.delay.add(Phaser.Timer.SECOND * 1.5, this.stopDelay, this);
        	this.delay.start();
    	}
    }

    stopDelay() {
		this.delay.stop();
    	this.toggleTurn();
        this.startTimer();
    }

	toggleTurn() {
		this.turn = 1 - this.turn;
		if (this.player_text)
			this.player_text.destroy();
		if (this.turn == 0) {
			this.player.didFireThisTurn = false;
			this.player.projectileSpeed = 100;
			this.player2.stamina = 60;
			this.game.camera.follow(this.player);
			if (this.text) this.text.destroy();
			this.player_text = this.game.add.text(140, 14,
               	"Player 1", {font: "20px Arial", fill: "#33B2FF", stroke: '#000000', strokeThickness: 3});
			this.player_text.anchor.setTo(0.5, 0.5);
        	this.player_text.fixedToCamera = true;
		}
		else {
			this.player2.didFireThisTurn = false;
			this.player2.projectileSpeed = 100;
			this.player.stamina = 60;
			this.game.camera.follow(this.player2);
			if (this.text) this.text.destroy();
			this.player_text = this.game.add.text(140, 14,
               	"Player 2", {font: "20px Arial", fill: "#FF6B66", stroke: '#000000', strokeThickness: 3});
			this.player_text.anchor.setTo(0.5, 0.5);
        	this.player_text.fixedToCamera = true;
		}
		// if (this.turn == 0) {
		// 	this.player.update();
		// 	this.player2.endTurn();
		// 	this.game.camera.follow(this.player);
		// }
		// else if (this.turn == 1) {
		// 	this.player2.update();
		// 	this.player.endTurn();
		// 	this.game.camera.follow(this.player2);
		// }
	}

	update() {

		var hitPlatform = this.game.physics.arcade.collide(this.player, this.layer);
		var hitPlatform2 = this.game.physics.arcade.collide(this.player2, this.layer);

        this.graphics.clear();
		if (this.turn == 0) {
			this.player.update(hitPlatform);
			this.player2.endTurn();
			//if (!this.isProjAlive) this.game.camera.follow(this.player);
		}
		else if (this.turn == 1) {
			this.player2.update(hitPlatform2);
			this.player.endTurn();
			//if (!this.isProjAlive) this.game.camera.follow(this.player2);
		}
		this.updateShadowTexture()
		this.player.drawHealthBar();
		this.player2.drawHealthBar();

	}
	updateShadowTexture() {
	    // This function updates the shadow texture (this.shadowTexture).
	    // First, it fills the entire texture with a dark shadow color.
	    // Then it draws a white circle centered on the pointer position.
	    // Because the texture is drawn to the screen using the MULTIPLY
	    // blend mode, the dark areas of the texture make all of the colors
	    // underneath it darker, while the white area is unaffected.

	    // Draw shadow
	    // change this to be 0,0,0 for it to become nothing
	    this.shadowTexture.context.fillStyle = 'rgb(0, 0, 0)';
	    this.shadowTexture.context.fillRect(0, 0, 1600, this.game.height);

	    // Iterate through each of the lights and draw the glow
	    this.lights.forEach(function(light) {
	        // Randomly change the radius each frame
	        var radius = this.LIGHT_RADIUS;

	        // Draw circle of light with a soft edge
	        var gradient =
	            this.shadowTexture.context.createRadialGradient(
	                light.x, light.y,this.LIGHT_RADIUS * 0.75,
	                light.x, light.y, radius);
	        gradient.addColorStop(0, 'rgba(255, 255, 255, 1.0)');
	        gradient.addColorStop(1, 'rgba(255, 255, 255, 0.0)');

	        this.shadowTexture.context.beginPath();
	        this.shadowTexture.context.fillStyle = gradient;
	        this.shadowTexture.context.arc(light.x, light.y, radius, 0, Math.PI*2);
	        this.shadowTexture.context.fill();
	    }, this);

	    // This just tells the engine it should update the texture cache
	    this.shadowTexture.dirty = true;
	};
}

export default GameState;<|endoftext|>


<commit_before>'use strict';

var game = require('../game'),
    Phaser = require('phaser').Phaser;

var sprite;
var iAmHovering = false;
var pukeAbilitySprite;
var hoverAbilitySprite;
var pukeAbility = 0;
var hoverAbility = 0;
var controls = {};
var testMap;
var puker = 1;
var jumper = 0;
var layer;
var grassyLayer;
var ability = 0;//0 = vomit, 1 = hover. THis is checked in puke() which is general perpose
var aCounter = 0;//this keeps track of how close we are to triggering an ability.
var emitter;
var emitting = false;
var emitterXvelocity;
var emitterXvelecoityMoving;
var baddies = [];

function createGameState() {
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.stage.backgroundColor = '#999999';

    testMap = game.add.tilemap('testMap');
    testMap.addTilesetImage('all_small', 'all_small');
    layer = testMap.createLayer('Tile Layer 1');
    grassyLayer = testMap.createLayer('Grass On Top');

    emitter = game.add.emitter(0, 0, 1);
    sprite = game.add.sprite(200, 200, 'player');
    sprite.anchor.setTo(0.65, 0.5);
    sprite.facing = 1;

    sprite.animations.add('walk', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]);
    sprite.animations.add('stand', [6]);

    sprite.animations.play('walk', 60, true);

    game.physics.arcade.enable(sprite);
    sprite.body.setSize(40, 144, 6, 14);
    game.physics.arcade.gravity.y = 300;

    game.physics.arcade.collide(sprite, layer);
    testMap.setCollisionBetween(8, 11, true, layer);
    testMap.setCollisionBetween(13, 17, true, layer);
    testMap.setCollisionBetween(19, 23, true, layer);
    testMap.setCollisionBetween(26, 29, true, layer);

    sprite.body.maxVelocity.x = 400;
    sprite.body.drag.x = 370;
    sprite.body.drag.y = 370;
    sprite.running = false;
    game.physics.enable(sprite, Phaser.Physics.ARCADE);
    sprite.body.gravity.y = 1000;

    game.camera.follow(sprite);
    layer.resizeWorld();

    emitter.makeParticles('vomit', [0,1,2,3], 200, true, true);

    // Attach the emitter to the sprite
    //sprite.addChild(emitter);

    //position the emitter relative to the sprite's anchor location
    emitter.y = 100;
    emitter.x = -250;

    emitterXvelocity = 700;
    emitter.minParticleSpeed.setTo(emitterXvelocity, 100);
    emitter.maxParticleSpeed.setTo(emitterXvelocity / 2, 600);

    emitter.gravity = 1;
    emitter.bounce.setTo(0.5, 0.5);
    emitter.angularDrag = 0;

    controls.left = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    controls.right = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    controls.run = game.input.keyboard.addKey(Phaser.Keyboard.X);
    controls.jump = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    populateBaddies();
    makeTokens();
}

function updateGameState() {
    game.physics.arcade.collide(sprite, layer);
    game.physics.arcade.collide(emitter, layer);
    game.physics.arcade.overlap(sprite, pukeAbilitySprite, handlePukeSprite);
    game.physics.arcade.overlap(sprite, hoverAbilitySprite, handleHoverSprite);

    if (!sprite.running && controls.run.isDown) {
        sprite.running = true;
        sprite.body.maxVelocity.x = 700;
        sprite.body.drag.x = 470;
    }
    if (!controls.run.isDown && sprite.running) {
        sprite.running = false;
        sprite.body.maxVelocity.x = 400;
        sprite.body.drag.x = 370;
        emitterXvelecoityMoving = emitterXvelocity;
        emitter.minParticleSpeed.setTo(emitterXvelocity, 0);
    }

    var moving = false;
    if (controls.left.isDown) {
        moving = true;
        sprite.body.velocity.x -= 50;
        if (sprite.facing === 1) {
            sprite.scale.x = -1;
            sprite.facing = -1;
        }
        if (emitting) {
            emitter.maxParticleSpeed.x = (emitterXvelocity * sprite.facing) + sprite.body.velocity.x;
            emitter.minParticleSpeed.x = ((emitterXvelocity * sprite.facing)/2) + sprite.body.velocity.x;
        }
    }
    if (controls.right.isDown) {
        moving = true;
        sprite.body.velocity.x += 50;
        if (sprite.facing === -1) {
            sprite.scale.x = 1;
            sprite.facing = 1;
        }
        if (emitting) {
            emitter.maxParticleSpeed.x = (emitterXvelocity * sprite.facing) + sprite.body.velocity.x;
            emitter.minParticleSpeed.x = ((emitterXvelocity * sprite.facing)/2) + sprite.body.velocity.x;
        }
    }
    if (!moving) {
        if (sprite.animations.currentAnim.name !== 'stand') {
            sprite.animations.play('stand');
        }
    } else {
        if (sprite.animations.currentAnim.name !== 'walk') {
            sprite.animations.play('walk', 60, true);
        }
    }
    if(jumper > 0) {jumper--;}
    if(sprite.body.onFloor() && controls.jump.isDown && jumper == 0){
       jumper = 20;
       sprite.body.velocity.y = -500;
       if(sprite.running){
           sprite.body.velocity.y -= 100;
       }
       puker++;
    }
    else if (controls.jump.isDown && sprite.body.velocity.y < -300){
        sprite.body.velocity.y -= 20;
    }
    //if(puker % 4 == 0){
    if(pukeAbility > 70) {
       puke();
    }
    if(hoverAbility > 100) {
        hover()
    }

    if (emitting) {
        emitter.emitParticle();
        //emitter.x += 10;
        //emitter.position = sprite.position;
        emitter.x = sprite.x+10;
        emitter.y = sprite.y;
    }

    pukeAbility -= 1;
    if (pukeAbility < 0) {
        pukeAbility = 0;
    }
    hoverAbility -= 1;
    if (hoverAbility < 0) {
        hoverAbility = 0;
    }

 if(sprite.body.y > 700){gameOver();}
}

function gameOver(){
//TODO you fail
    game.time.events.add(1000, reset);
    sprite.kill();
}
function reset(){
    baddies = [];
    game.state.start("gameState");
}

function handlePukeSprite(){
    pukeAbility += 5;
    if (pukeAbility > 100) {
        pukeAbility = 100;
    }
}
function handleHoverSprite(){
    hoverAbility += 5;
    if (hoverAbility > 1000) {
        hoverAbility = 1000
    }
}

function puke(){
    puker = 1;
        var bullet = game.add.sprite(sprite.x, sprite.y + 30, 'test2');
        game.physics.arcade.enable(bullet);
        bullet.update = bulletColide;
        bullet.facing = sprite.facing;
        bullet.body.allowGravity = false;
        game.time.events.add(5000, bulletDeath, bullet);
    emitting = true;
    game.time.events.add(1000, function() {emitting = false;});
    }
function hover() {
    if (iAmHovering) {
        console.log ('Nice try.')
    } else {
        iAmHovering = true;
        sprite.body.gravity.y = 0;
        sprite.body.velocity.y = 0;
        sprite.body.y = sprite.body.y - 10;
        game.time.events.add(1500, endHover, sprite);
    }
}

function endHover(){
    this.body.gravity.y = 1000;
    iAmHovering = false;
}

function makeTokens() {
    pukeAbilitySprite = game.add.sprite(1000, 400, 'pukeAbilitySprite');
    pukeAbilitySprite.scale.setTo(0.5, 0.5);
    game.physics.arcade.enable(pukeAbilitySprite);
    //baddy.update = baddyColide;
    pukeAbilitySprite.body.allowGravity = false;

    hoverAbilitySprite = game.add.sprite(2000, 400, 'hoverAbilitySprite');
    hoverAbilitySprite.scale.setTo(0.5, 0.5);
    game.physics.arcade.enable(hoverAbilitySprite);
    //baddy.update = baddyColide;
    hoverAbilitySprite.body.allowGravity = false;
}

function bulletDeath(){
    this.kill();
}
function populateBaddies(){

    var baddy = game.add.sprite(1500, 345, 'enemy');
        baddy.scale.setTo(0.5, 0.5);
        baddy.anchor.setTo(0.5, 0.5);
        game.physics.arcade.enable(baddy);
        baddy.update = baddyColide;
        baddy.body.allowGravity = false;
        baddy.animations.add('normal', [1, 1, 1, 1, 1, 0]);
        baddy.animations.play('normal', 1, true);
baddies.push(baddy);
}
function baddyColide(){

    if(game.physics.arcade.collide(this, sprite)){gameOver();}
    game.physics.arcade.collide(this, layer);
}

function killBaddy(a){
baddies[a].kill();
}

function bulletColide(){
    this.body.velocity.x = 600 * this.facing;
    game.physics.arcade.collide(this, layer);
    if(game.physics.arcade.collide(this, baddies[0])){killBaddy(0);}
    if(game.physics.arcade.collide(this, baddies[1])){killBaddy(1);}

    if (!this.body.touching.none) {
        this.facing = this.facing * -1;
    }
}

var gameState = {
    create: createGameState,
    update: updateGameState
};

module.exports = gameState;
<commit_msg>new jumping and begining of ability systemoverhaul<commit_after>'use strict';

var game = require('../game'),
    Phaser = require('phaser').Phaser;

var sprite;
var iAmHovering = false;
var pukeAbilitySprite;
var hoverAbilitySprite;
var pukeAbility = 0;
var hoverAbility = 0;
var controls = {};
var testMap;
var puker = 1;
var jumper = 0;
var layer;
var grassyLayer;
var ability = 0;//0 = vomit, 1 = hover. THis is checked in puke() which is general perpose
var aCounter = 0;//this keeps track of how close we are to triggering an ability.
var emitter;
var emitting = false;
var emitterXvelocity;
var emitterXvelecoityMoving;
var baddies = [];
var charge = 20;

function createGameState() {
    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.stage.backgroundColor = '#999999';

    testMap = game.add.tilemap('testMap');
    testMap.addTilesetImage('all_small', 'all_small');
    layer = testMap.createLayer('Tile Layer 1');
    grassyLayer = testMap.createLayer('Grass On Top');

    emitter = game.add.emitter(0, 0, 1);
    sprite = game.add.sprite(200, 200, 'player');
    sprite.anchor.setTo(0.65, 0.5);
    sprite.facing = 1;

    sprite.animations.add('walk', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]);
    sprite.animations.add('stand', [6]);

    sprite.animations.play('walk', 60, true);

    game.physics.arcade.enable(sprite);
    sprite.body.setSize(40, 144, 6, 14);
    game.physics.arcade.gravity.y = 300;

    game.physics.arcade.collide(sprite, layer);
    testMap.setCollisionBetween(8, 11, true, layer);
    testMap.setCollisionBetween(13, 17, true, layer);
    testMap.setCollisionBetween(19, 23, true, layer);
    testMap.setCollisionBetween(26, 29, true, layer);

    sprite.body.maxVelocity.x = 400;
    sprite.body.drag.x = 370;
    sprite.body.drag.y = 370;
    sprite.running = false;
    game.physics.enable(sprite, Phaser.Physics.ARCADE);
    sprite.body.gravity.y = 2000;

    game.camera.follow(sprite);
    layer.resizeWorld();

    emitter.makeParticles('vomit', [0,1,2,3], 200, true, true);

    // Attach the emitter to the sprite
    //sprite.addChild(emitter);

    //position the emitter relative to the sprite's anchor location
    emitter.y = 100;
    emitter.x = -250;

    emitterXvelocity = 700;
    emitter.minParticleSpeed.setTo(emitterXvelocity, 100);
    emitter.maxParticleSpeed.setTo(emitterXvelocity / 2, 600);

    emitter.gravity = 1;
    emitter.bounce.setTo(0.5, 0.5);
    emitter.angularDrag = 0;

    controls.left = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
    controls.right = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
    controls.run = game.input.keyboard.addKey(Phaser.Keyboard.X);
    controls.jump = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    populateBaddies();
    makeTokens();
}

function updateGameState() {
if(Math.random() > 0.5) charge++;
if(Math.random() < 0.5) charge--;
if(charge > 25) {abilityTrigger(); charge = charge - 25;}
if(charge < 0) {charge = 0;}

    game.physics.arcade.collide(sprite, layer);
    game.physics.arcade.collide(emitter, layer);
    game.physics.arcade.overlap(sprite, pukeAbilitySprite, handlePukeSprite);
    game.physics.arcade.overlap(sprite, hoverAbilitySprite, handleHoverSprite);

    if (!sprite.running && controls.run.isDown) {
        sprite.running = true;
        sprite.body.maxVelocity.x = 700;
        sprite.body.drag.x = 470;
    }
    if (!controls.run.isDown && sprite.running) {
        sprite.running = false;
        sprite.body.maxVelocity.x = 400;
        sprite.body.drag.x = 370;
        emitterXvelecoityMoving = emitterXvelocity;
        emitter.minParticleSpeed.setTo(emitterXvelocity, 0);
    }

    var moving = false;
    if (controls.left.isDown) {
        moving = true;
        sprite.body.velocity.x -= 50;
        if (sprite.facing === 1) {
            sprite.scale.x = -1;
            sprite.facing = -1;
        }
        if (emitting) {
            emitter.maxParticleSpeed.x = (emitterXvelocity * sprite.facing) + sprite.body.velocity.x;
            emitter.minParticleSpeed.x = ((emitterXvelocity * sprite.facing)/2) + sprite.body.velocity.x;
        }
    }
    if (controls.right.isDown) {
        moving = true;
        sprite.body.velocity.x += 50;
        if (sprite.facing === -1) {
            sprite.scale.x = 1;
            sprite.facing = 1;
        }
        if (emitting) {
            emitter.maxParticleSpeed.x = (emitterXvelocity * sprite.facing) + sprite.body.velocity.x;
            emitter.minParticleSpeed.x = ((emitterXvelocity * sprite.facing)/2) + sprite.body.velocity.x;
        }
    }
    if (!moving) {
charge--;
charge--;
charge--;
        if (sprite.animations.currentAnim.name !== 'stand') {
            sprite.animations.play('stand');
        }
    } else {
        if (sprite.animations.currentAnim.name !== 'walk') {
            sprite.animations.play('walk', 60, true);
        }
    }
    if(jumper > 0) {jumper--;}
else {charge--;}
    if(sprite.body.onFloor() && controls.jump.isDown && jumper == 0){
       jumper = 20;
       sprite.body.velocity.y = -700;
       if(sprite.running){
           sprite.body.velocity.y -= 150;
       }
       puker++;
    }
    else if (controls.jump.isDown && sprite.body.velocity.y < -300){
charge++;
charge++;
        sprite.body.velocity.y -= 20;
    }
    //if(puker % 4 == 0){
    if(pukeAbility > 70) {
       puke();
    }
    if(hoverAbility > 100) {
        hover()
    }

    if (emitting) {
        emitter.emitParticle();
        //emitter.x += 10;
        //emitter.position = sprite.position;
        emitter.x = sprite.x+10;
        emitter.y = sprite.y;
    }

    pukeAbility -= 1;
    if (pukeAbility < 0) {
        pukeAbility = 0;
    }
    hoverAbility -= 1;
    if (hoverAbility < 0) {
        hoverAbility = 0;
    }

 if(sprite.body.y > 700){gameOver();}
}

function gameOver(){
//TODO you fail
    game.time.events.add(1000, reset);
    sprite.kill();
}
function reset(){
    baddies = [];
    game.state.start("gameState");
}

function handlePukeSprite(){
    pukeAbility += 5;
ability = 0;
    if (pukeAbility > 100) {
        pukeAbility = 100;
    }
}
function handleHoverSprite(){
ability = 1;
    hoverAbility += 5;
    if (hoverAbility > 1000) {
        hoverAbility = 1000
    }
}

function abilityTrigger(){
if(ability == 0) puke();
else if (ability == 1) hover();
}

function puke(){
    puker = 1;
        var bullet = game.add.sprite(sprite.x, sprite.y + 30, 'test2');
        game.physics.arcade.enable(bullet);
        bullet.update = bulletColide;
        bullet.facing = sprite.facing;
        bullet.body.allowGravity = false;
        game.time.events.add(5000, bulletDeath, bullet);
    emitting = true;
    game.time.events.add(1000, function() {emitting = false;});
    }
function hover() {
    if (iAmHovering) {
    } else {
        iAmHovering = true;
        sprite.body.gravity.y = 0;
        sprite.body.velocity.y = 0;
        sprite.body.y = sprite.body.y - 10;
        game.time.events.add(1500, endHover, sprite);
    }
}

function endHover(){
    this.body.gravity.y = 2000;
    iAmHovering = false;
}

function makeTokens() {
    pukeAbilitySprite = game.add.sprite(1000, 400, 'pukeAbilitySprite');
    pukeAbilitySprite.scale.setTo(0.5, 0.5);
    game.physics.arcade.enable(pukeAbilitySprite);
    //baddy.update = baddyColide;
    pukeAbilitySprite.body.allowGravity = false;

    hoverAbilitySprite = game.add.sprite(2000, 400, 'hoverAbilitySprite');
    hoverAbilitySprite.scale.setTo(0.5, 0.5);
    game.physics.arcade.enable(hoverAbilitySprite);
    //baddy.update = baddyColide;
    hoverAbilitySprite.body.allowGravity = false;
}

function bulletDeath(){
    this.kill();
}
function populateBaddies(){

    var baddy = game.add.sprite(1500, 345, 'enemy');
        baddy.scale.setTo(0.5, 0.5);
        baddy.anchor.setTo(0.5, 0.5);
        game.physics.arcade.enable(baddy);
        baddy.update = baddyColide;
        baddy.body.allowGravity = false;
        baddy.animations.add('normal', [1, 1, 1, 1, 1, 0]);
        baddy.animations.play('normal', 1, true);
baddies.push(baddy);
}
function baddyColide(){

    if(game.physics.arcade.collide(this, sprite)){gameOver();}
    game.physics.arcade.collide(this, layer);
}

function killBaddy(a){
  charge = charge + 100;
baddies[a].kill();
}

function bulletColide(){
    this.body.velocity.x = 600 * this.facing;
    game.physics.arcade.collide(this, layer);
    if(game.physics.arcade.collide(this, baddies[0])){killBaddy(0);}
    if(game.physics.arcade.collide(this, baddies[1])){killBaddy(1);}

    if (!this.body.touching.none) {
        this.facing = this.facing * -1;
    }
}

var gameState = {
    create: createGameState,
    update: updateGameState
};

module.exports = gameState;
<|endoftext|>


<commit_before>$(window).load(function(){
  // Place for us to stash debug info for JS console access.
  window.sensors = {};

  // ---------------------------------------------------------------------------
  // Utility functions
  // ---------------------------------------------------------------------------
  function log(msg) {
    try{
      console.log(msg);
    } catch (e) {
      // Browser doesn't support console.
    }
  }

  // ---------------------------------------------------------------------------
  // Startup.
  // ---------------------------------------------------------------------------
  function drawChart() {

    jQuery.getJSON("/readings", null, function(data) {
      log("Downloaded " + data["readings"].length + " readings");
      window.sensors["data"] = data;
      var chartData = new google.visualization.DataTable();
      chartData.addColumn('datetime', 'Date');
      chartData.addColumn('number', 'Temperature/C');

      var readings = data["readings"];
      for (var i = 0; i < readings.length; i++) {
        readings[i][0] = new Date(readings[i][0]*1000);
      }

      chartData.addRows(readings);

      // Set chart options
      var options = {
          'title':'Temperature',
          'width': 900,
          'height':600,
          'hAxis': {'format': 'd MMM ha',
                    'slanted_text': true}
      };

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(chartData, options);
    })
    .error(function() {
      log("Failed to load readings");
    });
  }

  drawChart();
});
<commit_msg>Tweak size<commit_after>$(window).load(function(){
  // Place for us to stash debug info for JS console access.
  window.sensors = {};

  // ---------------------------------------------------------------------------
  // Utility functions
  // ---------------------------------------------------------------------------
  function log(msg) {
    try{
      console.log(msg);
    } catch (e) {
      // Browser doesn't support console.
    }
  }

  // ---------------------------------------------------------------------------
  // Startup.
  // ---------------------------------------------------------------------------
  function drawChart() {

    jQuery.getJSON("/readings", null, function(data) {
      log("Downloaded " + data["readings"].length + " readings");
      window.sensors["data"] = data;
      var chartData = new google.visualization.DataTable();
      chartData.addColumn('datetime', 'Date');
      chartData.addColumn('number', 'Temperature/C');

      var readings = data["readings"];
      for (var i = 0; i < readings.length; i++) {
        readings[i][0] = new Date(readings[i][0]*1000);
      }

      chartData.addRows(readings);

      // Set chart options
      var options = {
          'title':'Temperature',
          'width': 1170,
          'height': 800,
          'hAxis': {'format': 'd MMM ha',
                    'slanted_text': true}
      };

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(chartData, options);
    })
    .error(function() {
      log("Failed to load readings");
    });
  }

  drawChart();
});
<|endoftext|>


<commit_before>YUI.add("bid-model-list", function (Y) {

    var BidList = Y.Base.create("bid-list", Y.ModelList, [], {

        model: Y.Bridge.Model.Bid,

        bids: function () {
            return Y.Array.map(this._items, function (bid) {
                return bid.getAttrs(["bid", "alert", "message"]);
            });
        },

        last: function (number) {
            number || (number = 1);

            return this._items.slice(-number);
        },

        isCompleted: function () {
            if (this.size() > 3) {
                return Y.Array.every(this.last(3), function (bid) {
                    return bid.get("bid") === "PASS";
                });
            } else {
                return false;
            }
        }

    }, {

        ATTRS: {

        }

    });

    Y.namespace("Bridge.Model").BidList = BidList;

}, "", { requires: ["model-list", "bid-model", "collection"] });
<commit_msg>added contract/modifier methods<commit_after>YUI.add("bid-model-list", function (Y) {

    var BidList = Y.Base.create("bid-list", Y.ModelList, [], {

        model: Y.Bridge.Model.Bid,

        bids: function () {
            return Y.Array.map(this._items, function (bid) {
                return bid.getAttrs(["bid", "alert", "message"]);
            });
        },

        last: function (number) {
            number || (number = 1);

            return this._items.slice(-number);
        },

        contracts: function () {
            return Y.Array.reduce(this._items, [], function (result, bid) {
                if (Y.Bridge.isContract(bid.get("bid"))) {
                    result.push(bid.get("bid"));
                }
                return result;
            });
        },

        modifier: function () {
            return Y.Array.reduce(this._items, undefined, function (result, bid) {
                if (Y.Bridge.isContract(bid.get("bid"))) {
                    return undefined;
                } else if (Y.Bridge.isModifier(bid.get("bid"))) {
                    return bid.get("bid");
                } else {
                    return result;
                }
            });
        },

        contract: function () {
            var contract,
                modifier = this.modifier(),
                contracts = this.contracts();

            contract = contracts[contracts.length - 1];

            if (Y.Lang.isValue(contract) && Y.Lang.isValue(modifier)) {
                return contract + modifier;
            } else {
                return contract;
            }
        },

        isCompleted: function () {
            if (this.size() > 3) {
                return Y.Array.every(this.last(3), function (bid) {
                    return bid.get("bid") === "PASS";
                });
            } else {
                return false;
            }
        }

    }, {

        ATTRS: {

        }

    });

    Y.namespace("Bridge.Model").BidList = BidList;

}, "", { requires: ["model-list", "bid-model", "collection"] });
<|endoftext|>


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

    angular.module('tubular.services')
        .provider('tubularConfig', function () {

            var provider = this;
            provider.platform = {};
            var PLATFORM = 'platform';

            var configProperties = {
                webApi: {
                    tokenUrl: PLATFORM,
                    refreshTokenUrl: PLATFORM,
                    enableRefreshTokens: PLATFORM,
                    requireAuthentication: PLATFORM,
                    baseUrl: PLATFORM
                },
                platform: {}
            };

            createConfig(configProperties, provider, '');

            // Default
            // -------------------------
            setPlatformConfig('default', {
                webApi: {
                    tokenUrl: '/api/token',
                    refreshTokenUrl: '/api/token',
                    enableRefreshTokens: false,
                    requireAuthentication: true,
                    baseUrl: '/api'
                }
            });

            // private: used to set platform configs
            function setPlatformConfig(platformName, platformConfigs) {
                configProperties.platform[platformName] = platformConfigs;
                provider.platform[platformName] = {};

                addConfig(configProperties, configProperties.platform[platformName]);

                createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
            }

            // add new platform configs
            function addConfig(configObj, platformObj) {
                for (var n in configObj) {
                    if (n != PLATFORM && configObj.hasOwnProperty(n)) {
                        if (angular.isObject(configObj[n])) {
                            if (angular.isUndefined(platformObj[n])) {
                                platformObj[n] = {};
                            }
                            addConfig(configObj[n], platformObj[n]);

                        } else if (angular.isUndefined(platformObj[n])) {
                            platformObj[n] = null;
                        }
                    }
                }
            }

            // create get/set methods for each config
            function createConfig(configObj, providerObj, platformPath) {
                angular.forEach(configObj, function (value, namespace) {

                    if (angular.isObject(configObj[namespace])) {
                        // recursively drill down the config object so we can create a method for each one
                        providerObj[namespace] = {};
                        createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);

                    } else {
                        // create a method for the provider/config methods that will be exposed
                        providerObj[namespace] = function (newValue) {
                            if (arguments.length) {
                                configObj[namespace] = newValue;
                                return providerObj;
                            }
                            if (configObj[namespace] == PLATFORM) {
                                // if the config is set to 'platform', then get this config's platform value
                                // var platformConfig = stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
                                // if (platformConfig || platformConfig === false) {
                                //     return platformConfig;
                                // }
                                // didnt find a specific platform config, now try the default
                                return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
                            }
                            return configObj[namespace];
                        };
                    }

                });
            }

            function stringObj(obj, str) {
                str = str.split('.');
                for (var i = 0; i < str.length; i++) {
                    if (obj && angular.isDefined(obj[str[i]])) {
                        obj = obj[str[i]];
                    } else {
                        return null;
                    }
                }
                return obj;
            }

            provider.setPlatformConfig = setPlatformConfig;

            // private: Service definition for internal Tubular use
            /**
             * @ngdoc service
             * @name tubularConfig
             * @module TubularModule
             * @private
             */
            provider.$get = function () {
                return provider;
            };
        });
})(angular);<commit_msg>Removed @private tag.<commit_after>(function (angular) {
    'use strict';

    angular.module('tubular.services')
        .provider('tubularConfig', function () {

            var provider = this;
            provider.platform = {};
            var PLATFORM = 'platform';

            var configProperties = {
                webApi: {
                    tokenUrl: PLATFORM,
                    refreshTokenUrl: PLATFORM,
                    enableRefreshTokens: PLATFORM,
                    requireAuthentication: PLATFORM,
                    baseUrl: PLATFORM
                },
                platform: {}
            };

            createConfig(configProperties, provider, '');

            // Default
            // -------------------------
            setPlatformConfig('default', {
                webApi: {
                    tokenUrl: '/api/token',
                    refreshTokenUrl: '/api/token',
                    enableRefreshTokens: false,
                    requireAuthentication: true,
                    baseUrl: '/api'
                }
            });

            // private: used to set platform configs
            function setPlatformConfig(platformName, platformConfigs) {
                configProperties.platform[platformName] = platformConfigs;
                provider.platform[platformName] = {};

                addConfig(configProperties, configProperties.platform[platformName]);

                createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
            }

            // add new platform configs
            function addConfig(configObj, platformObj) {
                for (var n in configObj) {
                    if (n != PLATFORM && configObj.hasOwnProperty(n)) {
                        if (angular.isObject(configObj[n])) {
                            if (angular.isUndefined(platformObj[n])) {
                                platformObj[n] = {};
                            }
                            addConfig(configObj[n], platformObj[n]);

                        } else if (angular.isUndefined(platformObj[n])) {
                            platformObj[n] = null;
                        }
                    }
                }
            }

            // create get/set methods for each config
            function createConfig(configObj, providerObj, platformPath) {
                angular.forEach(configObj, function (value, namespace) {

                    if (angular.isObject(configObj[namespace])) {
                        // recursively drill down the config object so we can create a method for each one
                        providerObj[namespace] = {};
                        createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);

                    } else {
                        // create a method for the provider/config methods that will be exposed
                        providerObj[namespace] = function (newValue) {
                            if (arguments.length) {
                                configObj[namespace] = newValue;
                                return providerObj;
                            }
                            if (configObj[namespace] == PLATFORM) {
                                // if the config is set to 'platform', then get this config's platform value
                                // var platformConfig = stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
                                // if (platformConfig || platformConfig === false) {
                                //     return platformConfig;
                                // }
                                // didnt find a specific platform config, now try the default
                                return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
                            }
                            return configObj[namespace];
                        };
                    }

                });
            }

            function stringObj(obj, str) {
                str = str.split('.');
                for (var i = 0; i < str.length; i++) {
                    if (obj && angular.isDefined(obj[str[i]])) {
                        obj = obj[str[i]];
                    } else {
                        return null;
                    }
                }
                return obj;
            }

            provider.setPlatformConfig = setPlatformConfig;

            // private: Service definition for internal Tubular use
            provider.$get = function () {
                return provider;
            };
        });
})(angular);<|endoftext|>


<commit_before>define(['common'], function (MAS) {
  'use strict';

  var defaults = {
    optionalCookies: []
  };

  var CookieController = function (opts) {
    this.config = $.extend({}, defaults, opts);
    this.addOptionalCookies();
  };

  CookieController.prototype.addOptionalCookies = function() {
    console.log('MAS: ', MAS);

    var analytics = {
      name : 'analytics',
      recommendedState: true,
      lawfulBasis: 'legitimate interest',
      cookies: ['_ga', '_gid', '_gat', '__utma', '__utmt', '__utmb', '__utmc', '__utmz', '__utmv'],
      label: MAS.text.cookieController.optionalCookies.analytics.label,
      description: MAS.text.cookieController.optionalCookies.analytics.description,

      onAccept : function(){
        // Add Google Analytics
        (function (i,s,o,g,r,a,m) {
          i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-XXXXX-Y', 'auto');

        ga('send', 'pageview');
        // End Google Analytics
      },
      onRevoke: function(){
      // Disable Google Analytics
      window['ga-disable-UA-XXXXX-Y'] = true;
      // End Google Analytics
      }
    };

    this.config.optionalCookies.push(analytics);
  }

  CookieController.prototype.loadModule = function() {
    console.log('loadModule!');

    CookieControl.load(this.config);
  }

  return CookieController;
});
<commit_msg>Adds onAccept/onRevoke methods from Merkle<commit_after>define(['common'], function (MAS) {
  'use strict';

  var defaults = {
    optionalCookies: []
  };

  var CookieController = function (opts) {
    this.config = $.extend({}, defaults, opts);
    this.addOptionalCookies();
  };

  CookieController.prototype.addOptionalCookies = function() {
    var analytics = {
      name : 'analytics',
      recommendedState: true,
      lawfulBasis: 'legitimate interest',
      cookies: ['_ga', '_gid', '_gat', '__utma', '__utmt', '__utmb', '__utmc', '__utmz', '__utmv'],
      label: MAS.text.cookieController.optionalCookies.analytics.label,
      description: MAS.text.cookieController.optionalCookies.analytics.description,

      onAccept: function() {
        window.dataLayer = window.dataLayer || [];

        window.dataLayer.push({
          'event': 'civicConsentResponse'
        });
      },

      onRevoke: function() {
        window.dataLayer = window.dataLayer || [];

        window.dataLayer.push({
          'event': 'civicConsentResponse'
        });
      }
    };

    this.config.optionalCookies.push(analytics);
  }

  CookieController.prototype.loadModule = function() {
    CookieControl.load(this.config);
  }

  return CookieController;
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import I18n from 'i18n-js';
import { assign } from 'lodash';
import classNames from 'classnames';
import Date from '../date';
import DateRangeValidator from '../../../utils/validations/date-range';
import DateHelper from '../../../utils/helpers/date';
import tagComponent from '../../../utils/helpers/tags';
import StyledDateRange from './date-range.style';

class DateRange extends React.Component {
  static propTypes = {
    /**
     * Optional label for endDate field
     * eslint is disabled because the prop is used to determine the label in the dateProps function
     */
    endLabel: PropTypes.string, // eslint-disable-line react/no-unused-prop-types

    /**
     * Custom callback - receives array of startDate and endDate
     */
    onChange: PropTypes.func.isRequired,

    /**
     * An array containing the value of startDate and endDate
     */
    value: PropTypes.array.isRequired,

    /**
     * Optional label for startDate field
     * eslint is disabled because the prop is used to determine the label in the dateProps function
     */
    startLabel: PropTypes.string, // eslint-disable-line react/no-unused-prop-types

    /**
     * Custom message for startDate field
     */
    startMessage: PropTypes.string,

    /**
     * Custom message for endDate field
     */
    endMessage: PropTypes.string,

    /**
     * Display labels inline
     */
    labelsInline: PropTypes.bool,

    /**
     * Props for the child start Date component
     */
    startDateProps: PropTypes.objectOf(Date.propTypes),

    /**
     * Props for the child end Date component
     */
    endDateProps: PropTypes.objectOf(Date.propTypes)
  };

  /**
   * onChange function -triggers validations on both fields and updates opposing field when one changed.
   */
  _onChange = (changedDate, ev) => {
    const newValue = ev.target.value;

    if (changedDate === 'startDate') {
      this.props.onChange([newValue, this.endDate]);
      if (DateHelper.isValidDate(this.endDate)) {
        // resets validations on opposing field. This is a code smell
        this._endDate._handleContentChange();
      }
    }

    if (changedDate === 'endDate') {
      this.props.onChange([this.startDate, newValue]);
    }

    // Triggers validations on both fields
    if (DateHelper.isValidDate(newValue)) {
      this._startDate.handleBlur();
      this._endDate.handleBlur();
    }
  }

  /**
   * The startDate value
   */
  get startDate() {
    if (this.props.startDateProps && this.props.startDateProps.value) {
      return this.props.startDateProps.value;
    }
    return this.props.value[0];
  }

  /**
   * The endDate value
   */
  get endDate() {
    if (this.props.endDateProps && this.props.endDateProps.value) {
      return this.props.endDateProps.value;
    }
    return this.props.value[1];
  }

  /**
   * The error message for the start message.
   */
  get startMessage() {
    return this.props.startMessage
      || I18n.t('errors.messages.date_range', { defaultValue: 'Start date must not be later than the end date' });
  }

  /**
   * The error message for the end message.
   */
  get endMessage() {
    return this.props.endMessage
     || I18n.t('errors.messages.date_range', { defaultValue: 'End date cannot be earlier than the start date' });
  }

  /**
   * Handle focus on start date field
   */
  focusStart = () => {
    this._endDate.closeDatePicker();
  }

  /**
   * Handle focus on end date field
   */
  focusEnd = () => {
    this._startDate.closeDatePicker();
  }

  /**
   * The startDate props
   */
  startDateProps() {
    return this.dateProps('start', [
      new DateRangeValidator({
        endDate: this.endDate,
        messageText: this.startMessage
      })
    ]);
  }

  /**
   * The endDate props
   */
  endDateProps() {
    return this.dateProps('end', [
      new DateRangeValidator({
        startDate: this.startDate,
        messageText: this.endMessage
      })
    ]);
  }

  /**
   * The startDate/endDate props
   */
  dateProps(propsKey, defaultValidations) {
    const dateProps = this.props[`${propsKey}DateProps`] || {};

    const props = assign({}, {
      label: this.props[`${propsKey}Label`],
      labelInline: this.props.labelsInline,
      onChange: this._onChange.bind(null, `${propsKey}Date`),
      ref: (c) => { this[`_${propsKey}Date`] = c; },
      value: this[`${propsKey}Date`]
    }, dateProps);

    props.className = classNames(
      dateProps.className
    );

    props.validations = defaultValidations.concat(dateProps.validations || []);
    return props;
  }

  render () {
    return (
      <StyledDateRange { ...tagComponent('date-range', this.props) }>
        <Date
          { ...this.startDateProps() } onFocus={ this.focusStart }
          data-element='start-date'
        />
        <Date
          { ...this.endDateProps() } onFocus={ this.focusEnd }
          data-element='end-date'
        />
      </StyledDateRange>
    );
  }
}

export default DateRange;
<commit_msg>removed handleContentChange from startdate<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import I18n from 'i18n-js';
import { assign } from 'lodash';
import classNames from 'classnames';
import Date from '../date';
import DateRangeValidator from '../../../utils/validations/date-range';
import DateHelper from '../../../utils/helpers/date';
import tagComponent from '../../../utils/helpers/tags';
import StyledDateRange from './date-range.style';

class DateRange extends React.Component {
  static propTypes = {
    /**
     * Optional label for endDate field
     * eslint is disabled because the prop is used to determine the label in the dateProps function
     */
    endLabel: PropTypes.string, // eslint-disable-line react/no-unused-prop-types

    /**
     * Custom callback - receives array of startDate and endDate
     */
    onChange: PropTypes.func.isRequired,

    /**
     * An array containing the value of startDate and endDate
     */
    value: PropTypes.array.isRequired,

    /**
     * Optional label for startDate field
     * eslint is disabled because the prop is used to determine the label in the dateProps function
     */
    startLabel: PropTypes.string, // eslint-disable-line react/no-unused-prop-types

    /**
     * Custom message for startDate field
     */
    startMessage: PropTypes.string,

    /**
     * Custom message for endDate field
     */
    endMessage: PropTypes.string,

    /**
     * Display labels inline
     */
    labelsInline: PropTypes.bool,

    /**
     * Props for the child start Date component
     */
    startDateProps: PropTypes.objectOf(Date.propTypes),

    /**
     * Props for the child end Date component
     */
    endDateProps: PropTypes.objectOf(Date.propTypes)
  };

  /**
   * onChange function -triggers validations on both fields and updates opposing field when one changed.
   */
  _onChange = (changedDate, ev) => {
    const newValue = ev.target.value;

    if (changedDate === 'startDate') {
      this.props.onChange([newValue, this.endDate]);
    }

    if (changedDate === 'endDate') {
      this.props.onChange([this.startDate, newValue]);
    }

    // Triggers validations on both fields
    if (DateHelper.isValidDate(newValue)) {
      this._startDate.handleBlur();
      this._endDate.handleBlur();
    }
  }

  /**
   * The startDate value
   */
  get startDate() {
    if (this.props.startDateProps && this.props.startDateProps.value) {
      return this.props.startDateProps.value;
    }
    return this.props.value[0];
  }

  /**
   * The endDate value
   */
  get endDate() {
    if (this.props.endDateProps && this.props.endDateProps.value) {
      return this.props.endDateProps.value;
    }
    return this.props.value[1];
  }

  /**
   * The error message for the start message.
   */
  get startMessage() {
    return this.props.startMessage
      || I18n.t('errors.messages.date_range', { defaultValue: 'Start date must not be later than the end date' });
  }

  /**
   * The error message for the end message.
   */
  get endMessage() {
    return this.props.endMessage
     || I18n.t('errors.messages.date_range', { defaultValue: 'End date cannot be earlier than the start date' });
  }

  /**
   * Handle focus on start date field
   */
  focusStart = () => {
    this._endDate.closeDatePicker();
  }

  /**
   * Handle focus on end date field
   */
  focusEnd = () => {
    this._startDate.closeDatePicker();
  }

  /**
   * The startDate props
   */
  startDateProps() {
    return this.dateProps('start', [
      new DateRangeValidator({
        endDate: this.endDate,
        messageText: this.startMessage
      })
    ]);
  }

  /**
   * The endDate props
   */
  endDateProps() {
    return this.dateProps('end', [
      new DateRangeValidator({
        startDate: this.startDate,
        messageText: this.endMessage
      })
    ]);
  }

  /**
   * The startDate/endDate props
   */
  dateProps(propsKey, defaultValidations) {
    const dateProps = this.props[`${propsKey}DateProps`] || {};

    const props = assign({}, {
      label: this.props[`${propsKey}Label`],
      labelInline: this.props.labelsInline,
      onChange: this._onChange.bind(null, `${propsKey}Date`),
      ref: (c) => { this[`_${propsKey}Date`] = c; },
      value: this[`${propsKey}Date`]
    }, dateProps);

    props.className = classNames(
      dateProps.className
    );

    props.validations = defaultValidations.concat(dateProps.validations || []);
    return props;
  }

  render () {
    return (
      <StyledDateRange { ...tagComponent('date-range', this.props) }>
        <Date
          { ...this.startDateProps() } onFocus={ this.focusStart }
          data-element='start-date'
        />
        <Date
          { ...this.endDateProps() } onFocus={ this.focusEnd }
          data-element='end-date'
        />
      </StyledDateRange>
    );
  }
}

export default DateRange;
<|endoftext|>


<commit_before>import React from "react";
import Helmet from "react-helmet";
import tag from "tag-hoc";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { createSelector } from "reselect";
import {
  Link,
  Icon,
  styled,
  injection,
  Text,
  ThemeProvider,
  themes,
  injectGlobal
} from "@patternplate/components";

import * as actions from "../actions";
import * as demo from "../selectors/demo";

import Favicon from "./favicon";
import Indicator from "./indicator";
import ConnectedLink from "./link";
import Logo from "./logo";
import Message from "./message";
import Navigation, { NavigationHeader, NavigationToolbar } from "./navigation";
import ToggleNavigation from "./toggle-navigation";
import ToggleSearch from "./toggle-search";
import Search from "./search";

export default connect(mapProps, mapDispatch)(Application);

const selectThemes = createSelector(
  state => state.config.color,
  color => themes(color)
);

const selectLines = createSelector(
  state => state.messages,
  demo.selectSrc,
  (messages, src) => (messages[src] || "").split("\n").filter(Boolean)
);

const selectMessage = createSelector(selectLines, lines =>
  lines
    .slice(0, 2)
    .map(l => l.trim())
    .join("\n")
);

const selectHasMessage = createSelector(
  selectMessage,
  message => typeof message === "string" && message !== ""
);

function mapProps(state) {
  return {
    base: state.base,
    description: state.schema.description,
    lightbox: state.lightbox,
    location: state.routing.locationBeforeTransitions,
    networkEnabled: state.networkEnabled,
    logo: state.config.logo,
    navigationEnabled: state.navigationEnabled,
    searchEnabled: state.searchEnabled,
    theme: state.theme,
    themes: selectThemes(state),
    title: state.config.title || state.schema.name,
    hasMessage: selectHasMessage(state)
  };
}

function mapDispatch(dispatch) {
  return bindActionCreators(
    {
      onLoad: () => actions.listen({ url: "api" }),
      onResize: actions.windowResize
    },
    dispatch
  );
}

const injections = [
  {
    target: Link,
    source: ConnectedLink
  }
];

function Application(props) {
  // Special mode for automated screenshots
  if (props.location.query.screenshot === "true") {
    injectGlobal`
      body {
        height: calc(100vh - 100px)!important;
        width: calc(100vw - 100px)!important;
        margin: 50px!important;
        border-radius: 10px!important;
        box-shadow: 0 0 30px rgba(0, 0, 0, 0.15)!important;
        overflow: hidden!important;
      }
    `;
  }

  return (
    <injection.InjectionProvider injections={injections}>
      <ThemeProvider theme={props.themes[props.theme]}>

            </React.Fragment>
          </ThemeProvider>

                </StyledBrowserContent>

              </StyledBrowserContainer>
            </StyledBrowserWarning>

                  <Text>
                    - Try reloading the page
                  </Text>
                  <Text>
                    - Report the problem at github.com/patternplate/patternplate
                  </Text>
                </StyledBrowserContent>

              </StyledBrowserContainer>
            </StyledBrowserWarning>
              {
                props.hasMessage && (

                )
              }
              {props.children}
              {props.searchEnabled && (
                <ThemeProvider theme={props.themes.dark}>

                  </StyledSearchBox>
                </ThemeProvider>
              )}
            </StyledContent>
          </StyledContentContainer>
        </StyledApplication>
      </ThemeProvider>
    </injection.InjectionProvider>
  );
}

const WIDTH = 300;
const NAVIGATION_WIDTH = props => (props.enabled ? WIDTH : 0);
const TOOLBAR_HEIGHT = 60;

const StyledWarningLabel = styled(Text)`
  font-weight: bold;
  margin-bottom: 1.3em;
`;

const StyledBrowserWarning = styled.div`
  display: none; /* overridden by separate js if needed */
  box-sizing: border-box;
  position: absolute;
  position: sticky;
  top: 0;
  z-index: 4;
  right: 0;
  left: 0;
  width: 100%;
  padding: 15px 20px;
  padding-left: ${props => props.navigationEnabled ? 20 : 60}px;
  background: ${props => props.theme.warning};
`;

const StyledBrowserContainer = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 1240px;
  margin: 0 auto;
  justify-content: space-between;
`;

const StyledBrowserContent = styled.div`

`;

const StyledBrowserText = styled(Text)`
  margin-bottom: 1.3em;
`

const StyledBrowserContainerClose = styled(Link)`
  flex-shrink: 0;
  margin-left: 15px;
  &:link,
  &:visited,
  &:active {
    color: ${props => props.theme.color};
  }
`;

const StyledApplication = styled.div`
  position: relative;
  box-sizing: border-box;
  display: flex;
  width: 100%;
  height: 100%;
  background: ${props => props.theme.background};
`;

const StyledNavigationBox = styled(tag(["enabled"])("div"))`
  position: relative;
  z-index: 2;
  height: 100%;
  width: ${NAVIGATION_WIDTH}px;
  flex: 0 0 ${NAVIGATION_WIDTH}px;
`;

const StyledMessageBox = styled.div`
  position: absolute;
  box-sizing: border-box;
  z-index: 3;
  padding: 15px;
  width: 100%;
  overflow: hidden;
`;

const StyledContent = styled.div`
  flex: 1 1 100%;
  width: 100%;
`;

const StyledContentContainer = styled.div`
  flex: 1 1 calc(100% - ${NAVIGATION_WIDTH}px);
  width: calc(100% - ${NAVIGATION_WIDTH}px);
  flex-direction: column;
  overflow: auto;
  position: relative;
`;

const StyledSearchBox = styled.div`
  position: absolute;
  top: 12.5vh;
  bottom: 10vh;
  right: 0;
  left: 0;
  width: 100%;
  pointer-events: none;
`;

const StyledSearchFrame = styled.div`
  width: 90%;
  min-width: 320px;
  max-width: 750px;
  max-height: 100%;
  margin: 0 auto;
  overflow: hidden;
`;

const StyledFloatingBox = styled.div`
  position: absolute;
  pointer-events: none;
  z-index: 2;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 10px 15px;
  height: 300px;
  display: flex;
`;

const StyledInfoPane = styled.div`
  flex: 0 0 auto;
  box-sizing: border-box;
  pointer-events: all;
`;

const StyledPane = styled.div`
  flex: 1 1 auto;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  overflow: hidden;
  pointer-events: all;
`;

const NavigationControl = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  z-index: 5;
  top: 0;
  left: ${props => props.enabled ? 300 : 0}px;
  transform: translate(-${props => props.enabled ? 100 : 0}%);
  color: ${props => props.enabled ? props.theme.color : props.theme.background};
  width: 60px;
  height: 60px;
`;

function meta(props) {
  return [
    { name: "description", content: props.description },
    { name: "viewport", content: "width=device-width, initial-scale=1" }
  ];
}
<commit_msg>fix: used fixed positioning again<commit_after>import React from "react";
import Helmet from "react-helmet";
import tag from "tag-hoc";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { createSelector } from "reselect";
import {
  Link,
  Icon,
  styled,
  injection,
  Text,
  ThemeProvider,
  themes,
  injectGlobal
} from "@patternplate/components";

import * as actions from "../actions";
import * as demo from "../selectors/demo";

import Favicon from "./favicon";
import Indicator from "./indicator";
import ConnectedLink from "./link";
import Logo from "./logo";
import Message from "./message";
import Navigation, { NavigationHeader, NavigationToolbar } from "./navigation";
import ToggleNavigation from "./toggle-navigation";
import ToggleSearch from "./toggle-search";
import Search from "./search";

export default connect(mapProps, mapDispatch)(Application);

const selectThemes = createSelector(
  state => state.config.color,
  color => themes(color)
);

const selectLines = createSelector(
  state => state.messages,
  demo.selectSrc,
  (messages, src) => (messages[src] || "").split("\n").filter(Boolean)
);

const selectMessage = createSelector(selectLines, lines =>
  lines
    .slice(0, 2)
    .map(l => l.trim())
    .join("\n")
);

const selectHasMessage = createSelector(
  selectMessage,
  message => typeof message === "string" && message !== ""
);

function mapProps(state) {
  return {
    base: state.base,
    description: state.schema.description,
    lightbox: state.lightbox,
    location: state.routing.locationBeforeTransitions,
    networkEnabled: state.networkEnabled,
    logo: state.config.logo,
    navigationEnabled: state.navigationEnabled,
    searchEnabled: state.searchEnabled,
    theme: state.theme,
    themes: selectThemes(state),
    title: state.config.title || state.schema.name,
    hasMessage: selectHasMessage(state)
  };
}

function mapDispatch(dispatch) {
  return bindActionCreators(
    {
      onLoad: () => actions.listen({ url: "api" }),
      onResize: actions.windowResize
    },
    dispatch
  );
}

const injections = [
  {
    target: Link,
    source: ConnectedLink
  }
];

function Application(props) {
  // Special mode for automated screenshots
  if (props.location.query.screenshot === "true") {
    injectGlobal`
      body {
        height: calc(100vh - 100px)!important;
        width: calc(100vw - 100px)!important;
        margin: 50px!important;
        border-radius: 10px!important;
        box-shadow: 0 0 30px rgba(0, 0, 0, 0.15)!important;
        overflow: hidden!important;
      }
    `;
  }

  return (
    <injection.InjectionProvider injections={injections}>
      <ThemeProvider theme={props.themes[props.theme]}>

            </React.Fragment>
          </ThemeProvider>

                </StyledBrowserContent>

              </StyledBrowserContainer>
            </StyledBrowserWarning>

                  <Text>
                    - Try reloading the page
                  </Text>
                  <Text>
                    - Report the problem at github.com/patternplate/patternplate
                  </Text>
                </StyledBrowserContent>

              </StyledBrowserContainer>
            </StyledBrowserWarning>
              {
                props.hasMessage && (

                )
              }
              {props.children}
              {props.searchEnabled && (
                <ThemeProvider theme={props.themes.dark}>

                  </StyledSearchBox>
                </ThemeProvider>
              )}
            </StyledContent>
          </StyledContentContainer>
        </StyledApplication>
      </ThemeProvider>
    </injection.InjectionProvider>
  );
}

const WIDTH = 300;
const NAVIGATION_WIDTH = props => (props.enabled ? WIDTH : 0);
const TOOLBAR_HEIGHT = 60;

const StyledWarningLabel = styled(Text)`
  font-weight: bold;
  margin-bottom: 1.3em;
`;

const StyledBrowserWarning = styled.div`
  display: none; /* overridden by separate js if needed */
  box-sizing: border-box;
  position: absolute;
  position: sticky;
  top: 0;
  z-index: 4;
  right: 0;
  left: 0;
  width: 100%;
  padding: 15px 20px;
  padding-left: ${props => props.navigationEnabled ? 20 : 60}px;
  background: ${props => props.theme.warning};
`;

const StyledBrowserContainer = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 1240px;
  margin: 0 auto;
  justify-content: space-between;
`;

const StyledBrowserContent = styled.div`

`;

const StyledBrowserText = styled(Text)`
  margin-bottom: 1.3em;
`

const StyledBrowserContainerClose = styled(Link)`
  flex-shrink: 0;
  margin-left: 15px;
  &:link,
  &:visited,
  &:active {
    color: ${props => props.theme.color};
  }
`;

const StyledApplication = styled.div`
  position: relative;
  box-sizing: border-box;
  display: flex;
  width: 100%;
  height: 100%;
  background: ${props => props.theme.background};
`;

const StyledNavigationBox = styled(tag(["enabled"])("div"))`
  position: relative;
  z-index: 2;
  height: 100%;
  width: ${NAVIGATION_WIDTH}px;
  flex: 0 0 ${NAVIGATION_WIDTH}px;
`;

const StyledMessageBox = styled.div`
  position: absolute;
  box-sizing: border-box;
  z-index: 3;
  padding: 15px;
  width: 100%;
  overflow: hidden;
`;

const StyledContent = styled.div`
  flex: 1 1 100%;
  width: 100%;
`;

const StyledContentContainer = styled.div`
  flex: 1 1 calc(100% - ${NAVIGATION_WIDTH}px);
  width: calc(100% - ${NAVIGATION_WIDTH}px);
  flex-direction: column;
  overflow: auto;
  position: relative;
`;

const StyledSearchBox = styled.div`
  position: fixed;
  top: 12.5vh;
  bottom: 10vh;
  right: 0;
  left: ${props => props.navigationEnabled ? 300 : 0}px;
  width: ${props => props.navigationEnabled ? `calc(100% - 300px)` : `100%`};
  pointer-events: none;
`;

const StyledSearchFrame = styled.div`
  width: 90%;
  min-width: 320px;
  max-width: 750px;
  max-height: 100%;
  margin: 0 auto;
  overflow: hidden;
`;

const StyledFloatingBox = styled.div`
  position: absolute;
  pointer-events: none;
  z-index: 2;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 10px 15px;
  height: 300px;
  display: flex;
`;

const StyledInfoPane = styled.div`
  flex: 0 0 auto;
  box-sizing: border-box;
  pointer-events: all;
`;

const StyledPane = styled.div`
  flex: 1 1 auto;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  overflow: hidden;
  pointer-events: all;
`;

const NavigationControl = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  z-index: 5;
  top: 0;
  left: ${props => props.enabled ? 300 : 0}px;
  transform: translate(-${props => props.enabled ? 100 : 0}%);
  color: ${props => props.enabled ? props.theme.color : props.theme.background};
  width: 60px;
  height: 60px;
`;

function meta(props) {
  return [
    { name: "description", content: props.description },
    { name: "viewport", content: "width=device-width, initial-scale=1" }
  ];
}
<|endoftext|>


<commit_before>function OAuthSignatureMethodHMACSHA1() {
    this.name = 'HMAC-SHA1';
    this.sign = function(consumer_secret, token_secret){
        this.hmac(consumer_secret, '');
        var signature = [];
        return signature.join('&');
    };

    this.blocksize = 64;
    this.hash = function (message) {
        var h0 = 0x67452301;
        var h1 = 0xEFCDAB89;
        var h2 = 0x98BADCFE;
        var h3 = 0x10325476;
        var h4 = 0xC3D2E1F0;

        message = OAuthUtilities.toByteString(message);
        message += '80';

        var bit_length = message.length * 4;
        var bit_length_hex = parseInt(bit_length, 16);
        var bit_length_hex_length = (bit_length_hex + '').length;

        var last_64_bit_hex = new Array(17 - bit_length_hex_length).join(0) + bit_length_hex;
        var pad_l = 512 - ((bit_length + 64) % 512);
        alert(pad_l);
        var pad = new Array(1 + pad_l).join(0);

        message += pad + last_64_bit_hex;
        alert(message.length * 4);
    }
}

OAuthSignatureMethodHMACSHA1.prototype = new OAuthSignatureMethod();

OAuthConsumer.signatureMethods['HMAC-SHA1'] = OAuthSignatureMethodHMACSHA1;

<commit_msg>remove unworking code in preperation for 3rd party library<commit_after>function OAuthSignatureMethodHMACSHA1() {
    this.name = 'HMAC-SHA1';
    this.sign = function(consumer_secret, token_secret){
        var signature = [];
        return signature.join('&');
    };

    this.blocksize = 64;
    this.hash = function (message) {/*stub*/}
}

OAuthSignatureMethodHMACSHA1.prototype = new OAuthSignatureMethod();

OAuthConsumer.signatureMethods['HMAC-SHA1'] = OAuthSignatureMethodHMACSHA1;

<|endoftext|>


<commit_before>'use strict';
var Reflux = require('reflux');
var React = require('react/addons');

var IndTimeliness = module.exports = React.createClass({

  propTypes: {
    data: React.PropTypes.array
  },

  render: function() {

    // THIS NEEDS TO BE CLEANED.
    // DEV NOTE: For now we're doing here a switch based on comparison.
    // This should be done in the parent and the data passed through props.data

    var data = null;
    var comparison = this.props.comparison || 'all';
    switch(comparison) {
      case 'all':
        data = (

Average timeline

        );
      break;
      case 'contract_procedure':
        data = (

Average timeline

        );
      break;
      case 'level_gov':
        data = (

Average timeline

        );
      break;
    }
    return (

Overview

Timely delivery of goods, works and services is a key indication of success in procurement, whether done by private sector companies or governments.

        {data}

    );
  }
});<commit_msg>Timeliness incorporates timechart<commit_after>'use strict';
var Reflux = require('reflux');
var React = require('react/addons');
var _ = require('lodash');
var TimeChart = require('../charts/timechart');

var IndTimeliness = module.exports = React.createClass({

  propTypes: {
    data: React.PropTypes.object
  },

  render: function() {

    var chartData = this.props.data.charts || [];
    var timeChartData = _.find(chartData, {id: 'average-timeline'});
    var timeCharts;

    if (timeChartData) {
      timeCharts =
<TimeChart data={timeChartData.data} x={timeChartData.x}  y={timeChartData.y} />

    }

    return (

Overview

Timely delivery of goods, works and services is a key indication of success in procurement, whether done by private sector companies or governments.

Average timeline

          {timeCharts ?
{timeCharts}
 : null}

Average timeline

    );
  }
});
<|endoftext|>


<commit_before>/**
 * @ngdoc directive
 * @name ionSideMenuContent
 * @module ionic
 * @restrict E
 * @parent ionic.directive:ionSideMenus
 *
 * @description
 * A container for the main visible content, sibling to one or more
 * {@link ionic.directive:ionSideMenu} directives.
 *
 * @usage
 * ```html
 * <ion-side-menu-content
 *   edge-drag-threshold="true"
 *   drag-content="true">
 * </ion-side-menu-content>
 * ```
 * For a complete side menu example, see the
 * {@link ionic.directive:ionSideMenus} documentation.
 *
 * @param {boolean=} drag-content Whether the content can be dragged. Default true.
 * @param {boolean|number=} edge-drag-threshold Whether the content drag can only start if it is below a certain threshold distance from the edge of the screen.  Default false. Accepts three types of values:
   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.
   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
 *
 */
IonicModule
.directive('ionSideMenuContent', [
  '$timeout',
  '$ionicGesture',
function($timeout, $ionicGesture) {

  return {
    restrict: 'EA', //DEPRECATED 'A'
    require: '^ionSideMenus',
    scope: true,
    compile: function(element, attr) {
      return { pre: prelink };
      function prelink($scope, $element, $attr, sideMenuCtrl) {
        var startCoord = null;
        var primaryScrollAxis = null;

        $element.addClass('menu-content pane');

        if (isDefined(attr.dragContent)) {
          $scope.$watch(attr.dragContent, function(value) {
            sideMenuCtrl.canDragContent(value);
          });
        } else {
          sideMenuCtrl.canDragContent(true);
        }

        if (isDefined(attr.edgeDragThreshold)) {
          $scope.$watch(attr.edgeDragThreshold, function(value) {
            sideMenuCtrl.edgeDragThreshold(value);
          });
        }

        // Listen for taps on the content to close the menu
        function onContentTap(e) {
          if(sideMenuCtrl.getOpenAmount() !== 0) {
            sideMenuCtrl.close();
            e.gesture.srcEvent.preventDefault();
            startCoord = null;
            primaryScrollAxis = null;
          }
        }

        function onDragX(e) {
          if(!sideMenuCtrl.isDraggableTarget(e)) return;

          if( getPrimaryScrollAxis(e) == 'x') {
            sideMenuCtrl._handleDrag(e);
            e.gesture.srcEvent.preventDefault();
          }
        }

        function onDragY(e) {
          if( getPrimaryScrollAxis(e) == 'x' ) {
            e.gesture.srcEvent.preventDefault();
          }
        }

        function onDragRelease(e) {
          sideMenuCtrl._endDrag(e);
          startCoord = null;
          primaryScrollAxis = null;
        }

        function getPrimaryScrollAxis(gestureEvt) {
          // gets whether the user is primarily scrolling on the X or Y
          // If a majority of the drag has been on the Y since the start of
          // the drag, but the X has moved a little bit, it's still a Y drag

          if(primaryScrollAxis) {
            // we already figured out which way they're scrolling
            return primaryScrollAxis
          }

          if(gestureEvt && gestureEvt.gesture) {

            if(!startCoord) {
              // get the starting point
              startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);

            } else {
              // we already have a starting point, figure out which direction they're going
              var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);

              var xDistance = Math.abs(endCoord.x - startCoord.x);
              var yDistance = Math.abs(endCoord.y - startCoord.y);

              var scrollAxis = ( xDistance > yDistance ? 'x' : 'y' );

              if( Math.max(xDistance, yDistance) > 30 ) {
                // ok, we pretty much know which way they're going
                // let's lock it in
                primaryScrollAxis = scrollAxis;
              }

              return scrollAxis;
            }

          }
        }

        sideMenuCtrl.setContent({
          element: element[0],
          onDrag: function(e) {},
          endDrag: function(e) {},
          getTranslateX: function() {
            return $scope.sideMenuContentTranslateX || 0;
          },
          setTranslateX: ionic.animationFrameThrottle(function(amount) {
            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px, 0, 0)';
            $timeout(function() {
              $scope.sideMenuContentTranslateX = amount;
            });
          }),
          enableAnimation: function() {
            $scope.animationEnabled = true;
            $element[0].classList.add('menu-animated');
          },
          disableAnimation: function() {
            $scope.animationEnabled = false;
            $element[0].classList.remove('menu-animated');
          }
        });

        // add gesture handlers
        var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element);
        var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element);
        var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element);
        var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element);
        var releaseGesture = $ionicGesture.on('release', onDragRelease, $element);
        var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element);

        // Cleanup
        $scope.$on('$destroy', function() {
          $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);
          $ionicGesture.off(dragRightGesture, 'dragright', onDragX);
          $ionicGesture.off(dragUpGesture, 'dragup', onDragY);
          $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);
          $ionicGesture.off(releaseGesture, 'release', onDragRelease);
          $ionicGesture.off(contentTapGesture, 'tap', onContentTap);
        });
      }
    }
  };
}]);
<commit_msg>style(): missing semi-colon<commit_after>/**
 * @ngdoc directive
 * @name ionSideMenuContent
 * @module ionic
 * @restrict E
 * @parent ionic.directive:ionSideMenus
 *
 * @description
 * A container for the main visible content, sibling to one or more
 * {@link ionic.directive:ionSideMenu} directives.
 *
 * @usage
 * ```html
 * <ion-side-menu-content
 *   edge-drag-threshold="true"
 *   drag-content="true">
 * </ion-side-menu-content>
 * ```
 * For a complete side menu example, see the
 * {@link ionic.directive:ionSideMenus} documentation.
 *
 * @param {boolean=} drag-content Whether the content can be dragged. Default true.
 * @param {boolean|number=} edge-drag-threshold Whether the content drag can only start if it is below a certain threshold distance from the edge of the screen.  Default false. Accepts three types of values:
   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.
   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
 *
 */
IonicModule
.directive('ionSideMenuContent', [
  '$timeout',
  '$ionicGesture',
function($timeout, $ionicGesture) {

  return {
    restrict: 'EA', //DEPRECATED 'A'
    require: '^ionSideMenus',
    scope: true,
    compile: function(element, attr) {
      return { pre: prelink };
      function prelink($scope, $element, $attr, sideMenuCtrl) {
        var startCoord = null;
        var primaryScrollAxis = null;

        $element.addClass('menu-content pane');

        if (isDefined(attr.dragContent)) {
          $scope.$watch(attr.dragContent, function(value) {
            sideMenuCtrl.canDragContent(value);
          });
        } else {
          sideMenuCtrl.canDragContent(true);
        }

        if (isDefined(attr.edgeDragThreshold)) {
          $scope.$watch(attr.edgeDragThreshold, function(value) {
            sideMenuCtrl.edgeDragThreshold(value);
          });
        }

        // Listen for taps on the content to close the menu
        function onContentTap(e) {
          if(sideMenuCtrl.getOpenAmount() !== 0) {
            sideMenuCtrl.close();
            e.gesture.srcEvent.preventDefault();
            startCoord = null;
            primaryScrollAxis = null;
          }
        }

        function onDragX(e) {
          if(!sideMenuCtrl.isDraggableTarget(e)) return;

          if( getPrimaryScrollAxis(e) == 'x') {
            sideMenuCtrl._handleDrag(e);
            e.gesture.srcEvent.preventDefault();
          }
        }

        function onDragY(e) {
          if( getPrimaryScrollAxis(e) == 'x' ) {
            e.gesture.srcEvent.preventDefault();
          }
        }

        function onDragRelease(e) {
          sideMenuCtrl._endDrag(e);
          startCoord = null;
          primaryScrollAxis = null;
        }

        function getPrimaryScrollAxis(gestureEvt) {
          // gets whether the user is primarily scrolling on the X or Y
          // If a majority of the drag has been on the Y since the start of
          // the drag, but the X has moved a little bit, it's still a Y drag

          if(primaryScrollAxis) {
            // we already figured out which way they're scrolling
            return primaryScrollAxis;
          }

          if(gestureEvt && gestureEvt.gesture) {

            if(!startCoord) {
              // get the starting point
              startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);

            } else {
              // we already have a starting point, figure out which direction they're going
              var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);

              var xDistance = Math.abs(endCoord.x - startCoord.x);
              var yDistance = Math.abs(endCoord.y - startCoord.y);

              var scrollAxis = ( xDistance > yDistance ? 'x' : 'y' );

              if( Math.max(xDistance, yDistance) > 30 ) {
                // ok, we pretty much know which way they're going
                // let's lock it in
                primaryScrollAxis = scrollAxis;
              }

              return scrollAxis;
            }

          }
        }

        sideMenuCtrl.setContent({
          element: element[0],
          onDrag: function(e) {},
          endDrag: function(e) {},
          getTranslateX: function() {
            return $scope.sideMenuContentTranslateX || 0;
          },
          setTranslateX: ionic.animationFrameThrottle(function(amount) {
            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px, 0, 0)';
            $timeout(function() {
              $scope.sideMenuContentTranslateX = amount;
            });
          }),
          enableAnimation: function() {
            $scope.animationEnabled = true;
            $element[0].classList.add('menu-animated');
          },
          disableAnimation: function() {
            $scope.animationEnabled = false;
            $element[0].classList.remove('menu-animated');
          }
        });

        // add gesture handlers
        var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element);
        var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element);
        var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element);
        var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element);
        var releaseGesture = $ionicGesture.on('release', onDragRelease, $element);
        var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element);

        // Cleanup
        $scope.$on('$destroy', function() {
          $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);
          $ionicGesture.off(dragRightGesture, 'dragright', onDragX);
          $ionicGesture.off(dragUpGesture, 'dragup', onDragY);
          $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);
          $ionicGesture.off(releaseGesture, 'release', onDragRelease);
          $ionicGesture.off(contentTapGesture, 'tap', onContentTap);
        });
      }
    }
  };
}]);
<|endoftext|>


<commit_before>'use strict';

const PouchDocument = require('./pouch-document.js');
const joi = require('joi');

/**
 * @constructor
 * @class Consortium
 * @description defines a group of users with a common objective.
 * @extends PouchDocument
 * @param {string} description long description of consortium
 * @param {string} label short description of consortium
 * @param {string[]} tags @deprecated
 * @param {string[]} users username array of members
 * @param {string[]} owners those who can kickoff a DecentralizedComputation
 *                          and manage consortium properties
 */
class Consortium extends PouchDocument {

  /**
   * @description Test whether username is a member of consortium (case insensitive)
   * @param  {string} username
   * @returns {boolean}          true if username is member
   */
  hasMember(username) {
    return this.users.some(Consortium.compareUsernames.bind(null, username));
  }

  /**
   * @description Test whether username is an owner of the consortium (case insensitive)
   * @param  {string} username
   * @returns {boolean}          true if username is an owner. false otherwise
   */
  isOwnedBy(username) {
    if (this.owners && this.owners.length) {
      return this.owners.some(Consortium.compareUsernames.bind(null, username));
    }

    return false;
  }

  /**
   * compare two usernames in a case-insensitive way
   * @param  {string} uname1
   * @param  {string} uname2
   * @return {boolean} true if the names match
   */
  static compareUsernames(uname1, uname2) {
    return uname1.toLowerCase().trim() === uname2.toLowerCase().trim();
  }
}

Consortium.schema = Object.assign({}, PouchDocument.schema, {
  _id: joi.string().regex(/^[a-zA-Z0-9]+$/),
  activeComputationId: joi.string().min(1),
  activeRunId: joi.string().min(1),
  description: joi.string().required(),
  label: joi.string().min(1).required(),
  tags: joi.array().default([]),
  users: joi.array().items(joi.string()).required()
    .default([]), // @TODO users => usernames
  owners: joi.array().items(joi.string()).required(),
});

module.exports = Consortium;
<commit_msg>Add `activeComputationInputs` to the `Consortium` model.<commit_after>'use strict';

const PouchDocument = require('./pouch-document.js');
const joi = require('joi');

/**
 * @constructor
 * @class Consortium
 * @description defines a group of users with a common objective.
 * @extends PouchDocument
 * @param {string} description long description of consortium
 * @param {string} label short description of consortium
 * @param {string[]} tags @deprecated
 * @param {string[]} users username array of members
 * @param {string[]} owners those who can kickoff a DecentralizedComputation
 *                          and manage consortium properties
 */
class Consortium extends PouchDocument {

  /**
   * @description Test whether username is a member of consortium (case insensitive)
   * @param  {string} username
   * @returns {boolean}          true if username is member
   */
  hasMember(username) {
    return this.users.some(Consortium.compareUsernames.bind(null, username));
  }

  /**
   * @description Test whether username is an owner of the consortium (case insensitive)
   * @param  {string} username
   * @returns {boolean}          true if username is an owner. false otherwise
   */
  isOwnedBy(username) {
    if (this.owners && this.owners.length) {
      return this.owners.some(Consortium.compareUsernames.bind(null, username));
    }

    return false;
  }

  /**
   * compare two usernames in a case-insensitive way
   * @param  {string} uname1
   * @param  {string} uname2
   * @return {boolean} true if the names match
   */
  static compareUsernames(uname1, uname2) {
    return uname1.toLowerCase().trim() === uname2.toLowerCase().trim();
  }
}

Consortium.schema = Object.assign({}, PouchDocument.schema, {
  _id: joi.string().regex(/^[a-zA-Z0-9]+$/),
  activeComputationId: joi.string().min(1),

  /**
   * @todo A computation's inputs shouldn't be set on the consortium because
   * this limits runs to one-at-a-time. Consider moving elsewhere, perhaps some
   * sort of `ComputationRun` model.
   */
  activeComputationInputs: joi.array().items(
    joi.array().items(
      joi.array().items(joi.string(), joi.number())
    )
  ),
  activeRunId: joi.string().min(1),
  description: joi.string().required(),
  label: joi.string().min(1).required(),
  tags: joi.array().default([]),
  users: joi.array().items(joi.string()).required()
    .default([]), // @TODO users => usernames
  owners: joi.array().items(joi.string()).required(),
});

module.exports = Consortium;
<|endoftext|>