<commit_before>var path = require('path');
var util = require('util');
var _ = require('lodash');
var File = require('./file');

module.exports = Env;

function Env(opt) {
  File.apply(this, arguments);

  this._base = opt.base || '';
  this._writeFilters = [];
  this._writeFiltersMap = {};

  var methodsToPrefix = [ 'mkdir', 'recurse', 'read', 'readJSON', 'write', 'copy',
      'delete' ];

  // Prefix path arguments with this environment root dir
  methodsToPrefix.forEach(function(methodName) {
    this[methodName] = function() {
      var args = _.toArray(arguments);
      args[0] = this.fromBase(args[0]);
      return File.prototype[methodName].apply(this, args);
    };
  }.bind(this));

  var actualWrite = this.write;
  this.write = function(filepath, contents, options) {
    this.applyWriteFilters({ path: filepath, contents: contents }, actualWrite, options);
  };
}

util.inherits(Env, File);

// Return a path prefixed by the base (if not absolute)
Env.prototype.fromBase = function( filepath ) {
  if (this.isPathAbsolute(filepath)) {
    return filepath;
  }
  return path.join(this._base, filepath);
};

Env.prototype.registerWriteFilter = function(name, filter) {
  this._writeFiltersMap[ name ] = this._writeFilters.length;
  this._writeFilters.push(filter);
};

Env.prototype.removeWriteFilter = function(name) {
  this._writeFilters.splice(this._writeFiltersMap[name], 1);
  delete this._writeFiltersMap[name];
};

Env.prototype.applyWriteFilters = function(file, actualWrite, options) {
  if (!this._writeFilters.length) {
    return actualWrite.call(this, file.path, file.contents, options);
  }

  var i = 0;
  var output;
  var recurse = function(file) {
    i++;
    if (this._writeFilters[i]) {
      runAsync( this._writeFilters[i], recurse, file );
    } else {
      output = actualWrite.call(this, file.path, file.contents, options);
    }
  }.bind(this);

  runAsync( this._writeFilters[i], recurse, file );

  return output;
};

// ---
// util.inherits(
function runAsync( func, cb ) {
  var rest = [];
  var len = 1;

  while ( len++ < arguments.length ) {
    rest.push( arguments[len] );
  }

  var async = false;
  var returnValue = func.apply({
    async: function() {
      async = true;
      return _.once(cb);
    }
  }, rest );

  // Note: Call the callback synchronously to keep the sync flow by default
  if ( !async ) {
    cb(returnValue);
  }
}
<commit_msg>Fix bug with the logic behind registering/removing write filters<commit_after>var path = require('path');
var util = require('util');
var _ = require('lodash');
var File = require('./file');

module.exports = Env;

function Env(opt) {
  File.apply(this, arguments);

  this._base = opt.base || '';
  this._writeFilters = {};

  var methodsToPrefix = [ 'mkdir', 'recurse', 'read', 'readJSON', 'write', 'copy',
      'delete' ];

  // Prefix path arguments with this environment root dir
  methodsToPrefix.forEach(function(methodName) {
    this[methodName] = function() {
      var args = _.toArray(arguments);
      args[0] = this.fromBase(args[0]);
      return File.prototype[methodName].apply(this, args);
    };
  }.bind(this));

  var actualWrite = this.write;
  this.write = function(filepath, contents, options) {
    this.applyWriteFilters({ path: filepath, contents: contents }, actualWrite, options);
  };
}

util.inherits(Env, File);

// Return a path prefixed by the base (if not absolute)
Env.prototype.fromBase = function( filepath ) {
  if (this.isPathAbsolute(filepath)) {
    return filepath;
  }
  return path.join(this._base, filepath);
};

Env.prototype.registerWriteFilter = function(name, filter) {
  this._writeFilters[name] = filter;
};

Env.prototype.removeWriteFilter = function(name) {
  delete this._writeFilters[name];
};

Env.prototype.applyWriteFilters = function(file, actualWrite, options) {
  var writeFilters = _.reduce(this._writeFilters, function(m, v) { m.push(v); return m; }, []);
  if (!writeFilters.length) {
    return actualWrite.call(this, file.path, file.contents, options);
  }

  var i = 0;
  var output;
  var recurse = function(file) {
    i++;
    if (writeFilters[i]) {
      runAsync( writeFilters[i], recurse, file );
    } else {
      output = actualWrite.call(this, file.path, file.contents, options);
    }
  }.bind(this);

  runAsync( writeFilters[i], recurse, file );

  return output;
};

// ---
// util.inherits(
function runAsync( func, cb ) {
  var rest = [];
  var len = 1;

  while ( len++ < arguments.length ) {
    rest.push( arguments[len] );
  }

  var async = false;
  var returnValue = func.apply({
    async: function() {
      async = true;
      return _.once(cb);
    }
  }, rest );

  // Note: Call the callback synchronously to keep the sync flow by default
  if ( !async ) {
    cb(returnValue);
  }
}
<|endoftext|>


<commit_before>document.body.style.backgroundColor = 'black'
var w = c.width = window.innerWidth,
    h = c.height = window.innerHeight,
    ctx = c.getContext('2d')

var points = [
    [107,125,200,234,250,260,274,279,278,292,301,304,298,298,309,312,312,306,313,326,337,347,354,358,362,375,382,392,387,388,394,409,412,425,442,440,463,470,488,495,509,520,532,538,536,536,547,558,578,598,601,611,623,629,619,610,605,601,595,598,580,578,578,575,565,543,538,527,510,510,514,506,490,478,472,446,427,420,392,387,383,377,368,363,348,337,332,320,310,301,285,272,279,273,264,255,251,248,250,252,247,245,246,253,254,256,265,271,283,293,289,293,309,309,304,290,277,259,246,239,239,244,239,237,231,225,217,216,211,203,193,177,163,152,143,136,125,114,107],
    [284,307,330,350,348,352,351,359,370,372,381,402,415,421,414,424,424,436,446,428,410,384,383,378,384,380,366,369,379,386,384,372,361,352,358,352,354,339,339,341,345,357,366,366,354,345,346,356,351,354,352,357,357,350,339,339,343,352,351,344,328,311,297,291,295,300,295,299,294,269,262,266,264,271,275,273,276,274,292,286,286,292,297,290,294,296,294,274,257,251,249,249,241,242,248,255,266,266,252,238,235,228,226,230,236,238,229,216,206,201,197,196,195,190,186,183,187,194,208,212,219,226,217,214,221,223,229,234,239,238,248,256,258,256,260,269,275,278,284],
    [565,563,551,548,542,542,554,557,548,540,536,531,525,524,530,528,537,505,513,510,514,507,482,472,455,438,426,417,412,402,394,388,384,384,372,338,316,308,289,284,269,257,241,216,230,226,210,196,187,189,173,147,112, 88, 68, 48, 20,  2,  3,  7, 18, 35, 55, 73, 83, 82, 86, 87, 83, 90, 91, 89, 80, 79, 93, 94, 85, 78, 71, 68, 74, 83, 93,108],
    [295,291,294,298,291,284,275,254,247,246,250,241,241,238,228,224,204,175,151,149,133,136,134,138,136,127,111, 90, 62, 46, 43, 48, 46, 38, 45, 42, 34, 48, 43, 45, 62, 67, 84, 89, 68, 64, 70, 80,100,111,124,143,156,166,181,201,230,258,274,280,279,264,251,243,236,240,237,239,245,243,246,251,261,263,251,255,263,263,266,275,281,276,284,284],
    [319,336,357,379,386,408,398,379],
    [239,251,259,252,265,250,241,252],
    [483,450,438,422,425,392,377,422],
    [219,211,194,177,155,141,161,177],
    [140,120,151,151,181],
    [233,204,191,165,149],
    [314,282,268,282,266,229,266,288,289,288,319,315,325,332,345,353,364],
    [107,129,178,129,126,152,126, 73, 55, 73, 83,107,152,152,143,138,122]
]

var starsX = [123,135,243,286,326,573,264,532,267,120,153,273,314,282,268,282,266,229,266,288,289,288,319,315,325,332,345,353,364,140,120,151,151,181,483,450,438,422,425,392,377,422,319,336,357,379,386,408,398,379]
var starsY = [279,292,226,365,289,297,314,303,204,296,260,127,107,129,178,129,126,152,126, 73, 55, 73, 83,107,152,152,143,138,122,233,204,191,165,149,219,211,194,177,155,141,161,177,239,251,259,252,265,250,241,252]

var pi = Math.PI

ctx.beginPath();
for (var i = 0; i < 2*pi; i+=pi/2) {
    ctx.arc(335,350,330,0 + i, pi/4 + i)
    ctx.arc(335,350,330,pi + pi/4 + i, pi + pi/4*2 + i)
}
ctx.lineWidth=2;
ctx.strokeStyle = '#1b1b1b'
ctx.stroke();

ctx.beginPath()
for (var i = .80; i > 0; i-=0.2) {
    ctx.arc(335,350,330*i,0,2*pi)
}
ctx.lineWidth=2;
ctx.strokeStyle = '#1b1b1b'
ctx.stroke();

for (var i = 0; i < points.length; i+=2) {
    ctx.beginPath();
    ctx.strokeStyle = (i < 3 ? '#666666' : 'navy')
    ctx.moveTo(points[0]+10, points[0]+110)
    for (var j = 0; j < points[i].length; j++) {
        ctx.lineTo(points[i][j] + 10, points[i + 1][j] + 110)
    }
    ctx.lineWidth=2;
    ctx.lineJoin='round'
    ctx.stroke();
}

for (var i = 0; i < starsX.length; i++) {
    ctx.beginPath()
    ctx.arc(starsX[i] + 10,starsY[i] + 110,2,0,2*pi)
    ctx.strokeStyle = 'maroon'
    ctx.fillStyle = 'maroon'
    ctx.fill()
    ctx.stroke();
}
<commit_msg>shifted dipper 10<commit_after>document.body.style.backgroundColor = 'black'
var w = c.width = window.innerWidth,
    h = c.height = window.innerHeight,
    ctx = c.getContext('2d')

