<commit_before>var keys = require('./keys');

/**
 * Input wrapper
 * @constructor
 * @param {Game} game - Game object
 */
var Input = function(game) {
  /**
   * Pressed keys object
   * @type {object}
   */
  this.keys = {};

  /**
   * Controls if you can press keys
   * @type {boolean}
   */
  this.canControlKeys = true;

  /**
   * Mouse object with positions and if is mouse button pressed
   * @type {object}
   */
  this.mouse = {
    isDown: false,
    button: null,
    x: null,
    y: null
  };

  this._addEvents(game);
};

/**
 * Clears the pressed keys object
 */
Input.prototype.resetKeys = function() {
  this.keys = {};
};

/**
 * Return true or false if key is pressed
 * @param {string} key
 * @return {boolean}
 */
Input.prototype.isKeyDown = function(key) {
  if (this.canControlKeys) {
    return this.keys[keys[key.toUpperCase()]];
  }
};

/**
 * Add canvas event listener
 * @private
 */
Input.prototype._addEvents = function(game) {
  var self = this;
  var canvas = game.canvas;

  canvas.addEventListener('mousemove', function(e) {
    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    game.mousemove(x, y);
    self.mouse.x = x;
    self.mouse.y = y;
  });

  canvas.addEventListener('click', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    game.click(x, y, e.button);
  });

  canvas.addEventListener('mouseup', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    self.mouse.button = e.button;
    self.mouse.isDown = false;

    game.mouseup(x, y, e.button);
  }, false);

  canvas.addEventListener('mousedown', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.button = e.button;
    self.mouse.isDown = true;

    game.mousedown(x, y, e.button);
  }, false);

  var touchX = null;
  var touchY = null;

  canvas.addEventListener('touchstart', function(e) {
    var x = e.layerX;
    var y = e.layerY;

    touchX = x;
    touchY = y;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = true;
  });

  canvas.addEventListener('touchmove', function(e) {
    e.preventDefault();

    var x = e.layerX;
    var y = e.layerY;

    game.mousemove(x, y);

    self.mouse.x = x;
    self.mouse.y = y;
  });

  canvas.addEventListener('touchend', function(e) {
    e.preventDefault();

    self.mouse.isDown = false;

    for (var i=0, len=e.changedTouches.length; i<len; i++) {
      var touch = e.changedTouches[i];

      var x = touch.pageX - canvas.offsetLeft;
      var y = touch.pageY - canvas.offsetTop;
      var button = 0;

      var dx = Math.abs(touchX - x);
      var dy = Math.abs(touchY - y);

      var threshold = 5;

      if (dx < threshold && dy < threshold) {
        self.mouse.x = x;
        self.mouse.y = y;

        game.click(x, y, button);
      }
    }
  });

  canvas.addEventListener('contextmenu', function(e) {
    e.preventDefault();
  });

  document.addEventListener('keydown', function(e) {
    game.input.keys[e.keyCode] = true;
    game.keydown(e.which, e);
  });

  document.addEventListener('keyup', function(e) {
    game.input.keys[e.keyCode] = false;
    game.keyup(e.which, e);
  });

  if (game.keypress) {
    document.addEventListener('keypress', function(e) {
      game.keypress(e.which, e);
    });
  }
};

module.exports = Input;
<commit_msg>add option to pass keyCode to isKeyDown<commit_after>var keys = require('./keys');

/**
 * Input wrapper
 * @constructor
 * @param {Game} game - Game object
 */
var Input = function(game) {
  /**
   * Pressed keys object
   * @type {object}
   */
  this.keys = {};

  /**
   * Controls if you can press keys
   * @type {boolean}
   */
  this.canControlKeys = true;

  /**
   * Mouse object with positions and if is mouse button pressed
   * @type {object}
   */
  this.mouse = {
    isDown: false,
    button: null,
    x: null,
    y: null
  };

  this._addEvents(game);
};

/**
 * Clears the pressed keys object
 */
Input.prototype.resetKeys = function() {
  this.keys = {};
};

/**
 * Return true or false if key is pressed
 * @param {string} key
 * @return {boolean}
 */
Input.prototype.isKeyDown = function(key) {
  if (key == null) { return false; }

  if (this.canControlKeys) {
    var code = Number.isInteger(key) ? key : keys[key.toUpperCase()];
    return this.keys[code];
  }
};

/**
 * Add canvas event listener
 * @private
 */
Input.prototype._addEvents = function(game) {
  var self = this;
  var canvas = game.canvas;

  canvas.addEventListener('mousemove', function(e) {
    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    game.mousemove(x, y);
    self.mouse.x = x;
    self.mouse.y = y;
  });

  canvas.addEventListener('click', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    game.click(x, y, e.button);
  });

  canvas.addEventListener('mouseup', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    self.mouse.button = e.button;
    self.mouse.isDown = false;

    game.mouseup(x, y, e.button);
  }, false);

  canvas.addEventListener('mousedown', function(e) {
    e.preventDefault();

    var x = e.offsetX === undefined ? e.layerX - canvas.offsetLeft : e.offsetX;
    var y = e.offsetY === undefined ? e.layerY - canvas.offsetTop : e.offsetY;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.button = e.button;
    self.mouse.isDown = true;

    game.mousedown(x, y, e.button);
  }, false);

  var touchX = null;
  var touchY = null;

  canvas.addEventListener('touchstart', function(e) {
    var x = e.layerX;
    var y = e.layerY;

    touchX = x;
    touchY = y;

    self.mouse.x = x;
    self.mouse.y = y;
    self.mouse.isDown = true;
  });

  canvas.addEventListener('touchmove', function(e) {
    e.preventDefault();

    var x = e.layerX;
    var y = e.layerY;

    game.mousemove(x, y);

    self.mouse.x = x;
    self.mouse.y = y;
  });

  canvas.addEventListener('touchend', function(e) {
    e.preventDefault();

    self.mouse.isDown = false;

    for (var i=0, len=e.changedTouches.length; i<len; i++) {
      var touch = e.changedTouches[i];

      var x = touch.pageX - canvas.offsetLeft;
      var y = touch.pageY - canvas.offsetTop;
      var button = 0;

      var dx = Math.abs(touchX - x);
      var dy = Math.abs(touchY - y);

      var threshold = 5;

      if (dx < threshold && dy < threshold) {
        self.mouse.x = x;
        self.mouse.y = y;

        game.click(x, y, button);
      }
    }
  });

  canvas.addEventListener('contextmenu', function(e) {
    e.preventDefault();
  });

  document.addEventListener('keydown', function(e) {
    game.input.keys[e.keyCode] = true;
    game.keydown(e.which, e);
  });

  document.addEventListener('keyup', function(e) {
    game.input.keys[e.keyCode] = false;
    game.keyup(e.which, e);
  });

  if (game.keypress) {
    document.addEventListener('keypress', function(e) {
      game.keypress(e.which, e);
    });
  }
};

module.exports = Input;
<|endoftext|>


<commit_before>/**
 * Created by Sergey Sokurenko on 1/28/17.
 */

app = {};

$(document).ready(function () {

    // DOM Elements

    app.dom = {
        compareButton: $('button.compare'),
        starshipsTable: $('#starshipsTable')
    };

    // Event Listeners

    app.dom.compareButton.click(app.actions.compare);

});

// Actions

app.actions = {
    compare: function () {
        run(gen).catch(function (err) {
            alert(err.message);
        });
    }
};

function* gen() {
    var leftItem = $('#spaceships-left-input').val(),
        rightItem = $('#spaceships-right-input').val(),
        API = 'http://swapi.co/api/starships/';

    if (starships[leftItem] === undefined || starships[rightItem] === undefined) {
        alert('The starships do not exist. Please correct input data.')
    } else {
        const leftShipResponse = yield fetch(API + starships[leftItem]);
        const rightShipResponse = yield fetch(API + starships[rightItem]);

        const leftShipData = yield leftShipResponse.json();
        const rightShipData = yield rightShipResponse.json();

        updateStarships(leftShipData, rightShipData);
        compareAndHighlight(leftShipData, rightShipData);

    }
}

function updateStarships(leftShipData, rightShipData) {
    app.dom.starshipsTable.find('tbody').html(`

                    Name
                    ` + leftShipData.name + `
                    ` + rightShipData.name + `

                    Cost
                    ` + leftShipData.cost_in_credits + `
                    ` + rightShipData.cost_in_credits + `

                    Speed
                    ` + leftShipData.max_atmosphering_speed + `
                    ` + rightShipData.max_atmosphering_speed + `

                    Cargo
                    ` + leftShipData.cargo_capacity + `
                    ` + rightShipData.cargo_capacity + `

                    Passengers
                    ` + leftShipData.passengers + `
                    ` + rightShipData.passengers + `

`);
    console.log(leftShipData, rightShipData);
}

function compareAndHighlight(leftShipData, rightShipData) {
    compareValues(leftShipData.cost_in_credits, rightShipData.cost_in_credits, 'cost');
    compareValues(leftShipData.max_atmosphering_speed, rightShipData.max_atmosphering_speed, 'speed');
    compareValues(leftShipData.cargo_capacity, rightShipData.cargo_capacity, 'cargo');
    compareValues(leftShipData.passengers, rightShipData.passengers, 'passengers');
}

function compareValues (val1, val2, cssclass) {
    val1 = parseInt(val1);
    val2 = parseInt(val2);
    if (val1 > val2) {
        $('.' + cssclass + '-left').addClass('red');
    } else if (val2 > val1) {
        $('.' + cssclass + '-right').addClass('red');
    }
}

<commit_msg>Minor protocol update for the API request to allow secure calls from https environments<commit_after>/**
 * Created by Sergey Sokurenko on 1/28/17.
 */

app = {};

$(document).ready(function () {

    // DOM Elements

    app.dom = {
        compareButton: $('button.compare'),
        starshipsTable: $('#starshipsTable')
    };

    // Event Listeners

    app.dom.compareButton.click(app.actions.compare);

});

// Actions

app.actions = {
    compare: function () {
        run(gen).catch(function (err) {
            alert(err.message);
        });
    }
};

function* gen() {
    var leftItem = $('#spaceships-left-input').val(),
        rightItem = $('#spaceships-right-input').val(),
        API = 'https://swapi.co/api/starships/';

    if (starships[leftItem] === undefined || starships[rightItem] === undefined) {
        alert('The starships do not exist. Please correct input data.')
    } else {
        const leftShipResponse = yield fetch(API + starships[leftItem]);
        const rightShipResponse = yield fetch(API + starships[rightItem]);

        const leftShipData = yield leftShipResponse.json();
        const rightShipData = yield rightShipResponse.json();

        updateStarships(leftShipData, rightShipData);
        compareAndHighlight(leftShipData, rightShipData);

    }
}