var points = [
    [565,563,551,548,542,542,554,557,548,540,536,531,525,524,530,528,537,505,513,510,514,507,482,472,455,438,426,417,412,402,394,388,384,384,372,338,316,308,289,284,269,257,241,216,230,226,210,196,187,189,173,147,112, 88, 68, 48, 20,  2,  3,  7, 18, 35, 55, 73, 83, 82, 86, 87, 83, 90, 91, 89, 80, 79, 93, 94, 85, 78, 71, 68, 74, 83, 93,108],
    [295,291,294,298,291,284,275,254,247,246,250,241,241,238,228,224,204,175,151,149,133,136,134,138,136,127,111, 90, 62, 46, 43, 48, 46, 38, 45, 42, 34, 48, 43, 45, 62, 67, 84, 89, 68, 64, 70, 80,100,111,124,143,156,166,181,201,230,258,274,280,279,264,251,243,236,240,237,239,245,243,246,251,261,263,251,255,263,263,266,275,281,276,284,284],
    [107,125,200,234,250,260,274,279,278,292,301,304,298,298,309,312,312,306,313,326,337,347,354,358,362,375,382,392,387,388,394,409,412,425,442,440,463,470,488,495,509,520,532,538,536,536,547,558,578,598,601,611,623,629,619,610,605,601,595,598,580,578,578,575,565,543,538,527,510,510,514,506,490,478,472,446,427,420,392,387,383,377,368,363,348,337,332,320,310,301,285,272,279,273,264,255,251,248,250,252,247,245,246,253,254,256,265,271,283,293,289,293,309,309,304,290,277,259,246,239,239,244,239,237,231,225,217,216,211,203,193,177,163,152,143,136,125,114,107],
    [284,307,330,350,348,352,351,359,370,372,381,402,415,421,414,424,424,436,446,428,410,384,383,378,384,380,366,369,379,386,384,372,361,352,358,352,354,339,339,341,345,357,366,366,354,345,346,356,351,354,352,357,357,350,339,339,343,352,351,344,328,311,297,291,295,300,295,299,294,269,262,266,264,271,275,273,276,274,292,286,286,292,297,290,294,296,294,274,257,251,249,249,241,242,248,255,266,266,252,238,235,228,226,230,236,238,229,216,206,201,197,196,195,190,186,183,187,194,208,212,219,226,217,214,221,223,229,234,239,238,248,256,258,256,260,269,275,278,284],
    [325,342,363,385,392,414,404,385],
    [239,251,259,252,265,250,241,252],
    [489,456,444,428,431,398,383,428],
    [219,211,194,177,155,141,161,177],
    [140,120,151,151,181],
    [233,204,191,165,149],
    [314,282,268,282,266,229,266,288,289,288,319,315,325,332,345,353,364],
    [107,129,178,129,126,152,126, 73, 55, 73, 83,107,152,152,143,138,122]
]

var starsX = [123,135,243,286,326,573,264,532,267,120,153,273,314,282,268,282,266,229,266,288,289,288,319,315,325,332,345,353,364,140,120,151,151,181,489,456,444,428,431,398,383,428,325,342,363,385,392,414,404,385]
var starsY = [279,292,226,365,289,297,314,303,204,296,260,127,107,129,178,129,126,152,126, 73, 55, 73, 83,107,152,152,143,138,122,233,204,191,165,149,219,211,194,177,155,141,161,177,239,251,259,252,265,250,241,252]

var pi = Math.PI

ctx.beginPath();
for (var i = 0; i < 2*pi; i+=pi/2) {
    ctx.arc(335,350,330,0 + i, pi/4 + i)
    ctx.arc(335,350,330,pi + pi/4 + i, pi + pi/4*2 + i)
}
ctx.lineWidth=2;
ctx.strokeStyle = '#1b1b1b'
ctx.stroke();

// ctx.beginPath()
// for (var i = 1; i > 0; i-=0.2) {
//     ctx.arc(335,350,330*i,0,2*pi)
// }
// ctx.lineWidth=2;
// ctx.strokeStyle = '#1b1b1b'
// ctx.stroke();

for (var i = 0; i < points.length; i+=2) {
    ctx.beginPath();
    ctx.strokeStyle = (i < 3 ? '#666666' : 'navy')
    ctx.moveTo(points[0]+10, points[0]+110)
    for (var j = 0; j < points[i].length; j++) {
        ctx.lineTo(points[i][j] + 10, points[i + 1][j] + 110)
    }
    ctx.lineWidth=2;
    ctx.lineJoin='round'
    // ctx.fill()
    ctx.stroke();
}

for (var i = 0; i < starsX.length; i++) {
    ctx.beginPath()
    ctx.arc(starsX[i] + 10,starsY[i] + 110,2,0,2*pi)
    ctx.strokeStyle = 'maroon'
    ctx.fillStyle = 'maroon'
    ctx.fill()
    ctx.stroke();
}
<|endoftext|>


<commit_before>// "constants"
var accel = 2000;
var runAccel = 3000;
var gravity = 2000;
var bouncyGravity = 1000;
var bouncyThrowMultiplier = 1.5;
var fast = 100;
var maxSpeed = 5 * fast;
var runSpeed = 7 * fast;
var jumpSpeed = 6.5 * fast;
var maxYVelocity = 20 * fast;

var stillDelta = 1; // 1 is pretty slow

var game = new Phaser.Game(1280, 600, Phaser.AUTO, '');

var levels = 0; // count levels
game.state.add('MainMenu', {
  preload: menuPreload,
  create: menuCreate,
  update: menuUpdate
});

game.state.add('Game', {
  preload: preload,
  create: create,
  update: update,
  render: render
});

var curState = 'MainMenu';
game.state.start('MainMenu');

function preload() {
  game.load.image('bg0', 'assets/Background/bg_layer1.png');
  game.load.image('bg1', 'assets/Background/bg_layer4.png');

  game.load.image('lava', 'assets/Obstacles/spikes_a.png');
  game.load.image('checkpoint', 'assets/Tiles/tile_214.png');
  game.load.image('bouncy', 'assets/Tiles/tile_03.png');
  game.load.image('gravity', 'assets/Tiles/tile_341.png');

  game.load.image('ground1_tb', 'assets/Tiles/tile_111.png');
  game.load.image('ground1_trb', 'assets/Tiles/tile_114.png');
  game.load.image('ground1_lrb', 'assets/Tiles/tile_115.png');
  game.load.image('ground1_lt', 'assets/Tiles/tile_116.png');
  game.load.image('ground1_tr', 'assets/Tiles/tile_117.png');
  game.load.image('ground1_lr', 'assets/Tiles/tile_138.png');
  game.load.image('ground1_ltr', 'assets/Tiles/tile_141.png');
  game.load.image('ground1_ltb', 'assets/Tiles/tile_142.png');
  game.load.image('ground1_lb', 'assets/Tiles/tile_143.png');
  game.load.image('ground1_rb', 'assets/Tiles/tile_144.png');
  game.load.image('ground1_l', 'assets/Tiles/tile_167.png');
  game.load.image('ground1_r', 'assets/Tiles/tile_168.png');
  game.load.image('ground1_', 'assets/Tiles/tile_169.png');
  game.load.image('ground1_t', 'assets/Tiles/tile_194.png');
  game.load.image('ground1_b', 'assets/Tiles/tile_195.png');
  game.load.image('ground1_ltrb', 'assets/Tiles/tile_196.png');

  game.load.spritesheet('player', 'assets/Players/bunny1.png', 150, 200);
  createLevel(1);
  createLevel(2);
  game.load.image('tiles', 'assets/Tiles/tilemap.png');
}

function createLevel(id) {
  game.load.tilemap('level' + id, 'levels/level' + id + '.json', null, Phaser.Tilemap.TILED_JSON);
  levels++;
}

var playerSpawn = {
  x: 0,
  y: 0
};

var levelId = 1;

var timer;

function create() {
  game.world.setBounds(0, 0, 1920, 1920);

  //  We're going to be using physics, so enable the Arcade Physics system
  game.physics.startSystem(Phaser.Physics.ARCADE);

  // increase this if you get tunneling
  game.physics.arcade.TILE_BIAS = 80;

  loadLevel(levelId);

  //jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
  //jumpButton.onDown.add(jump, this);

  //runButton = game.input.keyboard.addKey(Phaser.Keyboard.Z);

  //cursors = game.input.keyboard.createCursorKeys();

  cursors.up.onDown.add(jump, this);

  cursors.left.onDown.add(onLeft, this);
  cursors.right.onDown.add(onRight, this);

  spawnPlayer();

  startTimer();
}

function reset() {
    player.kill();
    spawnPlayer();
}

function touchlava() {
    reset();
}

function passCheckpoint(player, checkpoint) {
    playerSpawn = {
        x: checkpoint.body.position.x,
        y: checkpoint.body.position.y - 64
    }
    return false;
}

var grabbable = [];

function touchGrabbable(player, grabbable) {
  var input = processInput();
  if (input.run) {
    grab(grabbable);
  }
}

var gravityTimer;

function touchGravity(player, gravityBox) {
    if (!gravityTimer) {
        if (player.body.gravity.y == gravity) {
            player.body.gravity.y = gravity / 2;
        } else {
            player.body.gravity.y = gravity;
        }
        gravityTimer = game.time.create(false);
        gravityTimer.add(1000, killtimer, this);
        gravityTimer.start();
    }
}

function killtimer() {
    gravityTimer = null;
}

function retardateGrabbables() {
  /*
    for (var i = 0; i < grabbables.children.length; ++i) {
        var speed = grabbables.children[i].body.velocity.x
        grabbables.children[i].body.acceleration.x = -(speed && speed / Math.abs(speed)) * 500;
    }
    */
}

var sanicTimer;

var oldMax = maxSpeed;
var oldRun = runSpeed;

function goFast(player, sanic) {
  if (!sanicTimer) {
    maxSpeed = 1000 * fast;
    runSpeed = 1000 * fast;
  }
  sanicTimer = game.time.create(false);
  sanicTimer.add(3000, goSlow, this);
  sanicTimer.start();
}

function goSlow() {
  sanicTimer = null;
  maxSpeed = oldMax;
  runSpeed = oldRun;
}

function update() {
  game.physics.arcade.collide(player, groundLayer);
  //game.physics.arcade.collide(player, platforms);

  game.physics.arcade.collide(player, lavaGroup, touchlava, null, this);
  //game.physics.arcade.collide(player, grabbables, touchGrabbable, null, this);
  //game.physics.arcade.collide(grabbables, platforms);
  //game.physics.arcade.collide(grabbables, gravities);
  game.physics.arcade.collide(player, gvGroup, touchGravity, null, this);
  //game.physics.arcade.overlap(player, checkpoints, passCheckpoint, null, this);
  game.physics.arcade.overlap(player, cpGroup, null, passCheckpoint, this);
  //game.physics.arcade.collide(player, sanics, goFast, null, this);

  // run player input & movement code
  playerMovement();

  // player animations
  updateAnimations();

  // Retardate grabbables
  retardateGrabbables();
}