function updateStarships(leftShipData, rightShipData) {
    app.dom.starshipsTable.find('tbody').html(`

                    Name
                    ` + leftShipData.name + `
                    ` + rightShipData.name + `

                    Cost
                    ` + leftShipData.cost_in_credits + `
                    ` + rightShipData.cost_in_credits + `

                    Speed
                    ` + leftShipData.max_atmosphering_speed + `
                    ` + rightShipData.max_atmosphering_speed + `

                    Cargo
                    ` + leftShipData.cargo_capacity + `
                    ` + rightShipData.cargo_capacity + `

                    Passengers
                    ` + leftShipData.passengers + `
                    ` + rightShipData.passengers + `

`);
    console.log(leftShipData, rightShipData);
}

function compareAndHighlight(leftShipData, rightShipData) {
    compareValues(leftShipData.cost_in_credits, rightShipData.cost_in_credits, 'cost');
    compareValues(leftShipData.max_atmosphering_speed, rightShipData.max_atmosphering_speed, 'speed');
    compareValues(leftShipData.cargo_capacity, rightShipData.cargo_capacity, 'cargo');
    compareValues(leftShipData.passengers, rightShipData.passengers, 'passengers');
}

function compareValues (val1, val2, cssclass) {
    val1 = parseInt(val1);
    val2 = parseInt(val2);
    if (val1 > val2) {
        $('.' + cssclass + '-left').addClass('red');
    } else if (val2 > val1) {
        $('.' + cssclass + '-right').addClass('red');
    }
}

<|endoftext|>


<commit_before>'use strict';

module.exports = {
  init(sceneId) {
    this.sceneId = sceneId;
  },

  create() {
    this.addUIElements();
    this.enableInteraction();
  },

  addUIElements() {
    const sprite = this.add.sprite(
      this.camera.view.width / 2, this.camera.view.height / 2, 'menu-back'
    );

    sprite.anchor.set(0.5);

    const titleStyle = {
      font:            'Raleway',
      fontSize:        88,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };
    const defaultStyle = {
      font:            'Raleway',
      fontSize:        48,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };

    this.title = this.add.text(
      this.camera.view.width / 2, titleStyle.fontSize, 'To The End', titleStyle
    );
    this.title.anchor.set(0.5);

    this.playText = this.add.text(
      this.camera.view.centerX, this.camera.view.centerY,
      'Play', defaultStyle
    );
    this.playText.anchor.set(0.5);

    this.instructionsText = this.add.text(
      this.playText.x, this.playText.y + 80,
      'Instructions', defaultStyle
    );
    this.instructionsText.anchor.set(0.5);

    this.creditsText = this.add.text(
      this.instructionsText.x, this.instructionsText.y + 80,
      'Credits', defaultStyle
    );
    this.creditsText.anchor.set(0.5);
  },

  enableInteraction() {
    this.playText.inputEnabled = true;
    this.playText.events.onInputUp.add(() => {
      this.state.start('scene', true, false, this.sceneId);
    });

    this.instructionsText.inputEnabled = true;
    this.instructionsText.events.onInputUp.add(() => {
      this.showInstructions();
    });

    this.creditsText.inputEnabled = true;
    this.creditsText.events.onInputUp.add(() => {
      this.showCredits();
    });
  },

  showInstructions() {
    this.playText.kill();
    this.instructionsText.kill();
    this.creditsText.kill();

    const instructionsStyle = {
      font:            'Raleway',
      fontSize:        48,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };
    const commandsStyle = {
      font:            'Raleway',
      fontSize:        30,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };

    const saviour = this.add.text(
      this.camera.view.width * 2 / 10, this.camera.view.height * 3 / 10, 'Saviour', instructionsStyle
    );

    saviour.anchor.set(0.5);

    const protector = this.add.text(
      this.camera.view.width - saviour.x, saviour.y, 'Protector', instructionsStyle
    );

    protector.anchor.set(0.5);

    const saviourCommands1 = this.add.text(
      saviour.x, saviour.y + 100, 'Arrow keys', commandsStyle
    );

    saviourCommands1.anchor.set(0.5);

    const saviourCommands2 = this.add.text(
      saviourCommands1.x, saviourCommands1.y + 80, 'Spacebar', commandsStyle
    );

    saviourCommands2.anchor.set(0.5);

    const protectorCommands1 = this.add.text(
      protector.x, protector.y + 100, 'Mouse', commandsStyle
    );

    protectorCommands1.anchor.set(0.5);

    this.input.onDown.add(function returnToMain() {
      saviour.destroy();
      protector.destroy();
      saviourCommands1.destroy();
      saviourCommands2.destroy();
      protectorCommands1.destroy();
      this.playText.revive();
      this.instructionsText.revive();
      this.creditsText.revive();
      this.input.onDown.removeAll();
    }, this);
  },

  showCredits() {
    this.playText.kill();
    this.instructionsText.kill();
    this.creditsText.kill();

    const style = {
      font:            'Raleway',
      fontSize:        28,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
      align:           'center',
    };

    const thanksStyle = {
      font:            'Raleway',
      fontSize:        24,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
      align:           'center',
    };

    const ggj = this.add.text(
      this.camera.view.centerX, 200, 'Made for Global Game Jam 2016', style
    );

    ggj.anchor.set(0.5, 0);

    const antonio = this.add.text(
      this.camera.view.centerX, ggj.y + 100,
      'Antonio La Barbera - Art', style
    );

    antonio.anchor.set(0.5, 0);

    const endrit = this.add.text(
      this.camera.view.centerX, antonio.y + 38,
      'Endrit Bajo - Code', style
    );

    endrit.anchor.set(0.5, 0);

    const felix = this.add.text(
      this.camera.view.centerX, endrit.y + 38,
      'Felix Laurie von Massenbach - Code', style
    );

    felix.anchor.set(0.5, 0);

    const michael = this.add.text(
      this.camera.view.centerX, felix.y + 38,
      'Michael Le - Code', style
    );

    michael.anchor.set(0.5, 0);

    const archil = this.add.text(
      this.camera.view.centerX, michael.y + 38,
      'Archil Tsiskaridze - Code', style
    );

    archil.anchor.set(0.5, 0);

    const sam = this.add.text(
      this.camera.view.centerX, archil.y + 38,
      'Zhaoqian Yu - Code', style
    );

    sam.anchor.set(0.5, 0);

    const duncan = this.add.text(
      this.camera.view.centerX, sam.y + 38,
      'Duncan McKenna - Narrative', style
    );

    duncan.anchor.set(0.5, 0);

    const dave = this.add.text(
      this.camera.view.centerX, duncan.y + 38,
      'Dave Allen - Sound', style
    );

    dave.anchor.set(0.5, 0);

    const thanks = this.add.text(
      this.camera.view.centerX, dave.y + 100,
      'Source images from:\n\nChristophe Verdier\nMarLeah Cole\nPepe Free Hair',
      thanksStyle
    );

    thanks.anchor.set(0.5, 0);

    this.input.onDown.add(function returnToMain() {
      ggj.destroy();
      antonio.destroy();
      endrit.destroy();
      felix.destroy();
      michael.destroy();
      archil.destroy();
      sam.destroy();
      duncan.destroy();
      dave.destroy();
      thanks.destroy();

      this.playText.revive();
      this.instructionsText.revive();
      this.creditsText.revive();

      this.input.onDown.removeAll();
    }, this);
  },
};
<commit_msg>Change name<commit_after>'use strict';

module.exports = {
  init(sceneId) {
    this.sceneId = sceneId;
  },

  create() {
    this.addUIElements();
    this.enableInteraction();
  },

  addUIElements() {
    const sprite = this.add.sprite(
      this.camera.view.width / 2, this.camera.view.height / 2, 'menu-back'
    );

    sprite.anchor.set(0.5);

    const titleStyle = {
      font:            'Raleway',
      fontSize:        88,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };
    const defaultStyle = {
      font:            'Raleway',
      fontSize:        48,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };

    this.title = this.add.text(
      this.camera.view.width / 2, titleStyle.fontSize, 'To The End', titleStyle
    );
    this.title.anchor.set(0.5);

    this.playText = this.add.text(
      this.camera.view.centerX, this.camera.view.centerY,
      'Play', defaultStyle
    );
    this.playText.anchor.set(0.5);

    this.instructionsText = this.add.text(
      this.playText.x, this.playText.y + 80,
      'Instructions', defaultStyle
    );
    this.instructionsText.anchor.set(0.5);

    this.creditsText = this.add.text(
      this.instructionsText.x, this.instructionsText.y + 80,
      'Credits', defaultStyle
    );
    this.creditsText.anchor.set(0.5);
  },

  enableInteraction() {
    this.playText.inputEnabled = true;
    this.playText.events.onInputUp.add(() => {
      this.state.start('scene', true, false, this.sceneId);
    });

    this.instructionsText.inputEnabled = true;
    this.instructionsText.events.onInputUp.add(() => {
      this.showInstructions();
    });

    this.creditsText.inputEnabled = true;
    this.creditsText.events.onInputUp.add(() => {
      this.showCredits();
    });
  },

  showInstructions() {
    this.playText.kill();
    this.instructionsText.kill();
    this.creditsText.kill();

    const instructionsStyle = {
      font:            'Raleway',
      fontSize:        48,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };
    const commandsStyle = {
      font:            'Raleway',
      fontSize:        30,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
    };

    const saviour = this.add.text(
      this.camera.view.width * 2 / 10, this.camera.view.height * 3 / 10, 'Saviour', instructionsStyle
    );

    saviour.anchor.set(0.5);

    const protector = this.add.text(
      this.camera.view.width - saviour.x, saviour.y, 'Protector', instructionsStyle
    );

    protector.anchor.set(0.5);

    const saviourCommands1 = this.add.text(
      saviour.x, saviour.y + 100, 'Arrow keys', commandsStyle
    );

    saviourCommands1.anchor.set(0.5);

    const saviourCommands2 = this.add.text(
      saviourCommands1.x, saviourCommands1.y + 80, 'Spacebar', commandsStyle
    );

    saviourCommands2.anchor.set(0.5);

    const protectorCommands1 = this.add.text(
      protector.x, protector.y + 100, 'Mouse', commandsStyle
    );

    protectorCommands1.anchor.set(0.5);

    this.input.onDown.add(function returnToMain() {
      saviour.destroy();
      protector.destroy();
      saviourCommands1.destroy();
      saviourCommands2.destroy();
      protectorCommands1.destroy();
      this.playText.revive();
      this.instructionsText.revive();
      this.creditsText.revive();
      this.input.onDown.removeAll();
    }, this);
  },

  showCredits() {
    this.playText.kill();
    this.instructionsText.kill();
    this.creditsText.kill();

    const style = {
      font:            'Raleway',
      fontSize:        28,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
      align:           'center',
    };

    const thanksStyle = {
      font:            'Raleway',
      fontSize:        24,
      fill:            '#fff',
      stroke:          '#000',
      strokeThickness: 3,
      align:           'center',
    };

    const ggj = this.add.text(
      this.camera.view.centerX, 200, 'Made for Global Game Jam 2016', style
    );

    ggj.anchor.set(0.5, 0);

    const antonio = this.add.text(
      this.camera.view.centerX, ggj.y + 100,
      'Antonio La Barbera - Art', style
    );

    antonio.anchor.set(0.5, 0);

    const endrit = this.add.text(
      this.camera.view.centerX, antonio.y + 38,
      'Endrit Bajo - Code', style
    );

    endrit.anchor.set(0.5, 0);

    const erbridge = this.add.text(
      this.camera.view.centerX, endrit.y + 38,
      'erbridge - Code', style
    );

    erbridge.anchor.set(0.5, 0);

    const michael = this.add.text(
      this.camera.view.centerX, erbridge.y + 38,
      'Michael Le - Code', style
    );

    michael.anchor.set(0.5, 0);

    const archil = this.add.text(
      this.camera.view.centerX, michael.y + 38,
      'Archil Tsiskaridze - Code', style
    );

    archil.anchor.set(0.5, 0);

    const sam = this.add.text(
      this.camera.view.centerX, archil.y + 38,
      'Zhaoqian Yu - Code', style
    );

    sam.anchor.set(0.5, 0);

    const duncan = this.add.text(
      this.camera.view.centerX, sam.y + 38,
      'Duncan McKenna - Narrative', style
    );

    duncan.anchor.set(0.5, 0);

    const dave = this.add.text(
      this.camera.view.centerX, duncan.y + 38,
      'Dave Allen - Sound', style
    );

    dave.anchor.set(0.5, 0);

    const thanks = this.add.text(
      this.camera.view.centerX, dave.y + 100,
      'Source images from:\n\nChristophe Verdier\nMarLeah Cole\nPepe Free Hair',
      thanksStyle
    );

    thanks.anchor.set(0.5, 0);

    this.input.onDown.add(function returnToMain() {
      ggj.destroy();
      antonio.destroy();
      endrit.destroy();
      erbridge.destroy();
      michael.destroy();
      archil.destroy();
      sam.destroy();
      duncan.destroy();
      dave.destroy();
      thanks.destroy();

      this.playText.revive();
      this.instructionsText.revive();
      this.creditsText.revive();

      this.input.onDown.removeAll();
    }, this);
  },
};
<|endoftext|>