function render() {
  //game.debug.cameraInfo(game.camera, 32, 32);
  //game.debug.spriteCoords(player, 32, 500);
  //renderTimer();
  //game.debug.bodyInfo(player, 32, 40);
  //game.debug.body(player);
  //game.debug.bodyInfo(player, 32, 32);
  //game.debug.body(player);
  //game.debug.body(groundLayer);
}
<commit_msg>up resolution for fullhd goodness<commit_after>// "constants"
var accel = 2000;
var runAccel = 3000;
var gravity = 2000;
var bouncyGravity = 1000;
var bouncyThrowMultiplier = 1.5;
var fast = 100;
var maxSpeed = 5 * fast;
var runSpeed = 7 * fast;
var jumpSpeed = 6.5 * fast;
var maxYVelocity = 20 * fast;

var stillDelta = 1; // 1 is pretty slow

var game = new Phaser.Game(1920, 1080, Phaser.AUTO, '');

var levels = 0; // count levels
game.state.add('MainMenu', {
  preload: menuPreload,
  create: menuCreate,
  update: menuUpdate
});

game.state.add('Game', {
  preload: preload,
  create: create,
  update: update,
  render: render
});

var curState = 'MainMenu';
game.state.start('MainMenu');

function preload() {
  game.load.image('bg0', 'assets/Background/bg_layer1.png');
  game.load.image('bg1', 'assets/Background/bg_layer4.png');

  game.load.image('lava', 'assets/Obstacles/spikes_a.png');
  game.load.image('checkpoint', 'assets/Tiles/tile_214.png');
  game.load.image('bouncy', 'assets/Tiles/tile_03.png');
  game.load.image('gravity', 'assets/Tiles/tile_341.png');

  game.load.image('ground1_tb', 'assets/Tiles/tile_111.png');
  game.load.image('ground1_trb', 'assets/Tiles/tile_114.png');
  game.load.image('ground1_lrb', 'assets/Tiles/tile_115.png');
  game.load.image('ground1_lt', 'assets/Tiles/tile_116.png');
  game.load.image('ground1_tr', 'assets/Tiles/tile_117.png');
  game.load.image('ground1_lr', 'assets/Tiles/tile_138.png');
  game.load.image('ground1_ltr', 'assets/Tiles/tile_141.png');
  game.load.image('ground1_ltb', 'assets/Tiles/tile_142.png');
  game.load.image('ground1_lb', 'assets/Tiles/tile_143.png');
  game.load.image('ground1_rb', 'assets/Tiles/tile_144.png');
  game.load.image('ground1_l', 'assets/Tiles/tile_167.png');
  game.load.image('ground1_r', 'assets/Tiles/tile_168.png');
  game.load.image('ground1_', 'assets/Tiles/tile_169.png');
  game.load.image('ground1_t', 'assets/Tiles/tile_194.png');
  game.load.image('ground1_b', 'assets/Tiles/tile_195.png');
  game.load.image('ground1_ltrb', 'assets/Tiles/tile_196.png');

  game.load.spritesheet('player', 'assets/Players/bunny1.png', 150, 200);
  createLevel(1);
  createLevel(2);
  game.load.image('tiles', 'assets/Tiles/tilemap.png');
}

function createLevel(id) {
  game.load.tilemap('level' + id, 'levels/level' + id + '.json', null, Phaser.Tilemap.TILED_JSON);
  levels++;
}

var playerSpawn = {
  x: 0,
  y: 0
};

var levelId = 1;

var timer;

function create() {
  game.world.setBounds(0, 0, 1920, 1920);

  //  We're going to be using physics, so enable the Arcade Physics system
  game.physics.startSystem(Phaser.Physics.ARCADE);

  // increase this if you get tunneling
  game.physics.arcade.TILE_BIAS = 80;

  loadLevel(levelId);

  //jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
  //jumpButton.onDown.add(jump, this);

  //runButton = game.input.keyboard.addKey(Phaser.Keyboard.Z);

  //cursors = game.input.keyboard.createCursorKeys();

  cursors.up.onDown.add(jump, this);

  cursors.left.onDown.add(onLeft, this);
  cursors.right.onDown.add(onRight, this);

  spawnPlayer();

  startTimer();
}

function reset() {
    player.kill();
    spawnPlayer();
}

function touchlava() {
    reset();
}

function passCheckpoint(player, checkpoint) {
    playerSpawn = {
        x: checkpoint.body.position.x,
        y: checkpoint.body.position.y - 64
    }
    return false;
}

var grabbable = [];

function touchGrabbable(player, grabbable) {
  var input = processInput();
  if (input.run) {
    grab(grabbable);
  }
}

var gravityTimer;

function touchGravity(player, gravityBox) {
    if (!gravityTimer) {
        if (player.body.gravity.y == gravity) {
            player.body.gravity.y = gravity / 2;
        } else {
            player.body.gravity.y = gravity;
        }
        gravityTimer = game.time.create(false);
        gravityTimer.add(1000, killtimer, this);
        gravityTimer.start();
    }
}

function killtimer() {
    gravityTimer = null;
}

function retardateGrabbables() {
  /*
    for (var i = 0; i < grabbables.children.length; ++i) {
        var speed = grabbables.children[i].body.velocity.x
        grabbables.children[i].body.acceleration.x = -(speed && speed / Math.abs(speed)) * 500;
    }
    */
}

var sanicTimer;

var oldMax = maxSpeed;
var oldRun = runSpeed;

function goFast(player, sanic) {
  if (!sanicTimer) {
    maxSpeed = 1000 * fast;
    runSpeed = 1000 * fast;
  }
  sanicTimer = game.time.create(false);
  sanicTimer.add(3000, goSlow, this);
  sanicTimer.start();
}

function goSlow() {
  sanicTimer = null;
  maxSpeed = oldMax;
  runSpeed = oldRun;
}

function update() {
  game.physics.arcade.collide(player, groundLayer);
  //game.physics.arcade.collide(player, platforms);

  game.physics.arcade.collide(player, lavaGroup, touchlava, null, this);
  //game.physics.arcade.collide(player, grabbables, touchGrabbable, null, this);
  //game.physics.arcade.collide(grabbables, platforms);
  //game.physics.arcade.collide(grabbables, gravities);
  game.physics.arcade.collide(player, gvGroup, touchGravity, null, this);
  //game.physics.arcade.overlap(player, checkpoints, passCheckpoint, null, this);
  game.physics.arcade.overlap(player, cpGroup, null, passCheckpoint, this);
  //game.physics.arcade.collide(player, sanics, goFast, null, this);

  // run player input & movement code
  playerMovement();

  // player animations
  updateAnimations();

  // Retardate grabbables
  retardateGrabbables();
}

function render() {
  //game.debug.cameraInfo(game.camera, 32, 32);
  //game.debug.spriteCoords(player, 32, 500);
  //renderTimer();
  //game.debug.bodyInfo(player, 32, 40);
  //game.debug.body(player);
  //game.debug.bodyInfo(player, 32, 32);
  //game.debug.body(player);
  //game.debug.body(groundLayer);
}
<|endoftext|>


<commit_before>---
layout: null
---
$(document).ready(function () {
  alert("what's up")
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

/*  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
  alert('window.location.pathname');*/

/*  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}/index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
*/
    if (window.location.pathname !== 'wrong.com' && window.location.pathname !== 'wrongagain.com') {
      $('.panel-cover').addClass('panel-cover--collapsed')
    }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<commit_msg>change main.js back to working, with alert<commit_after>---
layout: null
---
$(document).ready(function () {

  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

/*  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }*/
  alert('window.location.pathname');

  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}/index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<|endoftext|>


<commit_before>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "http://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
      },
      function(err){},
      options);
    }
	//return pos;
	var location = pos.lat + " " + pos.lng;
	alert(location);
}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<commit_msg>Update main.js<commit_after>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "http://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
		alert(location);
      },
      function(err){},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<|endoftext|>