<commit_before>var AmatYr = function(apiurl) {
    this.apiurl = apiurl;
    this.current_weather;
    this.windroseData;
    this.that = this;
    that = this;
    currentsource = false;
    // array of all sparklines, used for updating them dynamically
    var sparklines = [];

    /* Initial and on resize we draw draw draw */
    on_resize(function() {
        // Redraw graphs
        draw(currentsource);
        // Redraw sparklines
        for(key in sparklines) {
            sparklines[key].redrawWithAnimation();
        }
    }); // these parenthesis does the trick

    // debulked onresize handler
    function on_resize(c,t){onresize=function(){clearTimeout(t);t=setTimeout(c,300)};return c};

    // Fetch current weather
    d3.json(apiurl + 'now', function(json) {
        current_weather = {
            current: json[0]
        };
        rivets.bind(document.getElementById('current_weather'), current_weather);
    });

    /****
     *
     *
     * WIND ROSE SECTION
     *
     *
     */
    var drawWindrose = function(startarg) {
        if (this.windroseData == undefined) {
            // Get all the wind history and draw two wind roses
            d3.json('/api/windhist?start='+startarg, function(data) {
                this.windroseData = data;
                windrose.drawBigWindrose(data, "#windrose", "Frequency by Direction");
                windrose.drawBigWindrose(data, "#windroseavg", "Average Speed by Direction");
            });
        }else{ // update existing with new data
            d3.json('/api/windhist?start='+startarg, function(data) {
                this.windroseData = data;
                windrose.updateWindVisDiagrams(data);
            })
        }
    }
    // Create windroses
    windrose = new WindRose();

    var initPath = function() {
        // Register HTML5 push state handler for navbar links
        $("#main_nav a").bind("click", function(event){
            event.preventDefault();
            // Fix active link
            $('.navbar li.active').removeClass('active');
            $(this).closest('li').addClass('active');

            // Call path state to handle the clicked link
            Path.history.pushState({}, "", $(this).attr("href"));
        });

        Path.map("/year/:year").to(function(){
            var year = this.params['year'];
            var yearurl = apiurl + 'year/' + year;
            // Fetch data for this year
            d3.json(yearurl, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(year);
        });
        Path.map("/day/:day").to(function(){
            var day = this.params['day'];
            var url = apiurl + 'day/' + day;
            // Fetch data for this year
            d3.json(url+'?start='+day, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(day);
        });
        Path.map("/hour/:arg").to(function(){
            var arg = this.params['arg'];
            var url = apiurl + 'hour/' + arg;
            // Fetch data for this year
            d3.json(url+'?start='+arg, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(arg);
        });
        Path.map("/").to(function(){
            var width = $('#main').css('width').split('px')[0];
            d3.json(apiurl+'hour?start=3day', function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose('3DAY');
        });

        // Start listening for URL events
        Path.history.listen(true);  // Yes, please fall back to hashtags if HTML5 is not supported.

        // Initial fetch and draw
        Path.history.pushState({}, "", window.location.pathname);
        // Fix initial active link in case user got direct link and not started at /
        $('#main_nav a[href="'+window.location.pathname+'"]').closest('li').addClass('active');
    }
    initPath();

    // Fetch current weather with 1 minute interval
    setInterval(function() { d3.json(apiurl + 'now', function(json) {
        // Update each key with new val
        for(key in current_weather.current) {
            current_weather.current[key] = json[0][key]
        }
    }) }, 60*1000);

    // Draw sparkline
    d3.json(apiurl+'recent', function(json) {
        var tdata = [];
        var wdata = [];
        var pdata = [];
        json.forEach(function(k, v) {
            // Ordered wrong way, so unshift
            tdata.unshift(k.outtemp);
            wdata.unshift(k.windspeed);
            pdata.unshift(k.barometer);
        });
        sparklines.push(new sparkline('#sparkline', tdata, 'outtemp', tdata.length, 38, 'basis', true, 1000));
        sparklines.push(new sparkline('#windsparkline', wdata, 'windspeed', wdata.length, 38, 'basis', true, 1000));
        sparklines.push(new sparkline('#pressuresparkline', pdata, 'barometer', pdata.length, 38, 'basis', true, 1000));
        for(key in sparklines) {
            // Update each minute
            setInterval(sparklines[key].update, 60*1000);
        }
    });

    /****
     *
     *
     * RECORD WEATHER SECTION
     *
     *
     * */

    // Init the data structure to be used by records and rivets
    var record_weather = {current:{}};

    // Fetch record weather
    var updateRecordsYear = function(year) {
        var keys = ['max', 'min'];
        var vals = ['outtemp', 'windspeed', 'dayrain', 'barometer', 'windgust', 'heatindex', 'windchill'];
        vals.forEach(function(k, v) {
            keys.forEach(function(func, idx) {
                // set key for rivets to set up proper setters and getters
                record_weather.current[func+k+'date'] = '';
                record_weather.current[func+k+'value'] = '';
                record_weather.current[func+k+'age'] = '';
                /// XXX needs a black list for certain types that doesn't make sense
                // like min daily_rain or min windspeed
                d3.json(apiurl + 'record/'+k+'/'+func+'?start='+year, function(json) {
                    if (json) {
                        record_weather.current[func+k+'date'] = json[0].datetime;
                        record_weather.current[func+k+'value'] = json[0][k];
                        record_weather.current[func+k+'age'] = json[0].age;
                    }
                });
            })
        });
        // Additional entries
        var k = 'rain',
            func = 'sum';
        d3.json(apiurl + 'record/'+k+'/'+func+'?start='+year, function(json) {
            record_weather.current[func+k+'value'] = json[0][k];
        });
    }
    // initial structure for rivets to work
    updateRecordsYear('today');
    //rivets.bind(document.getElementById('r2013'), record_weather);

    // Populate all the tab content with the tab template
    d3.selectAll('#record_weather .tab-pane').forEach(function (tab) {
       $(tab).html($('#record_table_template').html());
    });
    // Bind rivets after both elemend and var is available and populated
    rivets.bind(document.getElementById('record_weather'), record_weather);

    // Bind the tab clicks to fetching new content
    $('#record_weather .nav-tabs a').bind('click', function(e) {
        e.preventDefault();

        // Find target container
        var tab = $($(this).attr('href'));

        // Get the year clicked
        var year = $(this).text();
        // Fetch new data from db
        updateRecordsYear(year);

        // Show tab
        $(this).tab('show');

    });

    /* Calendar generation */
    var updateCalender = function() {
        // TODO dynamic
        var width = $('#main').css('width').split('px')[0];
        d3.json(apiurl + 'year/2013', function(json) {
            //drawcalender('#heat_calender', json, width);
            var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

            // Add d3 js date for each datum
            json.forEach(function(d) {
                d.date = ""+(+parseDate(d.datetime))/1000;
            });

            // Format data to how calheatmap likes it
            var data = d3.nest()
              .key(function(d) { return d.date; })
              .rollup(function(d) { return d[0].dayrain; })
              .map(json);
            var cal = new CalHeatMap();

            // Remove spinner
            $('#cal-heatmap .spinner').remove();
            // Draw calendar
            cal.init({
                data: data,
                start: new Date(2013,1), // TODO year selector
                end: new Date(),
                itemSelector : "#cal-heatmap",
                domain : "month",       // Group data by month
                subDomain : "day",      // Split each month by days
                range : new Date().getMonth(),  // Only display up to current month
                highlight: "now",
                cellRadius : 2,
                itemName: ['mm', 'mm'],
                weekStartOnMonday: true,
                scale: [1, 4, 6, 8]    // Custom threshold for the scale
            });

            updateTabularData(json);

        });

    };
    updateCalender();

    var updateTabularData = function(data) {
        // Remove spinner
        $('#tabular .spinner').remove();

        var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

        // Add d3 js date for each datum
        data.forEach(function(d) {
            d.date = parseDate(d.datetime);
        });

        // Group data by month
        var monthdata = d3.nest()
          .key(function(d) { return d.date.getMonth(); })
          .map(data);

        var aggdata =  d3.nest()
          .key(function(d) { return d.date.getMonth(); })
          .sortKeys(d3.ascending)
          .rollup(function(d) {
            return {
                barometer: d3.mean(d, function(g) { return +g.barometer }),
                windspeed: d3.mean(d, function(g) { return +g.windspeed }),
                outtemp: d3.mean(d, function(g) { return +g.outtemp }),
                tempmax: d3.max(d, function(g) { return +g.tempmax }),
                tempmin: d3.min(d, function(g) { return +g.tempmin }),
                dayrain: d3.sum(d, function(g) { return +g.dayrain }),
                date: d3.min(d, function(g) { return +g.date })
            }
          })
          .entries(data)
          .sort(function(a,b) { return parseInt(a.key,10)>parseInt(b.key) });

          window.aggdata = aggdata;

        var columns = ['datetime', 'dayrain', 'outtemp', 'windspeed', 'winddir'];
        // Create a collapsible group for each month
        aggdata.forEach(function (agg, i) {
            console.log(agg, agg.values, agg.values.outtemp);
            var month = agg.key,
                values = agg.values,
                monthname = d3.time.format('%Y %B')(new Date(values.date)),
                header = monthname,
                headertext =
                    ' Rain: ' + amatyrlib.autoformat('dayrain', values.dayrain) +
                    ' Avg Temp: ' + amatyrlib.autoformat('outtemp', values.outtemp) +
                    ' Min Temp: ' + amatyrlib.autoformat('outtemp', values.tempmin) +
                    ' Max Temp: ' + amatyrlib.autoformat('outtemp', values.tempmax) +
                    ' Avg Wind: ' + amatyrlib.autoformat('windspeed', values.windspeed) +
                    ' Avg Pressure:' + amatyrlib.autoformat('barometer', values.barometer)
                ,
                panel = d3.select('#accordion').append('div')
                .classed('panel', true),
            heading = panel.append('div')
                .classed('panel-heading', true),
            h4 = heading.append('h4')
                .html(''+header+''+headertext+''),
            collapse = panel.append('div')
                .attr('id', 'collapse-'+i)
                .classed('panel-collapse collapse', true),
            body = collapse.append('div')
                .classed('panel-body', true),
            table = body.append('table')
                .classed('table table-condensed', true),
            thead = table.append("thead"),
            tbody = table.append("tbody");

            // append the header row
            thead.append("tr")
                .selectAll("th")
                .data(columns)
                .enter()
                .append("th")
                .text(function(column) { return column; });

            // create a row for each object in the data
            var rows = tbody.selectAll("tr")
                .data(monthdata[month])
                .enter()
                .append("tr");

            // create a cell in each row for each column
            var cells = rows.selectAll("td")
                .data(function(row) {
                    return columns.map(function(column) {
                        return {column: column, value: row[column]};
                    });
                })
            .enter()
                .append("td")
                .attr("style", "font-family: monospace")
                .html(function(d) { return amatyrlib.autoformat(d.column, d.value); });
        });
    }

    // Auto update webcam
    setInterval(function () {
      var imgElem = document.getElementById("webcam");
      var newImg = new Image();
      newImg.src = imgElem.src.split("?")[0] + "?" + new Date().getTime();
      newImg.addEventListener("load", function (evt) {
        imgElem.src = newImg.src;
      });
    }, 30000);

    return this;
}
var amatyrlib = new amatyrlib();
var amatyr = new AmatYr('/api/');
<commit_msg>Use max wind gust instead of barometer<commit_after>var AmatYr = function(apiurl) {
    this.apiurl = apiurl;
    this.current_weather;
    this.windroseData;
    this.that = this;
    that = this;
    currentsource = false;
    // array of all sparklines, used for updating them dynamically
    var sparklines = [];

    /* Initial and on resize we draw draw draw */
    on_resize(function() {
        // Redraw graphs
        draw(currentsource);
        // Redraw sparklines
        for(key in sparklines) {
            sparklines[key].redrawWithAnimation();
        }
    }); // these parenthesis does the trick

    // debulked onresize handler
    function on_resize(c,t){onresize=function(){clearTimeout(t);t=setTimeout(c,300)};return c};

    // Fetch current weather
    d3.json(apiurl + 'now', function(json) {
        current_weather = {
            current: json[0]
        };
        rivets.bind(document.getElementById('current_weather'), current_weather);
    });

    /****
     *
     *
     * WIND ROSE SECTION
     *
     *
     */
    var drawWindrose = function(startarg) {
        if (this.windroseData == undefined) {
            // Get all the wind history and draw two wind roses
            d3.json('/api/windhist?start='+startarg, function(data) {
                this.windroseData = data;
                windrose.drawBigWindrose(data, "#windrose", "Frequency by Direction");
                windrose.drawBigWindrose(data, "#windroseavg", "Average Speed by Direction");
            });
        }else{ // update existing with new data
            d3.json('/api/windhist?start='+startarg, function(data) {
                this.windroseData = data;
                windrose.updateWindVisDiagrams(data);
            })
        }
    }
    // Create windroses
    windrose = new WindRose();

    var initPath = function() {
        // Register HTML5 push state handler for navbar links
        $("#main_nav a").bind("click", function(event){
            event.preventDefault();
            // Fix active link
            $('.navbar li.active').removeClass('active');
            $(this).closest('li').addClass('active');

            // Call path state to handle the clicked link
            Path.history.pushState({}, "", $(this).attr("href"));
        });

        Path.map("/year/:year").to(function(){
            var year = this.params['year'];
            var yearurl = apiurl + 'year/' + year;
            // Fetch data for this year
            d3.json(yearurl, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(year);
        });
        Path.map("/day/:day").to(function(){
            var day = this.params['day'];
            var url = apiurl + 'day/' + day;
            // Fetch data for this year
            d3.json(url+'?start='+day, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(day);
        });
        Path.map("/hour/:arg").to(function(){
            var arg = this.params['arg'];
            var url = apiurl + 'hour/' + arg;
            // Fetch data for this year
            d3.json(url+'?start='+arg, function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose(arg);
        });
        Path.map("/").to(function(){
            var width = $('#main').css('width').split('px')[0];
            d3.json(apiurl+'hour?start=3day', function(json) {
                // Save to global for redrawing
                currentsource = json;
                draw(json);
            });
            drawWindrose('3DAY');
        });

        // Start listening for URL events
        Path.history.listen(true);  // Yes, please fall back to hashtags if HTML5 is not supported.

        // Initial fetch and draw
        Path.history.pushState({}, "", window.location.pathname);
        // Fix initial active link in case user got direct link and not started at /
        $('#main_nav a[href="'+window.location.pathname+'"]').closest('li').addClass('active');
    }
    initPath();

    // Fetch current weather with 1 minute interval
    setInterval(function() { d3.json(apiurl + 'now', function(json) {
        // Update each key with new val
        for(key in current_weather.current) {
            current_weather.current[key] = json[0][key]
        }
    }) }, 60*1000);

    // Draw sparkline
    d3.json(apiurl+'recent', function(json) {
        var tdata = [];
        var wdata = [];
        var pdata = [];
        json.forEach(function(k, v) {
            // Ordered wrong way, so unshift
            tdata.unshift(k.outtemp);
            wdata.unshift(k.windspeed);
            pdata.unshift(k.barometer);
        });
        sparklines.push(new sparkline('#sparkline', tdata, 'outtemp', tdata.length, 38, 'basis', true, 1000));
        sparklines.push(new sparkline('#windsparkline', wdata, 'windspeed', wdata.length, 38, 'basis', true, 1000));
        sparklines.push(new sparkline('#pressuresparkline', pdata, 'barometer', pdata.length, 38, 'basis', true, 1000));
        for(key in sparklines) {
            // Update each minute
            setInterval(sparklines[key].update, 60*1000);
        }
    });

    /****
     *
     *
     * RECORD WEATHER SECTION
     *
     *
     * */

    // Init the data structure to be used by records and rivets
    var record_weather = {current:{}};

    // Fetch record weather
    var updateRecordsYear = function(year) {
        var keys = ['max', 'min'];
        var vals = ['outtemp', 'windspeed', 'dayrain', 'barometer', 'windgust', 'heatindex', 'windchill'];
        vals.forEach(function(k, v) {
            keys.forEach(function(func, idx) {
                // set key for rivets to set up proper setters and getters
                record_weather.current[func+k+'date'] = '';
                record_weather.current[func+k+'value'] = '';
                record_weather.current[func+k+'age'] = '';
                /// XXX needs a black list for certain types that doesn't make sense
                // like min daily_rain or min windspeed
                d3.json(apiurl + 'record/'+k+'/'+func+'?start='+year, function(json) {
                    if (json) {
                        record_weather.current[func+k+'date'] = json[0].datetime;
                        record_weather.current[func+k+'value'] = json[0][k];
                        record_weather.current[func+k+'age'] = json[0].age;
                    }
                });
            })
        });
        // Additional entries
        var k = 'rain',
            func = 'sum';
        d3.json(apiurl + 'record/'+k+'/'+func+'?start='+year, function(json) {
            record_weather.current[func+k+'value'] = json[0][k];
        });
    }
    // initial structure for rivets to work
    updateRecordsYear('today');
    //rivets.bind(document.getElementById('r2013'), record_weather);

    // Populate all the tab content with the tab template
    d3.selectAll('#record_weather .tab-pane').forEach(function (tab) {
       $(tab).html($('#record_table_template').html());
    });
    // Bind rivets after both elemend and var is available and populated
    rivets.bind(document.getElementById('record_weather'), record_weather);

    // Bind the tab clicks to fetching new content
    $('#record_weather .nav-tabs a').bind('click', function(e) {
        e.preventDefault();

        // Find target container
        var tab = $($(this).attr('href'));

        // Get the year clicked
        var year = $(this).text();
        // Fetch new data from db
        updateRecordsYear(year);

        // Show tab
        $(this).tab('show');

    });

    /* Calendar generation */
    var updateCalender = function() {
        // TODO dynamic
        var width = $('#main').css('width').split('px')[0];
        d3.json(apiurl + 'year/2013', function(json) {
            //drawcalender('#heat_calender', json, width);
            var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

            // Add d3 js date for each datum
            json.forEach(function(d) {
                d.date = ""+(+parseDate(d.datetime))/1000;
            });

            // Format data to how calheatmap likes it
            var data = d3.nest()
              .key(function(d) { return d.date; })
              .rollup(function(d) { return d[0].dayrain; })
              .map(json);
            var cal = new CalHeatMap();

            // Remove spinner
            $('#cal-heatmap .spinner').remove();
            // Draw calendar
            cal.init({
                data: data,
                start: new Date(2013,1), // TODO year selector
                end: new Date(),
                itemSelector : "#cal-heatmap",
                domain : "month",       // Group data by month
                subDomain : "day",      // Split each month by days
                range : new Date().getMonth(),  // Only display up to current month
                highlight: "now",
                cellRadius : 2,
                itemName: ['mm', 'mm'],
                weekStartOnMonday: true,
                scale: [1, 4, 6, 8]    // Custom threshold for the scale
            });

            updateTabularData(json);

        });

    };
    updateCalender();

    var updateTabularData = function(data) {
        // Remove spinner
        $('#tabular .spinner').remove();

        var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;

        // Add d3 js date for each datum
        data.forEach(function(d) {
            d.date = parseDate(d.datetime);
        });

        // Group data by month
        var monthdata = d3.nest()
          .key(function(d) { return d.date.getMonth(); })
          .map(data);

        var aggdata =  d3.nest()
          .key(function(d) { return d.date.getMonth(); })
          .sortKeys(d3.ascending)
          .rollup(function(d) {
            return {
                barometer: d3.mean(d, function(g) { return +g.barometer }),
                windspeed: d3.mean(d, function(g) { return +g.windspeed }),
                windgustmax: d3.max(d, function(g) { return +g.windgust}),
                outtemp: d3.mean(d, function(g) { return +g.outtemp }),
                tempmax: d3.max(d, function(g) { return +g.tempmax }),
                tempmin: d3.min(d, function(g) { return +g.tempmin }),
                dayrain: d3.sum(d, function(g) { return +g.dayrain }),
                date: d3.min(d, function(g) { return +g.date })
            }
          })
          .entries(data)
          .sort(function(a,b) { return parseInt(a.key,10)>parseInt(b.key) });

          window.aggdata = aggdata;

        var columns = ['datetime', 'dayrain', 'outtemp', 'windspeed', 'winddir'];
        // Create a collapsible group for each month
        aggdata.forEach(function (agg, i) {
            console.log(agg, agg.values, agg.values.outtemp);
            var month = agg.key,
                values = agg.values,
                monthname = d3.time.format('%Y %B')(new Date(values.date)),
                header = monthname,
                headertext =
                    ' Rain: ' + amatyrlib.autoformat('dayrain', values.dayrain) + '' +
                    ' Avg Temp: ' + amatyrlib.autoformat('outtemp', values.outtemp) +
                    ' Min Temp: ' + amatyrlib.autoformat('outtemp', values.tempmin) +
                    ' Max Temp: ' + amatyrlib.autoformat('outtemp', values.tempmax) +
                    ' Avg Wind: ' + amatyrlib.autoformat('windspeed', values.windspeed) +
                    ' Max Windgust: ' + amatyrlib.autoformat('windspeed', values.windgustmax)
                ,
                panel = d3.select('#accordion').append('div')
                .classed('panel', true),
            heading = panel.append('div')
                .classed('panel-heading', true),
            h4 = heading.append('h4')
                .html(''+header+''+headertext+''),
            collapse = panel.append('div')
                .attr('id', 'collapse-'+i)
                .classed('panel-collapse collapse', true),
            body = collapse.append('div')
                .classed('panel-body', true),
            table = body.append('table')
                .classed('table table-condensed', true),
            thead = table.append("thead"),
            tbody = table.append("tbody");

            // append the header row
            thead.append("tr")
                .selectAll("th")
                .data(columns)
                .enter()
                .append("th")
                .text(function(column) { return column; });

            // create a row for each object in the data
            var rows = tbody.selectAll("tr")
                .data(monthdata[month])
                .enter()
                .append("tr");

            // create a cell in each row for each column
            var cells = rows.selectAll("td")
                .data(function(row) {
                    return columns.map(function(column) {
                        return {column: column, value: row[column]};
                    });
                })
            .enter()
                .append("td")
                .attr("style", "font-family: monospace")
                .html(function(d) { return amatyrlib.autoformat(d.column, d.value); });
        });
    }

    // Auto update webcam
    setInterval(function () {
      var imgElem = document.getElementById("webcam");
      var newImg = new Image();
      newImg.src = imgElem.src.split("?")[0] + "?" + new Date().getTime();
      newImg.addEventListener("load", function (evt) {
        imgElem.src = newImg.src;
      });
    }, 30000);

    return this;
}
var amatyrlib = new amatyrlib();
var amatyr = new AmatYr('/api/');
<|endoftext|>


<commit_before>
// based on http://bl.ocks.org/d3noob/8329404

// *********** Convert flat data into a nice tree ***************
// create a name: node map
var dataMap = data.reduce(function(map, node) {
	map[node.name] = node;
	return map;
}, {});

// create the tree array
var treeData = [];
data.forEach(function(node) {
	// add to parent
	var parent = dataMap[node.parent];
	if (parent) {
		// create child array if it doesn't exist
		(parent.children || (parent.children = []))
			// add node to child array
			.push(node);
	} else {
		// parent is null or missing
		treeData.push(node);
	}
});

// ************** Generate the tree diagram	 *****************
var margin = {top: 20, right: 10, bottom: 10, left: 20},
	width = 600 - margin.right - margin.left,
	height = 400 - margin.top - margin.bottom;

var i = 0;

var tree = d3.layout.tree()
	.size([width, height]);

var diagonal = d3.svg.diagonal()
	.projection(function(d) { return [d.x, d.y]; });

var svg = d3.select("#graph").append("svg")
    .attr("class", "graph")
	.attr("width", width + margin.right + margin.left)
	.attr("height", height + margin.top + margin.bottom)
  .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];

update(root);

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
	  links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) { d.y = d.depth * 80; });

  // Declare the nodes…
  var node = svg.selectAll("g.node")
	  .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter the nodes.
  var nodeEnter = node.enter().append("g")
	  .attr("class", "node")
	  .attr("transform", function(d) {
		  return "translate(" + d.x + "," + d.y + ")"; });

  nodeEnter.append("circle")
	  .attr("r", 10)
	  .style("fill", "#fff");

  nodeEnter.append("text")
	  .attr("x", function(d) {
		  return d.children  })//|| d._children ? -13 : 13; })
	  .attr("dy", "22px")
	  .attr("text-anchor", function(d) {
		  return "middle" })//|| d._children ? "end" : "start"; })
	  .text(function(d) { return d.name; })
	  .style("fill-opacity", 1);

  // Declare the links…
  var link = svg.selectAll("path.link")
	  .data(links, function(d) { return d.target.id; });

  // Enter the links.
  link.enter().insert("path", "g")
	  .attr("class", "link")
	  .attr("d", diagonal);

}

<commit_msg>make ancestry graph bigger<commit_after>
// based on http://bl.ocks.org/d3noob/8329404

// *********** Convert flat data into a nice tree ***************
// create a name: node map
var dataMap = data.reduce(function(map, node) {
	map[node.name] = node;
	return map;
}, {});

// create the tree array
var treeData = [];
data.forEach(function(node) {
	// add to parent
	var parent = dataMap[node.parent];
	if (parent) {
		// create child array if it doesn't exist
		(parent.children || (parent.children = []))
			// add node to child array
			.push(node);
	} else {
		// parent is null or missing
		treeData.push(node);
	}
});

// ************** Generate the tree diagram	 *****************
var margin = {top: 20, right: 10, bottom: 10, left: 20},
	width = 600 - margin.right - margin.left,
	height = 600 - margin.top - margin.bottom;

var i = 0;

var tree = d3.layout.tree()
	.size([width, height]);

var diagonal = d3.svg.diagonal()
	.projection(function(d) { return [d.x, d.y]; });

var svg = d3.select("#graph").append("svg")
    .attr("class", "graph")
	.attr("width", width + margin.right + margin.left)
	.attr("height", height + margin.top + margin.bottom)
  .append("g")
	.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];

update(root);

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
	  links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) { d.y = d.depth * 80; });

  // Declare the nodes…
  var node = svg.selectAll("g.node")
	  .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter the nodes.
  var nodeEnter = node.enter().append("g")
	  .attr("class", "node")
	  .attr("transform", function(d) {
		  return "translate(" + d.x + "," + d.y + ")"; });

  nodeEnter.append("circle")
	  .attr("r", 10)
	  .style("fill", "#fff");

  nodeEnter.append("text")
	  .attr("x", function(d) {
		  return d.children  })//|| d._children ? -13 : 13; })
	  .attr("dy", "22px")
	  .attr("text-anchor", function(d) {
		  return "middle" })//|| d._children ? "end" : "start"; })
	  .text(function(d) { return d.name; })
	  .style("fill-opacity", 1);

  // Declare the links…
  var link = svg.selectAll("path.link")
	  .data(links, function(d) { return d.target.id; });

  // Enter the links.
  link.enter().insert("path", "g")
	  .attr("class", "link")
	  .attr("d", diagonal);

}