<commit_before>$(function() {
	testModel = new Models.ItemListing({
		id: 0,
		name: "Test Item",
		price: "(USD) $5",
		location: "Singapore",
		buyers: [0],
		owner: 0,
		imageUrl: 'http://placehold.it/96x96'
	});

	yourCollection = new Models.ItemListings();
	friendCollection = new Models.ItemListings();
	featuredCollection = new Models.ItemListings();
	publicCollection = new Models.ItemListings();

	yourView = new Views.ListingView({
		collection: yourCollection,
		el: $('#you-listing')[0]
	});

	friendView = new Views.ListingView({
		collection: friendCollection,
		el: $('#friend-listing')[0]
	});

	featuredView = new Views.ListingView({
		collection: featuredCollection,
		el: $('#featured-listing')[0]
	});

	publicView = new Views.ListingView({
		collection: publicCollection,
		el: $('#public-listing')[0]
	})

	yourCollection.add(testModel);
});
<commit_msg>Add another dummy model.<commit_after>$(function() {
	yourCollection = new Models.ItemListings();
	friendCollection = new Models.ItemListings();
	featuredCollection = new Models.ItemListings();
	publicCollection = new Models.ItemListings();

	yourView = new Views.ListingView({
		collection: yourCollection,
		el: $('#you-listing')[0]
	});

	friendView = new Views.ListingView({
		collection: friendCollection,
		el: $('#friend-listing')[0]
	});

	featuredView = new Views.ListingView({
		collection: featuredCollection,
		el: $('#featured-listing')[0]
	});

	publicView = new Views.ListingView({
		collection: publicCollection,
		el: $('#public-listing')[0]
	})

	yourCollection.add({
		id: 0,
		name: "Test Item",
		price: "(USD) $5",
		location: "Singapore",
		buyers: [0],
		owner: 0,
		imageUrl: 'http://placehold.it/96x96'
	});
	friendCollection.add({
		id: 1,
		name: "Another Item",
		price: "(USD) $25",
		location: "Singapore",
		buyers: [0, 1, 2],
		owner:  1,
		imageUrl: 'http://placehold.it/96x96'
	});
});
<|endoftext|>


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

    let depth = Number.parseInt(
      globalThis.location.search.substring(1),
      10
    );

    if(globalThis.isNaN(depth)
      || depth < 0){
        depth = 0;
    }

    const display = [];

    Object.getOwnPropertyNames(globalThis).forEach(
      function(property){
          display.push(
            '
'
            + property
            + '<textarea readonly>'
            + globalThis[property]
            + '</textarea>'
          );
          fetchInfo(
            globalThis[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object === globalThis){
            return;
        }

        for(const property in object){
            if(object.hasOwnProperty(property)){
                display.push(
                  '
'
                  + name
                  + '.'
                  + property
                  + '<textarea readonly>'
                  + object[property]
                  + '</textarea>'
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('depth').value = 'Depth: ' + depth;
    document.getElementById('depth').onclick = function(){
        const newdepth = globalThis.prompt(
          'Enter new depth:',
          depth
        );

        if(newdepth === null
          || newdepth.length === 0
          || isNaN(newdepth)){
            return;
        }

        globalThis.location.replace('?' + newdepth);
    };
    document.getElementById('result').innerHTML = display.sort().join('');
}());
<commit_msg>improved formatting<commit_after>(function(){
    'use strict';

    let depth = Number.parseInt(
      globalThis.location.search.substring(1),
      10
    );

    if(globalThis.isNaN(depth)
      || depth < 0){
        depth = 0;
    }

    const display = [];

    Object.getOwnPropertyNames(globalThis).forEach(
      function(property){
          display.push(
            '
' + property
              + '<textarea readonly>' + globalThis[property] + '</textarea>'
          );
          fetchInfo(
            globalThis[property],
            property,
            0
          );
      }
    );

    function fetchInfo(object, name, depthcounter){
        if(depthcounter >= depth
          || object === globalThis){
            return;
        }

        for(const property in object){
            if(object.hasOwnProperty(property)){
                display.push(
                  '
' + name + '.' + property
                    + '<textarea readonly>' + object[property] + '</textarea>'
                );
                fetchInfo(
                  object[property],
                  name + '.' + property,
                  depthcounter + 1
                );
            }
        }
    }

    document.getElementById('depth').value = 'Depth: ' + depth;
    document.getElementById('depth').onclick = function(){
        const newdepth = globalThis.prompt(
          'Enter new depth:',
          depth
        );

        if(newdepth === null
          || newdepth.length === 0
          || isNaN(newdepth)){
            return;
        }

        globalThis.location.replace('?' + newdepth);
    };
    document.getElementById('result').innerHTML = display.sort().join('');
}());
<|endoftext|>


<commit_before>jQuery.fn.updateWithText = function(text, speed)
{
	var dummy = $('
').html(text);

	if ($(this).html() != dummy.html())
	{
		$(this).fadeOut(speed/2, function() {
			$(this).html(text);
			$(this).fadeIn(speed/2, function() {
				//done
			});
		});
	}
}

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("
").append(this.eq(0).clone()).html();
};

function roundVal(temp)
{
	return Math.round(temp * 10) / 10;
}

function kmh2beaufort(kmh)
{
	var speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
	for (var beaufort in speeds) {
		var speed = speeds[beaufort];
		if (speed > kmh) {
			return beaufort;
		}
	}
	return 12;
}

jQuery(document).ready(function($) {

	var news = [];
	var newsIndex = 0;

	var eventList = [];

	var lastCompliment;
	var compliment;

    // multi-langugage support according to browser-lang
    var lang = window.navigator.language;
    switch (lang)
    {
        case 'de':
            var days = ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'];
            var months = ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
            var dayAbbr = ['So','Mo','Di','Mi','Do','Fr','Sa'];
            var today = 'heute';
            var tomorrow = 'morgen';
            var in_days = 'Tage';
            break;
        case 'nl':
            var days = ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'];
            var months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
            var dayAbbr = ['zo','ma','di','wo','do','vr','za'];
            var today = 'vandaag';
            var tomorrow = 'morgen';
            var in_days = 'dagen';
            break;
       case 'fr':
            var days = ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'];
            var months = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
            var dayAbbr = ['dim','lun','mar','mer','jeu','ven','sam'];
            var today = 'aujourd\'hui';
            var tomorrow = 'demain';
            var in_days = 'jour(s)';
            break;
        default:
            var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
            var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
            var dayAbbr = ['Sun','Mon','Tues','Wed','Thru','Fri','Sat'];
            var today = 'Today';
            var tomorrow = 'Tomorrow';
            var in_days = 'days';
    }

	//connect do Xbee monitor
	var socket = io.connect('http://rpi-development.local:8080');
	socket.on('dishwasher', function (dishwasherReady) {
		if (dishwasherReady) {
			$('.dishwasher').fadeIn(2000);
			$('.lower-third').fadeOut(2000);
		} else {
			$('.dishwasher').fadeOut(2000);
			$('.lower-third').fadeIn(2000);
		}
	});

	var weatherParams = {
		'q':'Baarn,Netherlands',
		'units':'metric',
		'lang':lang
	};

	(function checkVersion()
	{
		$.getJSON('githash.php', {}, function(json, textStatus) {
			if (json) {
				if (json.gitHash != gitHash) {
					window.location.reload();
					window.location.href=window.location.href;
				}
			}
		});
		setTimeout(function() {
			checkVersion();
		}, 3000);
	})();

	(function updateTime()
	{
		var now = new Date();

		var day = now.getDay();
		var date = now.getDate();
		var month = now.getMonth();
		var year = now.getFullYear();

		var date = days[day] + ', ' + date+' ' + months[month] + ' ' + year;

		$('.date').html(date);
		$('.time').html(now.toTimeString().substring(0,5) + ''+now.toTimeString().substring(6,8)+'');

		setTimeout(function() {
			updateTime();
		}, 1000);
	})();

	(function updateCalendarData()
	{
		new ical_parser("calendar.php", function(cal){
        	events = cal.getEvents();
        	eventList = [];

        	for (var i in events) {
        		var e = events[i];
        		for (var key in e) {
        			var value = e[key];
					var seperator = key.search(';');
					if (seperator >= 0) {
						var mainKey = key.substring(0,seperator);
						var subKey = key.substring(seperator+1);

						var dt;
						if (subKey == 'VALUE=DATE') {
							//date
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8));
						} else {
							//time
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8), value.substring(9,11), value.substring(11,13), value.substring(13,15));
						}

						if (mainKey == 'DTSTART') e.startDate = dt;
						if (mainKey == 'DTEND') e.endDate = dt;
					}
        		}

        		var now = new Date();
        		var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        		var days = moment(e.startDate).diff(moment(today), 'days');

        		//only add fututre events
        		if (days >= 0) {
	        		eventList.push({'description':e.SUMMARY,'days':days});
        		}
        	};
        	eventList.sort(function(a,b){return a.days-b.days});

        	setTimeout(function() {
        		updateCalendarData();
        	}, 60000);
    	});
	})();

	(function updateCalendar()
	{
		table = $('
').addClass('xsmall').addClass('calendar-table');
		opacity = 1;

		for (var i in eventList) {
			var e = eventList[i];
			var days = e.days;

			var daysString = (days == 1) ? tomorrow :  days + ' ' + in_days;
    		if (days == 0) {
    			daysString = today;
    		}

			var row = $('
').css('opacity',opacity);
			row.append($('').html(e.description).addClass('description'));
			row.append($('').html(daysString).addClass('days dimmed'));
			table.append(row);

			opacity -= 1 / eventList.length;
		}

		$('.calendar').updateWithText(table,1000);

		setTimeout(function() {
        	updateCalendar();
        }, 1000);
	})();

	(function updateCompliment()
	{

		var compliments = [
			'Hey, handsome!',
			'Hi, sexy!',
			'Hello, beauty!',
			'You look sexy!',
			'Wow, you look hot!',
			'Looking good today!',
			'You look nice!',
			'Enjoy your day!'
		];

		while (compliment == lastCompliment) {
			compliment = Math.floor(Math.random()*compliments.length);
		}

		$('.compliment').updateWithText(compliments[compliment], 4000);

		lastCompliment = compliment;

		setTimeout(function() {
			updateCompliment(true);
		}, 30000);

	})();

	(function updateCurrentWeather()
	{
		var iconTable = {
			'01d':'wi-day-sunny',
			'02d':'wi-day-cloudy',
			'03d':'wi-cloudy',
			'04d':'wi-cloudy-windy',
			'09d':'wi-showers',
			'10d':'wi-rain',
			'11d':'wi-thunderstorm',
			'13d':'wi-snow',
			'50d':'wi-fog',
			'01n':'wi-night-clear',
			'02n':'wi-night-cloudy',
			'03n':'wi-night-cloudy',
			'04n':'wi-night-cloudy',
			'09n':'wi-night-showers',
			'10n':'wi-night-rain',
			'11n':'wi-night-thunderstorm',
			'13n':'wi-night-snow',
			'50n':'wi-night-alt-cloudy-windy'
		}

		$.getJSON('http://api.openweathermap.org/data/2.5/weather', weatherParams, function(json, textStatus) {

			var temp = roundVal(json.main.temp);
			var temp_min = roundVal(json.main.temp_min);
			var temp_max = roundVal(json.main.temp_max);

			var wind = roundVal(json.wind.speed);

			var iconClass = iconTable[json.weather[0].icon];
			var icon = $('').addClass('icon').addClass('dimmed').addClass('wi').addClass(iconClass);
			$('.temp').updateWithText(icon.outerHTML()+temp+'°', 1000);

			// var forecast = 'Min: '+temp_min+'°, Max: '+temp_max+'°';
			// $('.forecast').updateWithText(forecast, 1000);

			var now = new Date();
			var sunrise = new Date(json.sys.sunrise*1000).toTimeString().substring(0,5);
			var sunset = new Date(json.sys.sunset*1000).toTimeString().substring(0,5);

			var windString = ' ' + kmh2beaufort(wind) ;
			var sunString = ' ' + sunrise;
			if (json.sys.sunrise*1000 < now && json.sys.sunset*1000 > now) {
				sunString = ' ' + sunset;
			}

			$('.windsun').updateWithText(windString+' '+sunString, 1000);
		});

		setTimeout(function() {
			updateCurrentWeather();
		}, 60000);
	})();

	(function updateWeatherForecast()
	{
			$.getJSON('http://api.openweathermap.org/data/2.5/forecast', weatherParams, function(json, textStatus) {

			var forecastData = {};

			for (var i in json.list) {
				var forecast = json.list[i];
				var dateKey  = forecast.dt_txt.substring(0, 10);

				if (forecastData[dateKey] == undefined) {
					forecastData[dateKey] = {
						'timestamp':forecast.dt * 1000,
						'temp_min':forecast.main.temp,
						'temp_max':forecast.main.temp
					};
				} else {
					forecastData[dateKey]['temp_min'] = (forecast.main.temp < forecastData[dateKey]['temp_min']) ? forecast.main.temp : forecastData[dateKey]['temp_min'];
					forecastData[dateKey]['temp_max'] = (forecast.main.temp > forecastData[dateKey]['temp_max']) ? forecast.main.temp : forecastData[dateKey]['temp_max'];
				}

			}

			var forecastTable = $('
').addClass('forecast-table');
			var opacity = 1;
			for (var i in forecastData) {
				var forecast = forecastData[i];
				var dt = new Date(forecast.timestamp);
				var row = $('
').css('opacity', opacity);

				row.append($('').addClass('day').html(dayAbbr[dt.getDay()]));
				row.append($('').addClass('temp-max').html(roundVal(forecast.temp_max)));
				row.append($('').addClass('temp-min').html(roundVal(forecast.temp_min)));

				forecastTable.append(row);
				opacity -= 0.155;
			}

			$('.forecast').updateWithText(forecastTable, 1000);
		});

		setTimeout(function() {
			updateWeatherForecast();
		}, 60000);
	})();

	(function fetchNews() {
		$.feedToJson({
			feed:'http://feeds.nos.nl/nosjournaal?format=rss',
			//feed:'http://www.nu.nl/feeds/rss/achterklap.rss',
			//feed:'http://www.nu.nl/feeds/rss/opmerkelijk.rss',
			success: function(data){
				news = [];
				for (var i in data.item) {
					var item = data.item[i];
					news.push(item.title);
				}
			}
		});
		setTimeout(function() {
			fetchNews();
		}, 60000);
	})();

	(function showNews() {
		var newsItem = news[newsIndex];
		$('.news').updateWithText(newsItem,2000);

		newsIndex--;
		if (newsIndex < 0) newsIndex = news.length - 1;
		setTimeout(function() {
			showNews();
		}, 5500);
	})();

});
<commit_msg>Update main.js<commit_after>jQuery.fn.updateWithText = function(text, speed)
{
	var dummy = $('
').html(text);

	if ($(this).html() != dummy.html())
	{
		$(this).fadeOut(speed/2, function() {
			$(this).html(text);
			$(this).fadeIn(speed/2, function() {
				//done
			});
		});
	}
}

jQuery.fn.outerHTML = function(s) {
    return s
        ? this.before(s).remove()
        : jQuery("
").append(this.eq(0).clone()).html();
};

function roundVal(temp)
{
	return Math.round(temp * 10) / 10;
}

function kmh2beaufort(kmh)
{
	var speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
	for (var beaufort in speeds) {
		var speed = speeds[beaufort];
		if (speed > kmh) {
			return beaufort;
		}
	}
	return 12;
}

jQuery(document).ready(function($) {

	var news = [];
	var newsIndex = 0;

	var eventList = [];

	var lastCompliment;
	var compliment;

    // multi-langugage support according to browser-lang
    var lang = window.navigator.language;
    switch (lang)
    {
        case 'de':
            var days = ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'];
            var months = ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
            var dayAbbr = ['So','Mo','Di','Mi','Do','Fr','Sa'];
            var today = 'heute';
            var tomorrow = 'morgen';
            var in_days = 'Tage';
            break;
        case 'nl':
            var days = ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'];
            var months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
            var dayAbbr = ['zo','ma','di','wo','do','vr','za'];
            var today = 'vandaag';
            var tomorrow = 'morgen';
            var in_days = 'dagen';
            break;
       case 'fr':
            var days = ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'];
            var months = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
            var dayAbbr = ['dim','lun','mar','mer','jeu','ven','sam'];
            var today = 'aujourd\'hui';
            var tomorrow = 'demain';
            var in_days = 'jour(s)';
            break;
        default:
            var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
            var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
            var dayAbbr = ['Sun','Mon','Tues','Wed','Thur','Fri','Sat'];
            var today = 'Today';
            var tomorrow = 'Tomorrow';
            var in_days = 'days';
    }

	//connect do Xbee monitor
	var socket = io.connect('http://rpi-development.local:8080');
	socket.on('dishwasher', function (dishwasherReady) {
		if (dishwasherReady) {
			$('.dishwasher').fadeIn(2000);
			$('.lower-third').fadeOut(2000);
		} else {
			$('.dishwasher').fadeOut(2000);
			$('.lower-third').fadeIn(2000);
		}
	});

	var weatherParams = {
		'q':'Baarn,Netherlands',
		'units':'metric',
		'lang':lang
	};

	(function checkVersion()
	{
		$.getJSON('githash.php', {}, function(json, textStatus) {
			if (json) {
				if (json.gitHash != gitHash) {
					window.location.reload();
					window.location.href=window.location.href;
				}
			}
		});
		setTimeout(function() {
			checkVersion();
		}, 3000);
	})();

	(function updateTime()
	{
		var now = new Date();

		var day = now.getDay();
		var date = now.getDate();
		var month = now.getMonth();
		var year = now.getFullYear();

		var date = days[day] + ', ' + date+' ' + months[month] + ' ' + year;

		$('.date').html(date);
		$('.time').html(now.toTimeString().substring(0,5) + ''+now.toTimeString().substring(6,8)+'');

		setTimeout(function() {
			updateTime();
		}, 1000);
	})();

	(function updateCalendarData()
	{
		new ical_parser("calendar.php", function(cal){
        	events = cal.getEvents();
        	eventList = [];

        	for (var i in events) {
        		var e = events[i];
        		for (var key in e) {
        			var value = e[key];
					var seperator = key.search(';');
					if (seperator >= 0) {
						var mainKey = key.substring(0,seperator);
						var subKey = key.substring(seperator+1);

						var dt;
						if (subKey == 'VALUE=DATE') {
							//date
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8));
						} else {
							//time
							dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8), value.substring(9,11), value.substring(11,13), value.substring(13,15));
						}

						if (mainKey == 'DTSTART') e.startDate = dt;
						if (mainKey == 'DTEND') e.endDate = dt;
					}
        		}

        		var now = new Date();
        		var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        		var days = moment(e.startDate).diff(moment(today), 'days');

        		//only add fututre events
        		if (days >= 0) {
	        		eventList.push({'description':e.SUMMARY,'days':days});
        		}
        	};
        	eventList.sort(function(a,b){return a.days-b.days});

        	setTimeout(function() {
        		updateCalendarData();
        	}, 60000);
    	});
	})();

	(function updateCalendar()
	{
		table = $('
').addClass('xsmall').addClass('calendar-table');
		opacity = 1;

		for (var i in eventList) {
			var e = eventList[i];
			var days = e.days;

			var daysString = (days == 1) ? tomorrow :  days + ' ' + in_days;
    		if (days == 0) {
    			daysString = today;
    		}

			var row = $('
').css('opacity',opacity);
			row.append($('').html(e.description).addClass('description'));
			row.append($('').html(daysString).addClass('days dimmed'));
			table.append(row);

			opacity -= 1 / eventList.length;
		}

		$('.calendar').updateWithText(table,1000);

		setTimeout(function() {
        	updateCalendar();
        }, 1000);
	})();

	(function updateCompliment()
	{

		var compliments = [
			'Hey, handsome!',
			'Hi, sexy!',
			'Hello, beauty!',
			'You look sexy!',
			'Wow, you look hot!',
			'Looking good today!',
			'You look nice!',
			'Enjoy your day!'
		];

		while (compliment == lastCompliment) {
			compliment = Math.floor(Math.random()*compliments.length);
		}

		$('.compliment').updateWithText(compliments[compliment], 4000);

		lastCompliment = compliment;

		setTimeout(function() {
			updateCompliment(true);
		}, 30000);

	})();

	(function updateCurrentWeather()
	{
		var iconTable = {
			'01d':'wi-day-sunny',
			'02d':'wi-day-cloudy',
			'03d':'wi-cloudy',
			'04d':'wi-cloudy-windy',
			'09d':'wi-showers',
			'10d':'wi-rain',
			'11d':'wi-thunderstorm',
			'13d':'wi-snow',
			'50d':'wi-fog',
			'01n':'wi-night-clear',
			'02n':'wi-night-cloudy',
			'03n':'wi-night-cloudy',
			'04n':'wi-night-cloudy',
			'09n':'wi-night-showers',
			'10n':'wi-night-rain',
			'11n':'wi-night-thunderstorm',
			'13n':'wi-night-snow',
			'50n':'wi-night-alt-cloudy-windy'
		}

		$.getJSON('http://api.openweathermap.org/data/2.5/weather', weatherParams, function(json, textStatus) {

			var temp = roundVal(json.main.temp);
			var temp_min = roundVal(json.main.temp_min);
			var temp_max = roundVal(json.main.temp_max);

			var wind = roundVal(json.wind.speed);

			var iconClass = iconTable[json.weather[0].icon];
			var icon = $('').addClass('icon').addClass('dimmed').addClass('wi').addClass(iconClass);
			$('.temp').updateWithText(icon.outerHTML()+temp+'°', 1000);

			// var forecast = 'Min: '+temp_min+'°, Max: '+temp_max+'°';
			// $('.forecast').updateWithText(forecast, 1000);

			var now = new Date();
			var sunrise = new Date(json.sys.sunrise*1000).toTimeString().substring(0,5);
			var sunset = new Date(json.sys.sunset*1000).toTimeString().substring(0,5);

			var windString = ' ' + kmh2beaufort(wind) ;
			var sunString = ' ' + sunrise;
			if (json.sys.sunrise*1000 < now && json.sys.sunset*1000 > now) {
				sunString = ' ' + sunset;
			}

			$('.windsun').updateWithText(windString+' '+sunString, 1000);
		});

		setTimeout(function() {
			updateCurrentWeather();
		}, 60000);
	})();

	(function updateWeatherForecast()
	{
			$.getJSON('http://api.openweathermap.org/data/2.5/forecast', weatherParams, function(json, textStatus) {

			var forecastData = {};

			for (var i in json.list) {
				var forecast = json.list[i];
				var dateKey  = forecast.dt_txt.substring(0, 10);

				if (forecastData[dateKey] == undefined) {
					forecastData[dateKey] = {
						'timestamp':forecast.dt * 1000,
						'temp_min':forecast.main.temp,
						'temp_max':forecast.main.temp
					};
				} else {
					forecastData[dateKey]['temp_min'] = (forecast.main.temp < forecastData[dateKey]['temp_min']) ? forecast.main.temp : forecastData[dateKey]['temp_min'];
					forecastData[dateKey]['temp_max'] = (forecast.main.temp > forecastData[dateKey]['temp_max']) ? forecast.main.temp : forecastData[dateKey]['temp_max'];
				}

			}

			var forecastTable = $('
').addClass('forecast-table');
			var opacity = 1;
			for (var i in forecastData) {
				var forecast = forecastData[i];
				var dt = new Date(forecast.timestamp);
				var row = $('
').css('opacity', opacity);

				row.append($('').addClass('day').html(dayAbbr[dt.getDay()]));
				row.append($('').addClass('temp-max').html(roundVal(forecast.temp_max)));
				row.append($('').addClass('temp-min').html(roundVal(forecast.temp_min)));

				forecastTable.append(row);
				opacity -= 0.155;
			}

			$('.forecast').updateWithText(forecastTable, 1000);
		});

		setTimeout(function() {
			updateWeatherForecast();
		}, 60000);
	})();

	(function fetchNews() {
		$.feedToJson({
			feed:'http://feeds.nos.nl/nosjournaal?format=rss',
			//feed:'http://www.nu.nl/feeds/rss/achterklap.rss',
			//feed:'http://www.nu.nl/feeds/rss/opmerkelijk.rss',
			success: function(data){
				news = [];
				for (var i in data.item) {
					var item = data.item[i];
					news.push(item.title);
				}
			}
		});
		setTimeout(function() {
			fetchNews();
		}, 60000);
	})();

	(function showNews() {
		var newsItem = news[newsIndex];
		$('.news').updateWithText(newsItem,2000);

		newsIndex--;
		if (newsIndex < 0) newsIndex = news.length - 1;
		setTimeout(function() {
			showNews();
		}, 5500);
	})();

});
<|endoftext|>


<commit_before>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.pulsarSortable = new pulsar.PulsarSortableComponent($html, window);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html, pulsar.disableUi);
	pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);
    pulsar.tableDetail = new pulsar.TableDetailComponent($html);
    pulsar.repeaterManager = new pulsar.RepeaterManagerComponent(
        pulsar.pulsarForm,
        pulsar.repeaterComponentFactory,
        $html
    );

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarSortable.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');
        pulsar.repeaterManager.init();

        // Switch out .svg for .png for <img> elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });
    });

}(jQuery));
<commit_msg>Table detail - re-added missing line from a didgy merge<commit_after>(function ($) {

    // Protect IE8 from any erroneous console.log uses which would break everything
    if (!window.console) {
        console = { log: function() {} }
    };

    var $html = $('html'),
        lt10 = $html.hasClass('lt-ie10');

    $html.removeClass('no-js');

    pulsar.button = new pulsar.ButtonComponent($html);
    pulsar.disableUi = new pulsar.DisableUiComponent($html);
    pulsar.flash = new pulsar.FlashMessageComponent($html);
    pulsar.helpText = new pulsar.HelpTextComponent($html, window, document);
    pulsar.pulsarForm = new pulsar.PulsarFormComponent($html);
    pulsar.pulsarUI = new pulsar.PulsarUIComponent($html, pulsar.history);
    pulsar.pulsarSortable = new pulsar.PulsarSortableComponent($html, window);
    pulsar.signIn = new pulsar.SignInComponent($html);
    pulsar.masterSwitch = new pulsar.MasterSwitchComponent($html, pulsar.disableUi);
	pulsar.modulePermissions = new pulsar.ModulePermissionsComponent($html);
    pulsar.navMain = new pulsar.NavMainComponent($html, window);
    pulsar.filterBar = new pulsar.FilterBarComponent($html);
    pulsar.tableDetail = new pulsar.TableDetailComponent($html);
    pulsar.repeaterManager = new pulsar.RepeaterManagerComponent(
        pulsar.pulsarForm,
        pulsar.repeaterComponentFactory,
        $html
    );

    $(function () {
        pulsar.button.init();
        pulsar.flash.init();
        pulsar.helpText.init();
        pulsar.helpText.updateHelpSidebar();
        pulsar.pulsarForm.init();
        pulsar.pulsarSortable.init();
        pulsar.pulsarUI.init();
        pulsar.signIn.init();
        pulsar.masterSwitch.init();
        pulsar.modulePermissions.init();
        pulsar.navMain.init();
        pulsar.filterBar.init();
        pulsar.disableUi.init();
        pulsar.tableDetail.init();
        pulsar.dropZoneComponent = pulsar.DropZoneComponentFactory.create($('body')[0], '.dropzone');
        pulsar.repeaterManager.init();

        // Switch out .svg for .png for <img> elements in older browsers
        pulsar.svgeezy.init('nocheck', 'png');

        // Use clickover enhancements for popovers
        $('[rel="clickover"]').clickover({ 'global_close': true });

        // Open navigation (should be added to NavMainComponent)
        $('.mobile-menu-button').on('click', function(e) {
            e.preventDefault();

            $('body').toggleClass('open-nav');
            $(this).toggleClass('open');

            if ($(this).text() == 'Menu') {
                $(this).text('Close');
            } else {
                $(this).text('Menu');
            }
        });

        // jsTree
        $('#container').jstree({
            'plugins' : ['state']
        });

        // DropZone
        pulsar.dropZoneComponent.init({
            supported: !lt10,
            showInputNode: lt10
        });
    });

}(jQuery));
<|endoftext|>


<commit_before>/* globals UTILS*/
UTILS.ajax('../data/notification.txt', {
	method: 'GET',
	done: function (response) {
		if (response && response !== '') {
			var message = document.getElementsByClassName('notifications')[0];
			message.innerHTML = response;
			message.style.display = 'block';
		}
	},
	fail: function (err) {
		console.log(err.message);
	}
});
<commit_msg>Update main.js<commit_after>/* globals UTILS*/
UTILS.ajax('/data/notification.txt', {
	method: 'GET',
	done: function (response) {
		if (response && response !== '') {
			var message = document.getElementsByClassName('notifications')[0];
			message.innerHTML = response;
			message.style.display = 'block';
		}
	},
	fail: function (err) {
		console.log(err.message);
	}
});
<|endoftext|>


<commit_before>'use strict';

function repo_drawlogic(){
    // Draw ripples.
    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_setproperties({
            'properties': {
              'fillStyle': entity_entities[entity]['color'],
            },
          });
          canvas_buffer.fillRect(
            entity_entities[entity]['x'] - entity_entities[entity]['width'],
            entity_entities[entity]['y'] - entity_entities[entity]['height'],
            entity_entities[entity]['width'] * 2,
            entity_entities[entity]['height'] * 2
          );
      },
    });
}