<|endoftext|>


<commit_before>var detailsLat, detailsLon;
var requests = new Array();

// Handlebars helpers
Handlebars.registerHelper('carouselimages', function(spacedata) {
    var space_id = spacedata.id;
    var elements = new Array;
    for (i=0; i < spacedata.images.length; i++) {
        image_id = spacedata.images[i].id;
        image_url = "background:url(/space/" + space_id + "/image/" + image_id + "/thumb/constrain/width:500)";
        div_string = "

"
        elements.push(div_string);
    }
    return new Handlebars.SafeString(elements.join('\n'));
});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Handlebars.registerHelper('formatHours', function(hours) {
    //tomorrow_starts_at_midnight = true;
    //tomorrow_is_24_hours =
    //if (start_time[0] == 0 && start_time[1] == 0 && end_time[0] == 23 && end_time[1] == 59 && tomorrow_starts_at_midnight && !tomorrow_is_24_hours && tomorrows_hour > 3) {
        //dsf
    //}
    var formatted = {};
    $.each(hours, function(day) {
        if (hours[day].length > 0) {
            $.each(hours[day], function() {
                this[0] = this[0].replace(/^0+/, '');
                this[1] = this[1].replace(/^0+/, '');
            });
            dayMarker = day.charAt(0);
            dayMarker = dayMarker.toUpperCase();
            // Show two characters for Th, Sa, Su
            if (dayMarker == 'T' && day.charAt(1) == 'h' || dayMarker == 'S' && day.charAt(1) == 'a' || dayMarker == 'S' && day.charAt(1) == 'u') {
                dayMarker += day.charAt(1);
            }

            formatted[dayMarker] = to12Hour(hours[day]).join(", ");
        }
    });
    formatted = sortDays(formatted);
    formatted = groupHours(formatted);
    return new Handlebars.SafeString(formatted.join("
"));
});

function groupHours(days) {
    var days1 = [];
    var hours = [];
    var days2 = [];
    var daycount =0;
    var hourscount = 0;
    var final_hours = [];
    var final_hours_count=0;

    for(var i=0;i < days.length; i++) {
        var split = days[i].split(": ");
        var day = split[0];
        var hours1 = split[1].split(", ");
        for(hour in hours1) {
            days1[daycount]=day;
            if(day == "M") {
                days2[daycount]=0;
            }else if(day == "T") {
                days2[daycount]=1;
            }else if(day == "W") {
                days2[daycount]=2;
            }else if(day == "Th") {
                days2[daycount]=3;
            }else if(day == "F") {
                days2[daycount]=4;
            }else if(day == "Sa") {
                days2[daycount]=5;
            }else if(day == "Su") {
                days2[daycount]=6;
            }
            hours[hourscount]= hours1[hour];
            daycount++;
            hourscount++;
        }

    }

    for(var i=0; i<hours.length; i++) {
        var hour = hours[i].split(" - ");

        if(hours[i] != "Open 24 Hours"&& hour[1]=="Midnight") {
            var next_day = "null";
            if(i != hours.length-1) {
                for( var j=i+1; j<hours.length; j++) {
                    var new_hour=hours[j].split(" - ");
                    if((days2[j]-days2[i])> 1) {
                        break;
                    }
                    if((days2[j]-days2[i])== 1 && new_hour[0]=="12AM") {
                        hour[1]=new_hour[1];
                        hours[j]="null";
                        break;
                    }
                }
                hours[i]=hour[0]+" - "+ hour[1];
            }else if( days1[i] == "Su") {
                for( var j=0; j<hours.length; j++) {
                    var new_hour=hours[j].split(" - ");
                    if((days2[j]-days2[i])!= -6) {
                        break;
                    }
                    if((days2[j]-days2[i])==-6 && new_hour[0]=="12AM") {
                        hour[1]=new_hour[1];
                        hours[j]="null";
                        break;
                    }
                }
                hours[i]=hour[0]+" - "+ hour[1];
            }
        }
    }

    for(var i=0; i<hours.length; i++) {
        if (hours[i] != "null" && i != hours.length-1) {
            for(var j =i+1; j<hours.length; j++) {

                if(hours[i]==hours[j]) {
                    days1[i]+= ", "+days1[j];
                    hours[j]="null";
                }
            }
        }
    }
    for(var i=0; i<hours.length; i++) {
        if( hours[i] != "null") {
            final_hours[final_hours_count]=days1[i]+": "+ hours[i];
            final_hours_count++;
        }
    }
    return final_hours;
}

function to12Hour(day) {
    var retData = [];
    for (var j=0; j<day.length; j++) {
        var data = [ day[j][0], day[j][1] ];
        for (var i=0; i<data.length; i++) {
            time = data[i].split(":");
            if(time[0]=="23" & time[1] == "59") {
                data[i] = "Midnight";
            }
            else if (time[0] =="12" & time[1] =="00") {
                data[i] = "Noon";
            }else {
                if (time[0] > 12) {
                    time[0] -= 12;

                    time[1] += "PM";
                }
                else if (time[0] < 1) {
                    time[0] = 12;
                    time[1] += "AM";
                }
                else {
                    time[1] += "AM";
                }
                if (time[1] == "00AM") {
                    data[i] = time[0];
                    data[i] += "AM";
                } else if (time[1] == "00PM") {
                    data[i] = time[0];
                    data[i] += "PM"
                }else {
                    data[i] = time.join(":");
                }
            }
        }
        if(data[0]=="12AM" & data[1]=="Midnight") {
            retData[j]="Open 24 Hours";
        }else {
            retData[j]=data[0] +" - " +data[1];
        }
    }
    return retData;
}

function sortDays(days) {
    var ordered = [];
    order = ["M", "T", "W", "Th", "F", "Sa", "Su"];
    $.each(order, function(day) {
        if (days[order[day]]) {
            ordered.push(order[day] +": " +days[order[day]] );
        }
    });
    return ordered;
}

function default_open_at_filter() {
    // set the default open_at filter to close to now
    var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var date = new Date();
    var hour = date.getHours();
    var min = date.getMinutes();

    if (min < 16) {
        min = "00";
    }else if (min < 46) {
        min = "30";
    }else {
        min = "00";
        hour++;
    }

    if (hour > 11) {
        $("#ampm-from").val("PM");
    }else {
        $("#ampm-from").val("AM");
    }
    if (hour > 12) {
        hour = hour-12;
    }
    hour = ""+hour+":"+min;
    $("#day-from").val(weekdays[date.getDay()]);
    $("#hour-from").val(hour);
}

function format_location_filter(data) {
    var source = $('#building_list').html();
    var template = Handlebars.compile(source);
    //data = new String(data);
    $('#building_list_container').html(template({data: data}));
}

// Found at http://stackoverflow.com/questions/476679/preloading-images-with-jquery
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

(function(g){

	$(document).ready(function() {

        var pinimgs = ['/static/img/pins/pin00.png', '/static/img/pins/pin01.png'];
        preload(pinimgs);

        // handle changing of the location select
        $('#location_select').change(function() {
            window.default_latitude = $(this).val().split(',')[0];
            window.default_longitude = $(this).val().split(',')[1];
            // in case a new location gets selected before the map loads
            if (window.spacescout_map != null) {
                window.spacescout_map.setCenter(new google.maps.LatLng(window.default_latitude, window.default_longitude));
            }
        });

    	// handle clicking on map centering buttons
        $('#center_all').live('click', function(e){

            e.preventDefault();
            if (window.spacescout_map.getZoom() != window.default_zoom) {
                window.spacescout_map.setZoom(window.default_zoom);
            }
            window.spacescout_map.setCenter(new google.maps.LatLng(window.default_latitude, window.default_longitude));
        });

        // populate the location filter list
        url = '/buildings';
        if (window.default_location != null) {
            url = url + '?campus=' + window.default_location;
        }
        $.ajax({
            url: url,
            success: format_location_filter
        });

        // handle clicking on the "done" button for filters
        $("#view_results_button").click(function() {
            $('.count').hide();
            $('.spaces').hide();
            run_custom_search();
        });

        default_open_at_filter();

	});

})(this);

function getSpaceMap(lat, lon) {

  if (window.space_latitude) {
    lat = window.space_latitude
  }

  if (window.space_longitude) {
    lon = window.space_longitude
  }

  var mapOptions = {
    zoom: 17,
    center: new google.maps.LatLng(lat , lon),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    streetViewControl: false
  }

  var map = new google.maps.Map(document.getElementById("spaceMap"), mapOptions);

  var image = '/static/img/pins/pin00.png';

  var spaceLatLng = new google.maps.LatLng(lat , lon);
  var spaceMarker = new google.maps.Marker({
      position: spaceLatLng,
      map: map,
      icon: image
  });

}

function replaceUrls(){
    // Replace urls in reservation notes with actual links.
    var text = $("#ei_reservation_notes").html();
    var patt = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
    var url = patt.exec(text);
    if (url != null) {
        text = text.replace(url, "" + url + "");
        $("#ei_reservation_notes").html(text);
    }
}
<commit_msg>Change the buildings filter when location is changed.<commit_after>var detailsLat, detailsLon;
var requests = new Array();

// Handlebars helpers
Handlebars.registerHelper('carouselimages', function(spacedata) {
    var space_id = spacedata.id;
    var elements = new Array;
    for (i=0; i < spacedata.images.length; i++) {
        image_id = spacedata.images[i].id;
        image_url = "background:url(/space/" + space_id + "/image/" + image_id + "/thumb/constrain/width:500)";
        div_string = "

"
        elements.push(div_string);
    }
    return new Handlebars.SafeString(elements.join('\n'));
});

Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {

    if (arguments.length < 3)
        throw new Error("Handlerbars Helper 'compare' needs 2 parameters");

    operator = options.hash.operator || "==";

    var operators = {
        '==':       function(l,r) { return l == r; },
        '===':      function(l,r) { return l === r; },
        '!=':       function(l,r) { return l != r; },
        '<':        function(l,r) { return l < r; },
        '>':        function(l,r) { return l > r; },
        '<=':       function(l,r) { return l <= r; },
        '>=':       function(l,r) { return l >= r; },
        'typeof':   function(l,r) { return typeof l == r; }
    }

    if (!operators[operator])
        throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);

    var result = operators[operator](lvalue,rvalue);

    if( result ) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }

});