function repo_logic(){
    ripple_timer += 1;
    if(ripple_timer >= core_storage_data['ripple-timer-max']){
        ripple_timer = 0;

        // Create new ripple.
        entity_create({
          'properties': {
            'color': '#' + core_random_hex(),
            'height': 0,
            'width': 0,
            'x': core_mouse['down-x'],
            'y': core_mouse['down-y'],
          },
        });
    }

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          // Increase size of ripple.
          entity_entities[entity]['height'] += core_storage_data['height-speed'];
          entity_entities[entity]['width'] += core_storage_data['width-speed'];

          if(entity_entities[entity]['height'] > canvas_properties['height-half']
            || entity_entities[entity]['width'] > canvas_properties['width-half']){
              entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'events': {
        'restart': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'ripple_timer': 0,
      },
      'info': '<input id=restart type=button value=Restart>',
      'mousebinds': {
        'mousedown': {
          'todo': function(){
              ripple_timer = 99;
          },
        },
        'mousemove': {
          'todo': function(){
              if(core_mouse['down-0']){
                  core_mouse['down-x'] = core_mouse['x'];
                  core_mouse['down-y'] = core_mouse['y'];

                  ripple_timer = 99;
              }
          },
        },
      },
      'reset': canvas_setmode,
      'storage': {
        'height-speed': 1,
        'ripple-timer-max': 25,
        'width-speed': 1,
      },
      'storage-menu': '

<input id=height-speed>Height Speed'
        + '
<input id=ripple-timer-max>Ripple Timer Max'
        + '
<input id=width-speed>Width Speed
',
      'title': 'ColorDrops.htm',
    });
    canvas_init();
}
<commit_msg>added number type to settings inputs, removed unnecessary comments<commit_after>'use strict';

function repo_drawlogic(){
    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_setproperties({
            'properties': {
              'fillStyle': entity_entities[entity]['color'],
            },
          });
          canvas_buffer.fillRect(
            entity_entities[entity]['x'] - entity_entities[entity]['width'],
            entity_entities[entity]['y'] - entity_entities[entity]['height'],
            entity_entities[entity]['width'] * 2,
            entity_entities[entity]['height'] * 2
          );
      },
    });
}

function repo_logic(){
    ripple_timer += 1;
    if(ripple_timer >= core_storage_data['ripple-timer-max']){
        ripple_timer = 0;

        entity_create({
          'properties': {
            'color': '#' + core_random_hex(),
            'height': 0,
            'width': 0,
            'x': core_mouse['down-x'],
            'y': core_mouse['down-y'],
          },
        });
    }

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          entity_entities[entity]['height'] += core_storage_data['height-speed'];
          entity_entities[entity]['width'] += core_storage_data['width-speed'];

          if(entity_entities[entity]['height'] > canvas_properties['height-half']
            || entity_entities[entity]['width'] > canvas_properties['width-half']){
              entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'events': {
        'restart': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'ripple_timer': 0,
      },
      'info': '<input id=restart type=button value=Restart>',
      'mousebinds': {
        'mousedown': {
          'todo': function(){
              ripple_timer = 99;
          },
        },
        'mousemove': {
          'todo': function(){
              if(core_mouse['down-0']){
                  core_mouse['down-x'] = core_mouse['x'];
                  core_mouse['down-y'] = core_mouse['y'];

                  ripple_timer = 99;
              }
          },
        },
      },
      'reset': canvas_setmode,
      'storage': {
        'height-speed': 1,
        'ripple-timer-max': 25,
        'width-speed': 1,
      },
      'storage-menu': '

<input id=height-speed type=number>Height Speed'
        + '
<input id=ripple-timer-max min=1 type=number>Ripple Timer Max'
        + '
<input id=width-speed type=number>Width Speed
',
      'title': 'ColorDrops.htm',
    });
    canvas_init();
}
<|endoftext|>


<commit_before>
/**
 *
 *  Main JavaScript
 *
 *  @package gleesik_scripts
 *
 **/

 // IIFE - Immediately Invoked Function Expression