Handlebars.registerHelper('formatHours', function(hours) {
    //tomorrow_starts_at_midnight = true;
    //tomorrow_is_24_hours =
    //if (start_time[0] == 0 && start_time[1] == 0 && end_time[0] == 23 && end_time[1] == 59 && tomorrow_starts_at_midnight && !tomorrow_is_24_hours && tomorrows_hour > 3) {
        //dsf
    //}
    var formatted = {};
    $.each(hours, function(day) {
        if (hours[day].length > 0) {
            $.each(hours[day], function() {
                this[0] = this[0].replace(/^0+/, '');
                this[1] = this[1].replace(/^0+/, '');
            });
            dayMarker = day.charAt(0);
            dayMarker = dayMarker.toUpperCase();
            // Show two characters for Th, Sa, Su
            if (dayMarker == 'T' && day.charAt(1) == 'h' || dayMarker == 'S' && day.charAt(1) == 'a' || dayMarker == 'S' && day.charAt(1) == 'u') {
                dayMarker += day.charAt(1);
            }

            formatted[dayMarker] = to12Hour(hours[day]).join(", ");
        }
    });
    formatted = sortDays(formatted);
    formatted = groupHours(formatted);
    return new Handlebars.SafeString(formatted.join("
"));
});

function groupHours(days) {
    var days1 = [];
    var hours = [];
    var days2 = [];
    var daycount =0;
    var hourscount = 0;
    var final_hours = [];
    var final_hours_count=0;

    for(var i=0;i < days.length; i++) {
        var split = days[i].split(": ");
        var day = split[0];
        var hours1 = split[1].split(", ");
        for(hour in hours1) {
            days1[daycount]=day;
            if(day == "M") {
                days2[daycount]=0;
            }else if(day == "T") {
                days2[daycount]=1;
            }else if(day == "W") {
                days2[daycount]=2;
            }else if(day == "Th") {
                days2[daycount]=3;
            }else if(day == "F") {
                days2[daycount]=4;
            }else if(day == "Sa") {
                days2[daycount]=5;
            }else if(day == "Su") {
                days2[daycount]=6;
            }
            hours[hourscount]= hours1[hour];
            daycount++;
            hourscount++;
        }

    }

    for(var i=0; i<hours.length; i++) {
        var hour = hours[i].split(" - ");

        if(hours[i] != "Open 24 Hours"&& hour[1]=="Midnight") {
            var next_day = "null";
            if(i != hours.length-1) {
                for( var j=i+1; j<hours.length; j++) {
                    var new_hour=hours[j].split(" - ");
                    if((days2[j]-days2[i])> 1) {
                        break;
                    }
                    if((days2[j]-days2[i])== 1 && new_hour[0]=="12AM") {
                        hour[1]=new_hour[1];
                        hours[j]="null";
                        break;
                    }
                }
                hours[i]=hour[0]+" - "+ hour[1];
            }else if( days1[i] == "Su") {
                for( var j=0; j<hours.length; j++) {
                    var new_hour=hours[j].split(" - ");
                    if((days2[j]-days2[i])!= -6) {
                        break;
                    }
                    if((days2[j]-days2[i])==-6 && new_hour[0]=="12AM") {
                        hour[1]=new_hour[1];
                        hours[j]="null";
                        break;
                    }
                }
                hours[i]=hour[0]+" - "+ hour[1];
            }
        }
    }

    for(var i=0; i<hours.length; i++) {
        if (hours[i] != "null" && i != hours.length-1) {
            for(var j =i+1; j<hours.length; j++) {

                if(hours[i]==hours[j]) {
                    days1[i]+= ", "+days1[j];
                    hours[j]="null";
                }
            }
        }
    }
    for(var i=0; i<hours.length; i++) {
        if( hours[i] != "null") {
            final_hours[final_hours_count]=days1[i]+": "+ hours[i];
            final_hours_count++;
        }
    }
    return final_hours;
}

function to12Hour(day) {
    var retData = [];
    for (var j=0; j<day.length; j++) {
        var data = [ day[j][0], day[j][1] ];
        for (var i=0; i<data.length; i++) {
            time = data[i].split(":");
            if(time[0]=="23" & time[1] == "59") {
                data[i] = "Midnight";
            }
            else if (time[0] =="12" & time[1] =="00") {
                data[i] = "Noon";
            }else {
                if (time[0] > 12) {
                    time[0] -= 12;

                    time[1] += "PM";
                }
                else if (time[0] < 1) {
                    time[0] = 12;
                    time[1] += "AM";
                }
                else {
                    time[1] += "AM";
                }
                if (time[1] == "00AM") {
                    data[i] = time[0];
                    data[i] += "AM";
                } else if (time[1] == "00PM") {
                    data[i] = time[0];
                    data[i] += "PM"
                }else {
                    data[i] = time.join(":");
                }
            }
        }
        if(data[0]=="12AM" & data[1]=="Midnight") {
            retData[j]="Open 24 Hours";
        }else {
            retData[j]=data[0] +" - " +data[1];
        }
    }
    return retData;
}

function sortDays(days) {
    var ordered = [];
    order = ["M", "T", "W", "Th", "F", "Sa", "Su"];
    $.each(order, function(day) {
        if (days[order[day]]) {
            ordered.push(order[day] +": " +days[order[day]] );
        }
    });
    return ordered;
}

function default_open_at_filter() {
    // set the default open_at filter to close to now
    var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var date = new Date();
    var hour = date.getHours();
    var min = date.getMinutes();

    if (min < 16) {
        min = "00";
    }else if (min < 46) {
        min = "30";
    }else {
        min = "00";
        hour++;
    }

    if (hour > 11) {
        $("#ampm-from").val("PM");
    }else {
        $("#ampm-from").val("AM");
    }
    if (hour > 12) {
        hour = hour-12;
    }
    hour = ""+hour+":"+min;
    $("#day-from").val(weekdays[date.getDay()]);
    $("#hour-from").val(hour);
}

function format_location_filter(data) {
    var source = $('#building_list').html();
    var template = Handlebars.compile(source);
    //data = new String(data);
    $('#building_list_container').html(template({data: data}));
}

function get_location_buildings() {
    // populate the location filter list
    url = '/buildings';
    if (window.default_location != null) {
        url = url + '?campus=' + window.default_location;
    }
    $.ajax({
        url: url,
        success: format_location_filter
    });

}

// Found at http://stackoverflow.com/questions/476679/preloading-images-with-jquery
function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

(function(g){

	$(document).ready(function() {

        var pinimgs = ['/static/img/pins/pin00.png', '/static/img/pins/pin01.png'];
        preload(pinimgs);

        // handle changing of the location select
        $('#location_select').change(function() {
            window.default_latitude = $(this).val().split(',')[0];
            window.default_longitude = $(this).val().split(',')[1];
            window.default_location = $(this).val().split(',')[2];
            // in case a new location gets selected before the map loads
            if (window.spacescout_map != null) {
                window.spacescout_map.setCenter(new google.maps.LatLng(window.default_latitude, window.default_longitude));
            }
            get_location_buildings();
        });

    	// handle clicking on map centering buttons
        $('#center_all').live('click', function(e){

            e.preventDefault();
            if (window.spacescout_map.getZoom() != window.default_zoom) {
                window.spacescout_map.setZoom(window.default_zoom);
            }
            window.spacescout_map.setCenter(new google.maps.LatLng(window.default_latitude, window.default_longitude));
        });

        get_location_buildings();

        // handle clicking on the "done" button for filters
        $("#view_results_button").click(function() {
            $('.count').hide();
            $('.spaces').hide();
            run_custom_search();
        });

        default_open_at_filter();

	});

})(this);

function getSpaceMap(lat, lon) {

  if (window.space_latitude) {
    lat = window.space_latitude
  }

  if (window.space_longitude) {
    lon = window.space_longitude
  }

  var mapOptions = {
    zoom: 17,
    center: new google.maps.LatLng(lat , lon),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    streetViewControl: false
  }

  var map = new google.maps.Map(document.getElementById("spaceMap"), mapOptions);

  var image = '/static/img/pins/pin00.png';

  var spaceLatLng = new google.maps.LatLng(lat , lon);
  var spaceMarker = new google.maps.Marker({
      position: spaceLatLng,
      map: map,
      icon: image
  });

}

function replaceUrls(){
    // Replace urls in reservation notes with actual links.
    var text = $("#ei_reservation_notes").html();
    var patt = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
    var url = patt.exec(text);
    if (url != null) {
        text = text.replace(url, "" + url + "");
        $("#ei_reservation_notes").html(text);
    }
}
<|endoftext|>


<commit_before>/* Custom topojson class courtesy of Ryan Clark */
L.TopoJSON = L.GeoJSON.extend({
    addData: function(jsonData) {
        if (jsonData.type === "Topology") {
            for (var key in jsonData.objects) {
                geojson = topojson.feature(jsonData, jsonData.objects[key]);
                L.GeoJSON.prototype.addData.call(this, geojson);
            }
        } else {
            L.GeoJSON.prototype.addData.call(this, jsonData);
        }
    }
});

function initMap() {
    map.setView([51.5, -0.5], 8);
    mapLink = 'OpenStreetMap';
    // load a tile layer
    L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors © CartoDB, CartoDB attributions',
        maxZoom: 20,
        minZoom: 0
    }).addTo(map);
    $.getJSON('./data/topo_lad.json')
        .done(addTopoData);
}