(function($, window, document) {

  // The $ is now locally scoped

  // Listen for the jQuery ready event on the document
  $(function() {

    // The DOM is ready!

    // Global Variables
    var $window = $(window);

    /**
     *  Page Loader
     **/
    setTimeout(function() {
      $('.page-loader').addClass('load-complete');
    }, 1500);

    /**
     *  Parallax with Scrollax.js - Initialization
     **/
    'use strict';
    $.Scrollax();

    /**
     *  Main Menu Navigation
     **/
    var $body = $('body');
    var $nav_menu = $('.navigation-bar');
    var $nav_menu_link = $('#navMenu ul li a');
    var $toggle_menu_button = $('.navTrigger');

    // Navigation Menu Link
    $nav_menu_link.on('click', function() {

      // Select Current Navigation Item
      $nav_menu_link.parent().removeClass('current-menu-item');
      $(this).parent().addClass('current-menu-item');

      // Close Mobile Menu
      $nav_menu.removeClass('active');
      $toggle_menu_button.removeClass('active');
      $body.removeClass('no-scroll');

    });

    // Toggle Mobile Menu
    $toggle_menu_button.on('click', function() {
      $nav_menu.toggleClass('active');
      $body.toggleClass('no-scroll');
      $(this).toggleClass('active');
    });

    // Remove all classes on window resize
    $window.on('resize', function() {
      $nav_menu.removeClass('active');
      $body.removeClass('no-scroll');
      $toggle_menu_button.removeClass('active');
    });

    /**
     *  Portfolio
     **/
    var $filter_menu_item = $('.filter-menu ul li');
    var $portfolio_grid = $('.portfolio-grid');
    var $portfolio_grid_item = $portfolio_grid.children(".item");
    var $overlay = $portfolio_grid.children("#overlay");
    var $img = '';
    var $data_filters = null;

    // Filter Menu
    $filter_menu_item.on('click', function() {

      // Filter Menu
      $filter_menu_item.removeClass('current');
      $(this).addClass('current');

      // Collecting Data Filters
      $data_filters = $(this).data('filter');

      // Hide All Portfolio Items
      if($data_filters == 'all') {
        $portfolio_grid_item.addClass('visible');
      }
      else { // Show Portfolio Items from filter
        $portfolio_grid_item.removeClass('visible');
        $($data_filters).addClass('visible');
      }

    });

    // Show Image - Lightbox
    $portfolio_grid_item.find(".item-expand").on('click', function(e) {

      // Prevent Default Link Event
      e.preventDefault();

      // Get Image Link
      var $src = $(this).attr("href");

      // Create Image on the DOM
      $overlay.append($img);

      // Show Overlay Image
      $overlay.fadeIn(200).children("img").attr("src", $src);

      // Lock Body Scroll
      $body.toggleClass('no-scroll');

    });

    // Hide Overlay Lightbox
    $overlay.on('click', function() {

      // Hide Overlay Image
      $(this).fadeOut(200);

      // Remove Image from DOM
      $overlay.children("img").remove();

      // Unlock Body Scroll
      $body.toggleClass('no-scroll');

    });

    /**
     *  Scroll Event
     **/
    $window.scroll(function() {

      // Scroll Variables
      var $scrollTop = $window.scrollTop();
      var $windowHeight = $window.height();

      /**
       *  Go to Top Button
       **/
      var $go_top = $('.go-to-top-button');

      if ( $scrollTop > 600 ) {
        $go_top.addClass('active');
      } else {
        $go_top.removeClass('active');
      }

      // Reveal Item on Scroll
      function revealItem($container, $item) {
        if($scrollTop > ($container.offset().top - $windowHeight/1.3 )) {

          $item.each(function(i) {
            setTimeout(function() {
              $item.eq(i).addClass("is-showing");
            }, 150 * (i+1) );
          });

        }
      }

      // Portfolio Reveal Images
      revealItem($portfolio_grid, $portfolio_grid_item);

    });

    /**
     *  Testimonials Carousel Setup
     **/
    $("#testimonials-carousel").owlCarousel({

        navigation : true, // Show next & prev buttons
        slideSpeed : 300,
        paginationSpeed : 400,
        singleItem: true

    });

    /**
     *  Smooth Scrolling for Links
     **/
    $('a[href*="#"]:not([href="#"])').on('click', function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
       var target = $(this.hash);
       target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
        $('html, body').animate({
           scrollTop: target.offset().top
        }, 1000);
        return false;
       }
      }
    });

  });

}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
<commit_msg>Fix constant exception when no portfolio grid on page<commit_after>
/**
 *
 *  Main JavaScript
 *
 *  @package gleesik_scripts
 *
 **/

 // IIFE - Immediately Invoked Function Expression
(function($, window, document) {

  // The $ is now locally scoped

  // Listen for the jQuery ready event on the document
  $(function() {

    // The DOM is ready!

    // Global Variables
    var $window = $(window);

    /**
     *  Page Loader
     **/
    setTimeout(function() {
      $('.page-loader').addClass('load-complete');
    }, 1500);

    /**
     *  Parallax with Scrollax.js - Initialization
     **/
    'use strict';
    $.Scrollax();

    /**
     *  Main Menu Navigation
     **/
    var $body = $('body');
    var $nav_menu = $('.navigation-bar');
    var $nav_menu_link = $('#navMenu ul li a');
    var $toggle_menu_button = $('.navTrigger');

    // Navigation Menu Link
    $nav_menu_link.on('click', function() {

      // Select Current Navigation Item
      $nav_menu_link.parent().removeClass('current-menu-item');
      $(this).parent().addClass('current-menu-item');

      // Close Mobile Menu
      $nav_menu.removeClass('active');
      $toggle_menu_button.removeClass('active');
      $body.removeClass('no-scroll');

    });

    // Toggle Mobile Menu
    $toggle_menu_button.on('click', function() {
      $nav_menu.toggleClass('active');
      $body.toggleClass('no-scroll');
      $(this).toggleClass('active');
    });

    // Remove all classes on window resize
    $window.on('resize', function() {
      $nav_menu.removeClass('active');
      $body.removeClass('no-scroll');
      $toggle_menu_button.removeClass('active');
    });

    /**
     *  Portfolio
     **/
    var $filter_menu_item = $('.filter-menu ul li');
    var $portfolio_grid = $('.portfolio-grid');
    var $portfolio_grid_item = $portfolio_grid.children(".item");
    var $overlay = $portfolio_grid.children("#overlay");
    var $img = '';
    var $data_filters = null;

    // Filter Menu
    $filter_menu_item.on('click', function() {

      // Filter Menu
      $filter_menu_item.removeClass('current');
      $(this).addClass('current');

      // Collecting Data Filters
      $data_filters = $(this).data('filter');

      // Hide All Portfolio Items
      if($data_filters == 'all') {
        $portfolio_grid_item.addClass('visible');
      }
      else { // Show Portfolio Items from filter
        $portfolio_grid_item.removeClass('visible');
        $($data_filters).addClass('visible');
      }

    });

    // Show Image - Lightbox
    $portfolio_grid_item.find(".item-expand").on('click', function(e) {

      // Prevent Default Link Event
      e.preventDefault();

      // Get Image Link
      var $src = $(this).attr("href");

      // Create Image on the DOM
      $overlay.append($img);

      // Show Overlay Image
      $overlay.fadeIn(200).children("img").attr("src", $src);

      // Lock Body Scroll
      $body.toggleClass('no-scroll');

    });

    // Hide Overlay Lightbox
    $overlay.on('click', function() {

      // Hide Overlay Image
      $(this).fadeOut(200);

      // Remove Image from DOM
      $overlay.children("img").remove();

      // Unlock Body Scroll
      $body.toggleClass('no-scroll');

    });

    /**
     *  Scroll Event
     **/
    $window.scroll(function() {

      // Scroll Variables
      var $scrollTop = $window.scrollTop();
      var $windowHeight = $window.height();

      /**
       *  Go to Top Button
       **/
      var $go_top = $('.go-to-top-button');

      if ( $scrollTop > 600 ) {
        $go_top.addClass('active');
      } else {
        $go_top.removeClass('active');
      }

      // Reveal Item on Scroll
      function revealItem($container, $item) {
        if($scrollTop > ($container.offset().top - $windowHeight/1.3 )) {

          $item.each(function(i) {
            setTimeout(function() {
              $item.eq(i).addClass("is-showing");
            }, 150 * (i+1) );
          });

        }
      }

      // Portfolio Reveal Images
      if ($portfolio_grid && $portfolio_grid_item && $portfolio_grid_item.length > 0) {
        revealItem($portfolio_grid, $portfolio_grid_item);
      }
    });

    /**
     *  Testimonials Carousel Setup
     **/
    $("#testimonials-carousel").owlCarousel({

        navigation : true, // Show next & prev buttons
        slideSpeed : 300,
        paginationSpeed : 400,
        singleItem: true

    });

    /**
     *  Smooth Scrolling for Links
     **/
    $('a[href*="#"]:not([href="#"])').on('click', function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
       var target = $(this.hash);
       target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
        $('html, body').animate({
           scrollTop: target.offset().top
        }, 1000);
        return false;
       }
      }
    });

  });

}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
<|endoftext|>


<commit_before>if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var container;
var camera, scene, renderer, stats;
var plane;
var mouse, controls, raycaster;
var rollOverMesh, rollOverMaterial;
var pivotCenter = new THREE.Vector3(0, 0, 0);
var cubeGeo, cubeMaterial;
var objects = [];
var cells = [];
var gui;
var sRule = [2,3];
var bRule = [3];
init();
render();

function init() {
	//Add main div
	container = document.createElement( 'div' );
	document.body.appendChild( container );
	//Create camera and scene
	camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
	camera.position.set( 500, 800, 1300 );
	camera.lookAt( pivotCenter );
	scene = new THREE.Scene();

	//Add lights
	var light = new THREE.AmbientLight(0xffffff);
	scene.add(light);

	// cubes
	cubeGeo = new THREE.BoxGeometry( 50, 50, 50 );
	cubeMaterial = new THREE.MeshLambertMaterial( { color: 0x99ccff, ambient: 0x00ff80, shading: THREE.FlatShading, map: THREE.ImageUtils.loadTexture( "img/square-outline.png" ) } );
	cubeMaterial.ambient = cubeMaterial.color;
	//Create grid
	var size = 500, step = 50;
	var geometry = new THREE.Geometry();
	for ( var i = - size; i <= size; i += step ) {
		geometry.vertices.push( new THREE.Vector3( - size, 0, i ) );
		geometry.vertices.push( new THREE.Vector3(   size, 0, i ) );

		geometry.vertices.push( new THREE.Vector3( i, 0, - size ) );
		geometry.vertices.push( new THREE.Vector3( i, 0,   size ) );
	}

	var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2, transparent: true } );
	var line = new THREE.Line( geometry, material, THREE.LinePieces );
	scene.add( line );

	//Create renderer
	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setClearColor( 0xf0f0f0 );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );
	container.appendChild( renderer.domElement );

	// roll-over helpers
	rollOverGeo = new THREE.BoxGeometry( 50, 50, 50 );
	rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
	rollOverMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
	scene.add( rollOverMesh );

	//Add camera controls
	controls = new THREE.OrbitControls(camera);
	controls.addEventListener( 'change', render );

	//Cube drawing
	var geometry = new THREE.PlaneBufferGeometry( 1000, 1000 );
	geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
	plane = new THREE.Mesh( geometry );
	plane.visible = false;
	scene.add( plane );
	objects.push( plane );
	raycaster = new THREE.Raycaster();
	mouse = new THREE.Vector2();

	//GUI
	var gui = new dat.GUI();
	var text = {};
	text.Play = function() {
	var newCells = {};
	for( var cell in cells ) {
		var j=0;
		for(var i =-1; i<=1; i++){
			for(var k =-1; k<=1; k++){
				var x = cells[cell].position.x - 50*i;
				var y = cells[cell].position.y - 50*j;
				var z = cells[cell].position.z - 50*k;
				if(newCells[[x,y,z]]!==undefined) {
					newCells[[x,y,z]] = [newCells[[x,y,z]][0] || (i==0 && j==0 && k==0), newCells[[x,y,z]][1]+1];
				} else {
					newCells[[x,y,z]] = [i==0 && j==0 && k==0, 1];
				}
				if(i==0 && j==0 && k==0) newCells[[x,y,z]][1]--;
				//TODO: check boundaries
			}
		}
		//TODO: add 3D coordinates
		scene.remove(cells[cell]);
	}
	objects=[plane];
	cells = [];
	for( var cell in newCells ){
		if(newCells[cell][0]){
			//Survive rule
			if(sRule.indexOf(newCells[cell][1])>-1){
				var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
				var pos = cell.split(',');
				voxel.position.set(pos[0],pos[1],pos[2]);
				cells.push(voxel);
				scene.add( voxel );
			}
		} else {
			//Born rule
			if(bRule.indexOf(newCells[cell][1])>-1){
				var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
				var pos = cell.split(',');
				voxel.position.set(pos[0],pos[1],pos[2]);
				cells.push(voxel);
				scene.add( voxel );
			}
		}
	}
	};
	text.Speed = 1;
	text.Clear = false;
	text.Survive = '2';
	text.Born = '23';
	text.Expansion3D = false;
	text.Painting3D = false;
	var f1 = gui.addFolder('Controls')
	f1.add(text, 'Play');
	f1.add(text, 'Speed', 1, 5);
	f1.add(text, 'Clear');
	f1.open();
	var f2 = gui.addFolder('Rules');
	f2.add(text, 'Survive');
	f2.add(text, 'Born');
	var f3 = gui.addFolder('Settings');
	f3.add(text, 'Expansion3D');
	f3.add(text, 'Painting3D');

	document.addEventListener( 'mousedown', onDocumentMouseDown, false );
	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	window.addEventListener( 'resize', onWindowResize, false );
}

function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );
	render();
}
function onDocumentMouseMove( event ) {

	event.preventDefault();
	mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
	raycaster.setFromCamera( mouse, camera );
	var intersects = raycaster.intersectObjects( objects );
	if ( intersects.length > 0 ) {
		var intersect = intersects[ 0 ];
		rollOverMesh.position.copy( intersect.point ).add( intersect.face.normal );
		rollOverMesh.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
	}
	render();

}
function onDocumentMouseDown( event ) {
	event.preventDefault();
	mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
	raycaster.setFromCamera( mouse, camera );
	var intersects = raycaster.intersectObjects( objects );
	if ( intersects.length > 0 ) {

		var intersect = intersects[ 0 ];
		if ( intersect.object != plane ) return;
			var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
			voxel.position.copy( intersect.point ).add( intersect.face.normal );
			voxel.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
			scene.add( voxel );
			objects.push(voxel);
			cells.push(voxel);
		render();
	}
}

function render() {
	renderer.render( scene, camera );
}
<commit_msg>Added all basic functionalities<commit_after>if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var container;
var camera, scene, renderer, stats;
var plane;
var mouse, controls, raycaster;
var rollOverMesh, rollOverMaterial;
var pivotCenter = new THREE.Vector3(0, 0, 0);
var cubeGeo, cubeMaterial;
var objects = [];
var cells = [];
var gui;
var sRule = [2,3];
var bRule = [3,6];
var ruleS, ruleB;
var text = {};
var running = false;
var item;
init();

function init() {

	//Add main div
	container = document.createElement( 'div' );
	document.body.appendChild( container );

	//Create camera and scene
	camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
	camera.position.set( 500, 800, 1300 );
	camera.lookAt( pivotCenter );
	scene = new THREE.Scene();

	//Add lights
	var light = new THREE.AmbientLight(0xffffff);
	scene.add(light);

	// cubes
	cubeGeo = new THREE.BoxGeometry( 50, 50, 50 );
	cubeMaterial = new THREE.MeshLambertMaterial( { color: 0x99ccff, ambient: 0x00ff80, shading: THREE.FlatShading, map: THREE.ImageUtils.loadTexture( "img/square-outline.png" ) } );
	cubeMaterial.ambient = cubeMaterial.color;
	//Create grid
	var size = 500, step = 50;
	var geometry = new THREE.Geometry();
	for ( var i = - size; i <= size; i += step ) {
		geometry.vertices.push( new THREE.Vector3( - size, 0, i ) );
		geometry.vertices.push( new THREE.Vector3(   size, 0, i ) );

		geometry.vertices.push( new THREE.Vector3( i, 0, - size ) );
		geometry.vertices.push( new THREE.Vector3( i, 0,   size ) );
	}

	var material = new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2, transparent: true } );
	var line = new THREE.Line( geometry, material, THREE.LinePieces );
	scene.add( line );

	//Create renderer
	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setClearColor( 0xf0f0f0 );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );
	container.appendChild( renderer.domElement );

	// roll-over helpers
	rollOverGeo = new THREE.BoxGeometry( 50, 50, 50 );
	rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
	rollOverMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
	scene.add( rollOverMesh );

	//Add camera controls
	controls = new THREE.OrbitControls(camera, renderer.domElement );
	controls.addEventListener( 'change', render );

	//Cube drawing
	var geometry = new THREE.PlaneBufferGeometry( 1000, 1000 );
	geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
	plane = new THREE.Mesh( geometry );
	plane.visible = false;
	scene.add( plane );
	objects.push( plane );
	raycaster = new THREE.Raycaster();
	mouse = new THREE.Vector2();

	//GUI
	gui = new dat.GUI();
	text.Play = function() {
		running = true;
		animate();
		redrawGUI();
	};
	text.Pause = function() {
		running = false;
		redrawGUI();
	}
	text.Speed = 1;
	text.Clear = function() {
		for( var cell in cells ) {
			scene.remove(cells[cell]);
		}
		cells = [];
	}
	text.Survive = '2,3';
	text.Born = '3,6';
	text.Expansion3D = false;
	text.Painting3D = false;
	text.LimitedBox = true;
	f1 = gui.addFolder('Controls')
	item = f1.add(text, 'Play');
	f1.add(text, 'Speed', 1, 10);
	f1.add(text, 'Clear');
	f1.open();
	var f2 = gui.addFolder('Rules');
	ruleS = f2.add(text, 'Survive').onChange(function(newValue) {
		newValue= newValue.replace(/[^,\d]/g,"").replace(/,,/g,",");
		if(!running){
			sRule=[];
			sp = newValue.split(",");
			for( i in sp) {
				if(sp[i]!="") sRule.push(+sp[i]);
			}
		}
	});
	ruleB = f2.add(text, 'Born').onChange(function(newValue) {
		newValue= newValue.replace(/[^,\d]/g,"").replace(/,,/g,",");
		if(!running){
			bRule=[];
			sp = newValue.split(",");
			for( i in sp) {
				if(sp[i]!="") bRule.push(+sp[i]);
			}
		}
	});
	var f3 = gui.addFolder('Settings');
	f3.add(text, 'Expansion3D');
	f3.add(text, 'Painting3D');
	f3.add(text, 'LimitedBox');
	redrawGUI();

	document.addEventListener( 'mousedown', onDocumentMouseDown, false );
	document.addEventListener( 'mousemove', onDocumentMouseMove, false );
	window.addEventListener( 'resize', onWindowResize, false );
}

function redrawGUI() {
	f1.remove(item);
	if(running)
		item = f1.add(text, 'Pause');
	else
		item = f1.add(text, 'Play');
}

function generateIteration() {
	var newCells = {};
		for( var cell in cells ) {
			for(var i =-1; i<=1; i++){
				for(var k =-1; k<=1; k++){
					for(var j=-1; j<=1; j++){
						if(!text.Expansion3D && j!=0) continue;
						var x = cells[cell].position.x - 50*i;
						var y = cells[cell].position.y - 50*j;
						var z = cells[cell].position.z - 50*k;
						if(text.LimitedBox){
							if(x>500 || x<-475 ||
							y>1000 || y<0 ||
							z>500 || z<-475) continue;
						}
						if(newCells[[x,y,z]]!==undefined) {
							newCells[[x,y,z]] = [newCells[[x,y,z]][0] || (i==0 && j==0 && k==0), newCells[[x,y,z]][1]+1];
						} else {
							newCells[[x,y,z]] = [i==0 && j==0 && k==0, 1];
						}
						if(i==0 && j==0 && k==0) newCells[[x,y,z]][1]--;
						}
				}
			}
			scene.remove(cells[cell]);
		}
		objects=[plane];
		cells = [];
		for( var cell in newCells ){
			if(newCells[cell][0]){
				//Survive rule
				if(sRule.indexOf(newCells[cell][1])>-1){
					var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
					var pos = cell.split(',');
					voxel.position.set(pos[0],pos[1],pos[2]);
					cells.push(voxel);
					scene.add( voxel );
				}
			} else {
				//Born rule
				if(bRule.indexOf(newCells[cell][1])>-1){
					var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
					var pos = cell.split(',');
					voxel.position.set(pos[0],pos[1],pos[2]);
					cells.push(voxel);
					scene.add( voxel );
				}
			}
		}
}

function onWindowResize() {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );
	render();
}

function onDocumentMouseMove( event ) {

	mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
	raycaster.setFromCamera( mouse, camera );
	var intersects = raycaster.intersectObjects( objects );
	if ( intersects.length > 0 ) {
		var intersect = intersects[ 0 ];
		rollOverMesh.position.copy( intersect.point ).add( intersect.face.normal );
		rollOverMesh.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
	}
	render();

}
function onDocumentMouseDown( event ) {
	mouse.set( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1 );
	raycaster.setFromCamera( mouse, camera );
	var intersects = raycaster.intersectObjects( objects );
	if ( intersects.length > 0 ) {

		var intersect = intersects[ 0 ];
		if(event.which == 1){
			if ( !text.Painting3D && intersect.object != plane ) return;
			var voxel = new THREE.Mesh( cubeGeo, cubeMaterial );
			voxel.position.copy( intersect.point ).add( intersect.face.normal );
			voxel.position.divideScalar( 50 ).floor().multiplyScalar( 50 ).addScalar( 25 );
			scene.add( voxel );
			objects.push(voxel);
			cells.push(voxel);
		} else if(event.which == 3){
			if(intersect.object != plane)
				scene.remove(intersect.object);
		}
		render();
	}
}

function animate() {
	if(!running) return;
	setTimeout( function() {
        requestAnimationFrame( animate );
    }, 1000 / text.Speed );

	generateIteration(  );
	render();
}

function render() {
	renderer.render( scene, camera );
}
<|endoftext|>