function recenter() {
    map.fitBounds(topoLayer.getBounds());
}

function loadData() {
    $.ajax({
        url: "./data/lad_complexity.json",
        dataType: 'json'
    }).done(function(data) {
        complexityData = data;
        initMap();
    });
}

function addTopoData(data) {
    topoLayer.addData(data);
    topoLayer.addTo(map);
    topoLayer.eachLayer(handleLayer);
}

function handleLayer(layer) {
    var fillColor = colorScale(complexityData[layer.feature.id].value).hex();
    layer.setStyle({
        fillColor: fillColor,
        fillOpacity: 0.6,
        weight: 0.5,
        opacity: 1,
        color: 'white',
        dashArray: '1',
        smoothFactor: 0.5
    });

    layer.on({
        mouseover: enterLayer,
        mouseout: leaveLayer,

    });
}

function enterLayer() {
    this.bringToFront();
    this.setStyle({
        weight: 3,
        opacity: 1,
        fillOpacity: 1,
        color: '#666666'
    });
}

function leaveLayer() {
    this.bringToBack();
    this.setStyle({
        weight: 1,
        opacity: 0.5,
        fillOpacity: 0.7,
        color: 'white'
    });
}

// Initialise global map and layer variables
var map = new L.map('map');
var topoLayer = new L.TopoJSON();
var colorScale = chroma
    .scale(chroma.brewer.YlOrRd)
    .domain([-2.1227372118474177, 2.397453389303414]);

/* Dynamic resizing */
$(window).on("resize", function() {
    var h = $(window).height();
    $("#map").height(h - (h * 0.2));
    map.invalidateSize();
}).trigger("resize");

loadData();

/*--------------------------------------------------------------*/
/* Charts */

var chart;

function currentSelectedIndustry() {
    return $("#indList").val();
}

function parseData(data, prob, prod_complexity) {
    var marker_data = [];
    var x = [];
    var y = [];
    var color = [];
    for (var key in data.S12000033) {
        if (key !== "growth" && key !== "LAD14NM") {
            x.push(data.S12000033[key]);
            y.push(prob.S12000033[key]);
            color.push(prod_complexity[key].score);
        }
    }
    marker_data = [{
        x: x,
        y: y,
        mode: 'markers',
        marker: {
            sizemode: 'area',
            size: 20,
            sizeref: '2em',
            colorscale: 'YlOrRd',
            cmin: -3,
            cmax: 3,
            color: color,
            colorbar: {
                titleside: 'right',
                outlinecolor: 'rgba(68,68,68,0)',
                ticks: 'none',
                ticklen: 0,
                tickfont: 'Arial',
                fontsize: 4
            }
        }
    }];
    console.log(marker_data);
    return marker_data;
}

function analyze(error, business_data, prod_complexity, prob) {
    if (error) {
        console.log(error);
    }

    /*business_data.forEach(function(d) {
        d.growth = +d.growth;
        d.construction = +d.construction;
        d.manufacture_advanced = +d.manufacture_advanced;
        d.manufacture_agrochemical = +d.manufacture_agrochemical;
        d.manufacture_automotive = +d.manufacture_automotive;
        d.manufacture_chemical_pharma = +d.manufacture_chemical_pharma;
        d.manufacture_construction = +d.manufacture_construction;
        d.manufacture_electrical = +d.manufacture_electrical;
        d.manufacture_food = +d.manufacture_food;
        d.manufacture_food_2 = +d.manufacture_food_2;
        d.manufacture_footwear_leather = +d.manufacture_footwear_leather;
        d.manufacture_furniture = +d.manufacture_furniture;
        d.manufacture_light_misc = +d.manufacture_light_misc;
        d.manufacture_machinery = +d.manufacture_machinery;
        d.manufacture_metallurgy = +d.manufacture_metallurgy;
        d.manufacture_metallurgy_misc = +d.manufacture_metallurgy;
        d.manufacture_metallurgy_tools = +d.manufacture_metallurgy_tools;
        d.manufacture_optics = +d.manufacture_optics;
        d.manufacture_paper = +d.manufacture_paper;
        d.manufacture_plastic = +d.manufacture_plastic;
        d.manufacture_rubber = +d.manufacture_rubber;
        d.manufacture_shipbuilding = +d.manufacture_shipbuilding;
        d.manufacture_textiles = +d.manufacture_textiles;
        d.manufacturing_aerospace = +d.manufacturing_aerospace;
        d.manufacturing_misc = +d.manufacturing_misc;
        d.mining_mining = +d.mining_mining;
        d.mining_oil_gas = +d.mining_oil_gas;
        d.primary_farming = +d.primary_farming;
        d.primary_fishing = +d.primary_fishing;
        d.primary_forestry = +d.primary_forestry;
        d.primary_livestock = +d.primary_livestock;
        d.services_agriculture_rural = +d.services_agriculture_rural;
        d.services_automotive = +d.services_automotive;
        d.services_business_support = +d.services_business_support;
        d.services_cleaning_facilities = +d.services_cleaning_facilities;
        d.services_computing = +d.services_computing;
        d.services_consumer_retail = +d.services_consumer_retail;
        d.services_creative = +d.services_creative;
        d.services_creative_content = +d.services_creative_content;
        d.services_cultural = +d.services_cultural;
        d.services_education = +d.services_education;
        d.services_energy = +d.services_energy;
        d.services_finance_insurance = +d.services_finance_insurance;
        d.services_finance_real_state = +d.services_finance_real_state;
        d.services_freight_transport = +d.services_freight_transport;
        d.services_head_offices = +d.services_head_offices;
        d.services_health = +d.services_health;
        d.services_human_resources = +d.services_human_resources;
        d.services_kibs = +d.services_kibs;
        d.services_leisure = +d.services_leisure;
        d.services_professional_public = +d.services_professional_public;
        d.services_publishing = +d.services_publishing;
        d.services_r_and_d = +d.services_r_and_d;
        d.services_real_estate = +d.services_real_estate;
        d.services_repair_transport = +d.services_repair_transport;
        d.services_residential_social_work = +d.services_residential_social_work;
        d.services_retail_misc = +d.services_retail_misc;
        d.services_technical_engineering = +d.services_technical_engineering;
        d.services_telecommunications = +d.services_telecommunications;
        d.services_transport_storage = +d.services_transport_storage;
        d.services_travelling_tourism = +d.services_travelling_tourism;
        d.services_urban_transport = +d.services_urban_transport;
        d.services_waste_recycling = +d.services_waste_recycling;
        d.wholesale_repair_machinery = +d.wholesale_repair_machinery;
        d.wholesale_retail_misc = +d.wholesale_retail_misc;
    });*/

        var data = parseData(business_data, prob, prod_complexity);

        var layout = {
            showlegend: false,
            xaxis: {
                title: 'Number of Businesses - 2015',
                type: 'log',
                autorange: true
            },
            yaxis: {
                title: 'Probability of Growth in Sector in Area',
            },
            margin: {
                t: 10
            },
            hovermode: 'closest',
        };
        Plotly.newPlot('chart', data, layout, {
            showLink: false
        });
}

queue()
    .defer(d3.json, "/data/business_data.json")
    .defer(d3.json, "/data/product_complexity_2015.json")
    .defer(d3.json, "/data/probabilities.json")
    .await(analyze);
<commit_msg>Remove unneeded string formating<commit_after>/* Custom topojson class courtesy of Ryan Clark */
L.TopoJSON = L.GeoJSON.extend({
    addData: function(jsonData) {
        if (jsonData.type === "Topology") {
            for (var key in jsonData.objects) {
                geojson = topojson.feature(jsonData, jsonData.objects[key]);
                L.GeoJSON.prototype.addData.call(this, geojson);
            }
        } else {
            L.GeoJSON.prototype.addData.call(this, jsonData);
        }
    }
});

function initMap() {
    map.setView([51.5, -0.5], 8);
    mapLink = 'OpenStreetMap';
    // load a tile layer
    L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors © CartoDB, CartoDB attributions',
        maxZoom: 20,
        minZoom: 0
    }).addTo(map);
    $.getJSON('./data/topo_lad.json')
        .done(addTopoData);
}

function recenter() {
    map.fitBounds(topoLayer.getBounds());
}

function loadData() {
    $.ajax({
        url: "./data/lad_complexity.json",
        dataType: 'json'
    }).done(function(data) {
        complexityData = data;
        initMap();
    });
}

function addTopoData(data) {
    topoLayer.addData(data);
    topoLayer.addTo(map);
    topoLayer.eachLayer(handleLayer);
}

function handleLayer(layer) {
    var fillColor = colorScale(complexityData[layer.feature.id].value).hex();
    layer.setStyle({
        fillColor: fillColor,
        fillOpacity: 0.6,
        weight: 0.5,
        opacity: 1,
        color: 'white',
        dashArray: '1',
        smoothFactor: 0.5
    });

    layer.on({
        mouseover: enterLayer,
        mouseout: leaveLayer,

    });
}

function enterLayer() {
    this.bringToFront();
    this.setStyle({
        weight: 3,
        opacity: 1,
        fillOpacity: 1,
        color: '#666666'
    });
}

function leaveLayer() {
    this.bringToBack();
    this.setStyle({
        weight: 1,
        opacity: 0.5,
        fillOpacity: 0.7,
        color: 'white'
    });
}

// Initialise global map and layer variables
var map = new L.map('map');
var topoLayer = new L.TopoJSON();
var colorScale = chroma
    .scale(chroma.brewer.YlOrRd)
    .domain([-2.1227372118474177, 2.397453389303414]);

/* Dynamic resizing */
$(window).on("resize", function() {
    var h = $(window).height();
    $("#map").height(h - (h * 0.2));
    map.invalidateSize();
}).trigger("resize");

loadData();

/*--------------------------------------------------------------*/
/* Charts */

var chart;

function currentSelectedIndustry() {
    return $("#indList").val();
}

function parseData(data, prob, prod_complexity) {
    var marker_data = [];
    var x = [];
    var y = [];
    var color = [];
    for (var key in data.S12000033) {
        if (key !== "growth" && key !== "LAD14NM") {
            x.push(data.S12000033[key]);
            y.push(prob.S12000033[key]);
            color.push(prod_complexity[key].score);
        }
    }
    marker_data = [{
        x: x,
        y: y,
        mode: 'markers',
        marker: {
            sizemode: 'area',
            size: 20,
            sizeref: '2em',
            colorscale: 'YlOrRd',
            cmin: -3,
            cmax: 3,
            color: color,
            colorbar: {
                titleside: 'right',
                outlinecolor: 'rgba(68,68,68,0)',
                ticks: 'none',
                ticklen: 0,
                tickfont: 'Arial',
                fontsize: 4
            }
        }
    }];
    console.log(marker_data);
    return marker_data;
}

function analyze(error, business_data, prod_complexity, prob) {
    if (error) {
        console.log(error);
    }

    var data = parseData(business_data, prob, prod_complexity);

    var layout = {
        showlegend: false,
        xaxis: {
            title: 'Number of Businesses - 2015',
            type: 'log',
            autorange: true
        },
        yaxis: {
            title: 'Probability of Growth in Sector in Area',
        },
        margin: {
            t: 10
        },
        hovermode: 'closest',
    };
    Plotly.newPlot('chart', data, layout, {
        showLink: false
    });
}

queue()
    .defer(d3.json, "/data/business_data.json")
    .defer(d3.json, "/data/product_complexity_2015.json")
    .defer(d3.json, "/data/probabilities.json")
    .await(analyze);
<|endoftext|>


<commit_before>---
layout: null
---

var cacheName = 'gdgpisa-cache-v1.4';
var urlsToCache = [
    '/',
    '/index.html',
    '/blog/',
    '/manifests/manifest_webapp.json',
    '/manifests/manifest_notpush.json',
    '/assets/header.jpg',
    '/static/img/avatar.png',
    '/static/img/logo.png',
    '/static/css/main.css',
    '/static/css/bootstrap-material-design.min.css',
    '/static/css/bootstrap.min.css',
    '/static/css/syntax.css',
    '/static/css/thickbox.css',
    'https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
    'https://code.jquery.com/jquery-migrate-1.2.1.min.js',
    'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js',
    'https://use.fontawesome.com/18475ccca4.js',
    '/static/css/projects.css'
];

{% for asset in site.static_files %}
    {% if asset.path contains '/assets/images' or asset.path contains '/assets/posts' or asset.extname == '.js' %}
    urlsToCache.push("{{ file.path }}")
    {% endif %}
{% endfor %}

// Cache posts
{% for post in site.posts %}
  urlsToCache.push("{{ post.url }}")
{% endfor %}

// Cache pages
{% for page in site.html_pages %}
  urlsToCache.push("{{ page.url }}")
{% endfor %}

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(cacheName)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('activate', function(event) {
  console.log('Finally active. Ready to start serving content!');
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});
<commit_msg>Added images to cache<commit_after>---
layout: null
---

var cacheName = 'gdgpisa-cache-v1.5';
var urlsToCache = [
    '/',
    '/index.html',
    '/blog/',
    '/manifests/manifest_webapp.json',
    '/manifests/manifest_notpush.json',
    '/assets/header.jpg',
    '/static/img/1.png',
    '/static/img/2.png',
    '/static/img/3.png',
    '/static/img/4.png',
    '/static/img/avatar.png',
    '/static/img/logo.png',
    '/static/css/main.css',
    '/static/css/bootstrap-material-design.min.css',
    '/static/css/bootstrap.min.css',
    '/static/css/syntax.css',
    '/static/css/thickbox.css',
    'https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
    'https://code.jquery.com/jquery-migrate-1.2.1.min.js',
    'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js',
    'https://use.fontawesome.com/18475ccca4.js',
    '/static/css/projects.css'
];

{% for asset in site.static_files %}
    {% if asset.path contains '/assets/images' or asset.path contains '/assets/posts' or asset.extname == '.js' %}
    urlsToCache.push("{{ file.path }}")
    {% endif %}
{% endfor %}

// Cache posts
{% for post in site.posts %}
  urlsToCache.push("{{ post.url }}")
{% endfor %}

// Cache pages
{% for page in site.html_pages %}
  urlsToCache.push("{{ page.url }}")
{% endfor %}

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(cacheName)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

self.addEventListener('activate', function(event) {
  console.log('Finally active. Ready to start serving content!');
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          return response;
        }
        return fetch(event.request);
      }
    )
  );
});
<|endoftext|>