<commit_before>'use strict';

const CompositeDisposable = require('atom').CompositeDisposable;

const SelectListView = require('atom-space-pen-views').SelectListView,
    $$ = require('atom-space-pen-views').$$;

const _utilities = require('./utilities');

class PVSelectListView extends SelectListView {

    constructor () {
        super();
    }

    initialize () {

        this.disposables = new CompositeDisposable();

        this.setLoading('loading projects...');
        this.getEmptyMessage('couldn\'t find any projects');
    }

    destroy () {
        this.cancel();

        if (this.panel) {
            this.panel.destroy();
        }
    }

    cancelSelection () {
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        }
    }

    confirmSelection () {
      if (this.panel && !this.panel.isVisible()) {
          return;
      }
        const item = this.getSelectedItem();
        if (item) {
            this.confirmed(item);
        }
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        }
    }

    confirmed (item) {
        const event = new MouseEvent('click');
        const view = document.getElementById(item.projectId);
        if (view) {
          view.dispatchEvent(event);
        }
        this.cancel();
    }

    selectPreviousItemView () {
        let view = this.getSelectedItemView().prev();
        if (!view.length) {
            view = this.list.find('li:last');
        }
        return this.selectItemView(view);
    }

    selectNextItemView () {
        let view = this.getSelectedItemView().next();
        if (!view.length) {
            view = this.list.find('li:first');
        }
        return this.selectItemView(view);
    }

    cancel () {
        this.filterEditorView.setText('');
        this.hide();
    }

    show () {
        if (!this.panel) {
            this.panel = atom.workspace.addModalPanel({
                item: this
            });
        }
        this.disposables.add(
            atom.commands.add(
                'atom-workspace', {
                    'core:move-up': this.selectPreviousItemView.bind(this),
                    'core:move-down': this.selectNextItemView.bind(this),
                    'core:confirm': this.confirmSelection.bind(this),
                    'core:cancel': this.cancelSelection.bind(this)
                }
            )
        );
        this.disposables.add(
            this.filterEditorView.getModel().getBuffer().onDidStopChanging(this.onChange.bind(this))
        );
        this.storeFocusedElement();
        this.panel.show();
        if (this.items.length > 0) {
            this.scrollToItemView(this.list.find('li:first'));
        }
        this.focusFilterEditor();
    }

    hide () {
        this.disposables.dispose();
        if (this.panel) {
            this.list.empty();
            this.panel.hide();
        }
    }

    cancelled () {
        this.cancel();
    }

    toggle () {
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        } else {
            this.populate(this.filterItems());
            this.show();
            this.focusFilterEditor();
        }
    }

    populate (items) {
        let models = [];
        if (Array.isArray(items) && items.length > 0) {
            models = items;
        }
        this.setItems(models);
    }

    filterItems (query) {
        let list = _utilities.fetchProjects();

        if (!list || list.length === 0) {
            return [];
        }

        if (!query) {
            return list;
        }

        return list.filter(
            (project) => {
                return project.projectName.includes(query);
            }
        );
    }

    getFilterKey () {
        if (this.getFilterQuery().length) {
            return 'projectName';
        }
        return '';
    }

    onChange () {
        if (this.focusFilterEditor) {
            this.populate(
                this.filterItems(this.getFilterQuery())
            );
        }
    }

    viewForItem (item) {
        return $$(function() {
            return this.li({
                class: 'two-lines pv-select-view-li'
            }, () => {
                this.div({
                    class: 'status icon '.concat(item.projectIcon || item.groupIcon || item.clientIcon)
                });
                this.div({
                    class: 'primary-line no-icon'
                }, () => {
                    return this.strong({}, () => {
                        return this.text(item.projectName);
                    });
                });
                this.div({
                    class: 'primary-secondary no-icon'
                }, () => {
                    let projectLine = '';
                    if (item.clientName) {
                        projectLine += item.clientName;
                    }
                    if (item.groupName) {
                        projectLine += (projectLine.length ? ' / ': '') + item.groupName;
                    }
                    return this.text(projectLine);
                });
                return this;
            });
        });
    }
}

module.exports = PVSelectListView;
<commit_msg>select-view: fuzzy search and fix class name 'secondary-line'  with the right naming<commit_after>'use strict';

const CompositeDisposable = require('atom').CompositeDisposable;

const SelectListView = require('atom-space-pen-views').SelectListView,
    $$ = require('atom-space-pen-views').$$;

const _utilities = require('./utilities');

class PVSelectListView extends SelectListView {

    constructor () {
        super();
    }

    initialize () {

        this.disposables = new CompositeDisposable();

        this.setLoading('loading projects...');
        this.getEmptyMessage('couldn\'t find any projects');
    }

    destroy () {
        this.cancel();

        if (this.panel) {
            this.panel.destroy();
        }
    }

    cancelSelection () {
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        }
    }

    confirmSelection () {
      if (this.panel && !this.panel.isVisible()) {
          return;
      }
        const item = this.getSelectedItem();
        if (item) {
            this.confirmed(item);
        }
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        }
    }

    confirmed (item) {
        const event = new MouseEvent('click');
        const view = document.getElementById(item.projectId);
        if (view) {
          view.dispatchEvent(event);
        }
        this.cancel();
    }

    selectPreviousItemView () {
        let view = this.getSelectedItemView().prev();
        if (!view.length) {
            view = this.list.find('li:last');
        }
        return this.selectItemView(view);
    }

    selectNextItemView () {
        let view = this.getSelectedItemView().next();
        if (!view.length) {
            view = this.list.find('li:first');
        }
        return this.selectItemView(view);
    }

    cancel () {
        this.filterEditorView.setText('');
        this.hide();
    }

    show () {
        if (!this.panel) {
            this.panel = atom.workspace.addModalPanel({
                item: this
            });
        }
        this.disposables.add(
            atom.commands.add(
                'atom-workspace', {
                    'core:move-up': this.selectPreviousItemView.bind(this),
                    'core:move-down': this.selectNextItemView.bind(this),
                    'core:confirm': this.confirmSelection.bind(this),
                    'core:cancel': this.cancelSelection.bind(this)
                }
            )
        );
        this.disposables.add(
            this.filterEditorView.getModel().getBuffer().onDidStopChanging(this.onChange.bind(this))
        );
        this.storeFocusedElement();
        this.panel.show();
        if (this.items.length > 0) {
            this.scrollToItemView(this.list.find('li:first'));
        }
        this.focusFilterEditor();
    }

    hide () {
        this.disposables.dispose();
        if (this.panel) {
            this.list.empty();
            this.panel.hide();
        }
    }

    cancelled () {
        this.cancel();
    }

    toggle () {
        if (this.panel && this.panel.isVisible()) {
            this.cancel();
        } else {
            this.populate(this.filterItems());
            this.show();
            this.focusFilterEditor();
        }
    }

    populate (items) {
        let models = [];
        if (Array.isArray(items) && items.length > 0) {
            models = items;
        }
        this.setItems(models);
    }

    filterItems (query) {
        let list = _utilities.fetchProjects();

        if (!list || list.length === 0) {
            return [];
        }

        if (!query) {
            return list;
        }

        query = query.toLowerCase();
        return list.filter(
            (project) => project.projectName.toLowerCase().indexOf(query) !== -1
        );
    }

    getFilterKey () {
        if (this.getFilterQuery().length) {
            return 'projectName';
        }
        return '';
    }

    onChange () {
        if (this.focusFilterEditor) {
            this.populate(
                this.filterItems(this.getFilterQuery())
            );
        }
    }

    viewForItem (item) {
        return $$(function() {
            return this.li({
                class: 'two-lines pv-select-view-li'
            }, () => {
                this.div({
                    class: 'status icon '.concat(item.projectIcon || item.groupIcon || item.clientIcon)
                });
                this.div({
                    class: 'primary-line no-icon'
                }, () => {
                    return this.strong({}, () => {
                        return this.text(item.projectName);
                    });
                });
                this.div({
                    class: 'secondary-line no-icon'
                }, () => {
                    let projectLine = '';
                    if (item.clientName) {
                        projectLine += item.clientName;
                    }
                    if (item.groupName) {
                        projectLine += (projectLine.length ? ' / ': '') + item.groupName;
                    }
                    return this.text(projectLine);
                });
                return this;
            });
        });
    }
}

module.exports = PVSelectListView;
<|endoftext|>


<commit_before>/* globals __DEV__ */
import Phaser from 'phaser'
import Player from '../sprites/Player'
import Monster from '../sprites/Monster'
import Level from '../sprites/Level'
import Item from '../sprites/Item'
import Fire from '../sprites/Fire'

import config from '../config'

export default class extends Phaser.State {
  init () {
    this.stage.backgroundColor = '#000'
  }
  preload () {
  }

  create () {
    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    this.game.time.advancedTiming = true;
    this.itemPickupCooldown = 1.0;

    this.backgroundLayer = this.game.add.group();
    this.map = new Level({
      game: this.game,
      asset: config.state.map
    });

    // background if needed
    this.bg = new Phaser.TileSprite(this.game, 0, 0, this.game.world.width, this.game.world.height, 'starfield');
    this.bg.tilePosition.y += 2;
    this.bg.anchor.setTo(0.5, 0.5);
    this.backgroundLayer.add(this.bg);

    // create and add player
    var entranceXY = this.getEntranceXY(config.state.entrance);
    this.player = new Player({
      game: this.game,
      x: entranceXY[0],
      y: entranceXY[1],
      asset: 'hero'
    })
    this.map.spriteLayer.add(this.player);
    this.game.camera.follow(this.player);

    this.cursor = this.game.input.keyboard.createCursorKeys();
    this.spacebar = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    this.dropkey = this.game.input.keyboard.addKey(Phaser.Keyboard.D);
    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      Phaser.Keyboard.SPACEBAR
    ]);

    this.shadowTexture = this.game.add.bitmapData(this.game.width+100, this.game.height+100);
    this.lightSprite = this.game.add.image(this.game.camera.x-50, this.game.camera.y-50, this.shadowTexture);
    this.lightSprite.blendMode = Phaser.blendModes.MULTIPLY;
    var style = {
      font: 'bold 16px Belgrano',
      fill: '#222288',
      align: 'center',
      backgroundColor: 'rgba(255, 255, 255, 0.2)',
      boundsAlignH: "center",
      boundsAlignV: "middle",
    };
    this.tooltip = this.add.text(this.player.x, this.player.y, '', style);
    this.tooltip.anchor.setTo(0.5, 0.5);

    this.emitterLayer = this.game.add.group();

    // spawn items
    this.items = new Phaser.Group(this.game);
    this.map.spriteLayer.add(this.items);
    if (config.state.items == null)
      config.state.items = {};
    if (config.state.fires == null)
      config.state.fires = {};
    for (var key in config.state.items) {
      var obj = config.state.items[key];
      if (obj != "equipped" && obj.map == this.map.asset) {
       	this.spawnItem(key, obj.x, obj.y);
      }
    }
    for (var key in this.map.allObjects) {
      var obj = this.map.allObjects[key];
      if (obj.type == "item_spawn") {
	if (config.state.items[obj.name] == null) {
	  this.spawnItem(obj.name, obj.x + obj.width/2.0, obj.y+obj.height/2.0);
	}
      } else if (obj.type == "fire_spawn") {
	this.fire = new Fire({
	  game: this.game,
	  x: obj.x + obj.width / 2.0,
	  y: obj.y + obj.height*1.1,
	});
	if (config.state.fires[config.state.map])
	  this.ignite();
	this.items.add(this.fire);
      }
    }
    this.dark = !config.state.fires[config.state.map];

    // spawn monsters
    if (this.dark) {
      this.monsters = new Phaser.Group(this.game);
      this.map.spriteLayer.add(this.monsters);
      for (var key in this.map.allObjects) {
	var monster = this.map.allObjects[key];
	if (monster.type == "monster") {
	  var sprite = new Monster({
	    game: this.game,
	    x: monster.x + monster.width / 2.0,
	    y: monster.y + monster.height / 2.0,
	    info: monster.properties
	  });
	  this.monsters.add(sprite);
	}
      }
    }
  }

  spawnItem(name, x, y) {
    var sprite = new Item({
      game: this.game,
      x: x,
      y: y,
      name: name
    });
    sprite.props = {name: name, type: "item", properties: {tooltip: name}}
    this.items.add(sprite);
    this.emitterLayer.add(sprite.emitter);
    this.updateItemState(sprite);
    return sprite;
  }

  updateItemState(sprite) {
    config.state.items[sprite.props.name] = {
      map: this.map.asset,
      x: sprite.x,
      y: sprite.y
    };
  }

  pickupItem(sprite) {
    if (this.itemPickupCooldown <= 0.0) {
      this.dropItem();
      config.state.equipped = sprite.props.name;
      sprite.destroy();
      config.state.items[sprite.props.name] = "equipped";
      this.itemPickupCooldown = 1.0;
    }
  }

  dropItem() {
    if (config.state.equipped != null) {
      var sprite = this.spawnItem(config.state.equipped, this.player.x, this.player.y);
      sprite.body.velocity.x = this.player.body.velocity.x * 3;
      sprite.body.velocity.y = this.player.body.velocity.y * 2;
      this.game.add.tween(sprite.body.velocity).to({x: 0}, 1200, Phaser.Easing.Linear.None, true);
      config.state.equipped = null;
    }
  }

  ignite() {
    this.fire.ignite();
    config.state.fires[config.state.map] = true;
    this.dark = false;
  }

  render () {
    //game.debug.spriteInfo(this.player, 32, 32);
    //game.debug.text(game.time.fps || '--', 2, 14, "#fff");
    this.game.debug.text(game.time.fps || '--', 2, 14);
  }

  trigger(x, y) {
    if (y.props.type == "exit") {
      this.warp(y.props.properties);
    } else if (y.props.type == "item") {
      if (this.spacebar.isDown) {
	this.pickupItem(y);
      }
    } else if (y.props.type == "door") {
      if (this.spacebar.isDown) {
	this.warp(y.props.properties);
      }
    } else if (y.props.type == "fire") {
      if (this.spacebar.isDown) {
	this.ignite();
      }
    }

    // show tooltip if available
    if (y.props.properties) {
      var tooltip = y.props.properties.tooltip;
      if (tooltip != null) {
	this.tooltip.text = tooltip;
	this.tooltip.x = (y.left + y.right) / 2.0;
	this.tooltip.y = y.bottom - 64;
      }
    }
  }

  warp(props) {
    config.state.map = props.map;
    config.state.entrance = props.entrance;
    this.state.start('Warp');
  }

  getEntranceXY(entrance_name) {
    var entrance = this.map.objectMap[entrance_name];
    return [entrance.x+entrance.width/2.0,
	    entrance.y+entrance.height/2.0]
  }

  pushPlatformPhysics(sprite) {
    if (this.map.properties && this.map.properties.platforms) {
      sprite.body.checkCollision.up = false;
      sprite.body.checkCollision.left = false;
      sprite.body.checkCollision.right = false;
    }
  }

  popPlatformPhysics(sprite) {
    if (this.map.properties && this.map.properties.platforms) {
      sprite.body.checkCollision.up = true;
      sprite.body.checkCollision.left = true;
      sprite.body.checkCollision.right = true;
    }
  }

  update() {
    this.bg.x = (this.camera.x - this.world.width / 2.0) * 0.5 + this.bg.width/2.0;
    this.bg.y = (this.camera.y - this.world.height / 2.0) * 0.5 + this.bg.height/2.0;
    var dt = this.game.time.physicsElapsed;
    if (this.itemPickupCooldown > 0.0)
      this.itemPickupCooldown -= dt;
    this.pushPlatformPhysics(this.player);
    game.physics.arcade.collide([this.player, this.monsters, this.items], this.map.boundaries);
    this.popPlatformPhysics(this.player);
    this.tooltip.text = '';

    this.player.underwater = false;
    for (var idx in this.map.water) {
      var layer = this.map.water[idx];
      var tiles = layer.getTiles(this.player.x - 16, this.player.y - 16 - this.player.height / 2.0, 32, 32);
      this.player.underwater = tiles.filter((x) => x.index != -1).length > 0;
    }

    game.physics.arcade.overlap(this.player, this.items, this.trigger, null, this);
    game.physics.arcade.overlap(this.player, this.map.triggers, this.trigger, null, this);
    game.physics.arcade.overlap(this.player, this.monsters, (x, y) => {this.state.start("GameOver");}, null, this);
    var blocked = this.player.body.blocked.down;
    if (this.cursor.left.isDown) {
      this.player.moveLeft();
    }
    else if (this.cursor.right.isDown) {
      this.player.moveRight();
    }
    else if (blocked) {
      this.player.stop();
    }
    if (this.cursor.up.downDuration(250)) {
      this.player.startJump();
    }
    if (this.cursor.up.isDown) {
      this.player.continueJump();
    }
    if (this.dropkey.isDown) {
      this.dropItem();
    }
    this.lightSprite.reset(game.camera.x-50, game.camera.y-50);
    this.updateShadowTexture();
  }

  updateShadowTexture() {
    if (this.dark) {
      if (!this.map.properties.dark) {
	this.shadowTexture.context.fillStyle = 'rgb(100, 100, 100)';
      } else {
	this.shadowTexture.context.fillStyle = 'rgb(10, 10, 10)';
      }
    } else {
      this.shadowTexture.context.fillStyle = 'rgb(128, 128, 128)';
    }
    this.shadowTexture.context.fillRect(0, 0, this.game.width+100, this.game.height+100);

    var x = this.player.x - this.game.camera.x + 50;
    var y = this.player.y - this.game.camera.y + 50;

    if (config.state.equipped == 'flashlight') {
      this.drawLight(x, y, 150 + game.rnd.integerInRange(1,20), 1.0);
    }
  }

  drawLight(x, y, radius, brightness) {
    var gradient = this.shadowTexture.context.createRadialGradient(
      x, y, 0.0,
      x, y, radius);
    gradient.addColorStop(0, 'rgba(255, 255, 255, ' + brightness + ')');
    gradient.addColorStop(1, 'rgba(255, 255, 200, 0.0)');

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

    this.shadowTexture.dirty = true;
  }
}
<commit_msg>improved style of tooltip text<commit_after>/* globals __DEV__ */
import Phaser from 'phaser'
import Player from '../sprites/Player'
import Monster from '../sprites/Monster'
import Level from '../sprites/Level'
import Item from '../sprites/Item'
import Fire from '../sprites/Fire'

import config from '../config'

export default class extends Phaser.State {
  init () {
    this.stage.backgroundColor = '#000'
  }
  preload () {
  }

  create () {
    this.game.physics.startSystem(Phaser.Physics.ARCADE);
    this.game.time.advancedTiming = true;
    this.itemPickupCooldown = 1.0;

    this.backgroundLayer = this.game.add.group();
    this.map = new Level({
      game: this.game,
      asset: config.state.map
    });

    // background if needed
    this.bg = new Phaser.TileSprite(this.game, 0, 0, this.game.world.width, this.game.world.height, 'starfield');
    this.bg.tilePosition.y += 2;
    this.bg.anchor.setTo(0.5, 0.5);
    this.backgroundLayer.add(this.bg);

    // create and add player
    var entranceXY = this.getEntranceXY(config.state.entrance);
    this.player = new Player({
      game: this.game,
      x: entranceXY[0],
      y: entranceXY[1],
      asset: 'hero'
    })
    this.map.spriteLayer.add(this.player);
    this.game.camera.follow(this.player);

    this.cursor = this.game.input.keyboard.createCursorKeys();
    this.spacebar = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    this.dropkey = this.game.input.keyboard.addKey(Phaser.Keyboard.D);
    this.game.input.keyboard.addKeyCapture([
      Phaser.Keyboard.LEFT,
      Phaser.Keyboard.RIGHT,
      Phaser.Keyboard.UP,
      Phaser.Keyboard.DOWN,
      Phaser.Keyboard.SPACEBAR
    ]);

    this.shadowTexture = this.game.add.bitmapData(this.game.width+100, this.game.height+100);
    this.lightSprite = this.game.add.image(this.game.camera.x-50, this.game.camera.y-50, this.shadowTexture);
    this.lightSprite.blendMode = Phaser.blendModes.MULTIPLY;
    var style = {
      font: 'bold 16px Belgrano',
      fill: '#000',
      align: 'center',
      backgroundColor: 'rgba(255, 255, 255, 0.4)',
      boundsAlignH: "center",
      boundsAlignV: "middle",
    };
    this.tooltip = this.add.text(this.player.x, this.player.y, '', style);
    this.tooltip.anchor.setTo(0.5, 0.5);

    this.emitterLayer = this.game.add.group();

    // spawn items
    this.items = new Phaser.Group(this.game);
    this.map.spriteLayer.add(this.items);
    if (config.state.items == null)
      config.state.items = {};
    if (config.state.fires == null)
      config.state.fires = {};
    for (var key in config.state.items) {
      var obj = config.state.items[key];
      if (obj != "equipped" && obj.map == this.map.asset) {
       	this.spawnItem(key, obj.x, obj.y);
      }
    }
    for (var key in this.map.allObjects) {
      var obj = this.map.allObjects[key];
      if (obj.type == "item_spawn") {
	if (config.state.items[obj.name] == null) {
	  this.spawnItem(obj.name, obj.x + obj.width/2.0, obj.y+obj.height/2.0);
	}
      } else if (obj.type == "fire_spawn") {
	this.fire = new Fire({
	  game: this.game,
	  x: obj.x + obj.width / 2.0,
	  y: obj.y + obj.height*1.1,
	});
	if (config.state.fires[config.state.map])
	  this.ignite();
	this.items.add(this.fire);
      }
    }
    this.dark = !config.state.fires[config.state.map];

    // spawn monsters
    if (this.dark) {
      this.monsters = new Phaser.Group(this.game);
      this.map.spriteLayer.add(this.monsters);
      for (var key in this.map.allObjects) {
	var monster = this.map.allObjects[key];
	if (monster.type == "monster") {
	  var sprite = new Monster({
	    game: this.game,
	    x: monster.x + monster.width / 2.0,
	    y: monster.y + monster.height / 2.0,
	    info: monster.properties
	  });
	  this.monsters.add(sprite);
	}
      }
    }
  }

  spawnItem(name, x, y) {
    var sprite = new Item({
      game: this.game,
      x: x,
      y: y,
      name: name
    });
    sprite.props = {name: name, type: "item", properties: {tooltip: name}}
    this.items.add(sprite);
    this.emitterLayer.add(sprite.emitter);
    this.updateItemState(sprite);
    return sprite;
  }

  updateItemState(sprite) {
    config.state.items[sprite.props.name] = {
      map: this.map.asset,
      x: sprite.x,
      y: sprite.y
    };
  }

  pickupItem(sprite) {
    if (this.itemPickupCooldown <= 0.0) {
      this.dropItem();
      config.state.equipped = sprite.props.name;
      sprite.destroy();
      config.state.items[sprite.props.name] = "equipped";
      this.itemPickupCooldown = 1.0;
    }
  }

  dropItem() {
    if (config.state.equipped != null) {
      var sprite = this.spawnItem(config.state.equipped, this.player.x, this.player.y);
      sprite.body.velocity.x = this.player.body.velocity.x * 3;
      sprite.body.velocity.y = this.player.body.velocity.y * 2;
      this.game.add.tween(sprite.body.velocity).to({x: 0}, 1200, Phaser.Easing.Linear.None, true);
      config.state.equipped = null;
    }
  }

  ignite() {
    this.fire.ignite();
    config.state.fires[config.state.map] = true;
    this.dark = false;
  }

  render () {
    //game.debug.spriteInfo(this.player, 32, 32);
    //game.debug.text(game.time.fps || '--', 2, 14, "#fff");
    this.game.debug.text(game.time.fps || '--', 2, 14);
  }

  trigger(x, y) {
    if (y.props.type == "exit") {
      this.warp(y.props.properties);
    } else if (y.props.type == "item") {
      if (this.spacebar.isDown) {
	this.pickupItem(y);
      }
    } else if (y.props.type == "door") {
      if (this.spacebar.isDown) {
	this.warp(y.props.properties);
      }
    } else if (y.props.type == "fire") {
      if (this.spacebar.isDown) {
	this.ignite();
      }
    }

    // show tooltip if available
    if (y.props.properties) {
      var tooltip = y.props.properties.tooltip;
      if (tooltip != null) {
	this.tooltip.text = tooltip;
	this.tooltip.x = (y.left + y.right) / 2.0;
	this.tooltip.y = y.bottom - 64;
      }
    }
  }

  warp(props) {
    if (props != null && config.levels[props.map] != null) {
      config.state.map = props.map;
      config.state.entrance = props.entrance;
      this.state.start('Warp');
    } else {
      this.tooltip.text = "undeveloped";
      this.tooltip.x = this.camera.x + this.game.width/2.0;
      this.tooltip.y = this.camera.y + this.game.height/2.0;
    }
  }

  getEntranceXY(entrance_name) {
    var entrance = this.map.objectMap[entrance_name];
    return [entrance.x+entrance.width/2.0,
	    entrance.y+entrance.height/2.0]
  }

  pushPlatformPhysics(sprite) {
    if (this.map.properties && this.map.properties.platforms) {
      sprite.body.checkCollision.up = false;
      sprite.body.checkCollision.left = false;
      sprite.body.checkCollision.right = false;
    }
  }

  popPlatformPhysics(sprite) {
    if (this.map.properties && this.map.properties.platforms) {
      sprite.body.checkCollision.up = true;
      sprite.body.checkCollision.left = true;
      sprite.body.checkCollision.right = true;
    }
  }

  update() {
    this.bg.x = (this.camera.x - this.world.width / 2.0) * 0.5 + this.bg.width/2.0;
    this.bg.y = (this.camera.y - this.world.height / 2.0) * 0.5 + this.bg.height/2.0;
    var dt = this.game.time.physicsElapsed;
    if (this.itemPickupCooldown > 0.0)
      this.itemPickupCooldown -= dt;
    this.pushPlatformPhysics(this.player);
    game.physics.arcade.collide([this.player, this.monsters, this.items], this.map.boundaries);
    this.popPlatformPhysics(this.player);
    this.tooltip.text = '';

    this.player.underwater = false;
    for (var idx in this.map.water) {
      var layer = this.map.water[idx];
      var tiles = layer.getTiles(this.player.x - 16, this.player.y - 16 - this.player.height / 2.0, 32, 32);
      this.player.underwater = tiles.filter((x) => x.index != -1).length > 0;
    }

    game.physics.arcade.overlap(this.player, this.items, this.trigger, null, this);
    game.physics.arcade.overlap(this.player, this.map.triggers, this.trigger, null, this);
    game.physics.arcade.overlap(this.player, this.monsters, (x, y) => {this.state.start("GameOver");}, null, this);
    var blocked = this.player.body.blocked.down;
    if (this.cursor.left.isDown) {
      this.player.moveLeft();
    }
    else if (this.cursor.right.isDown) {
      this.player.moveRight();
    }
    else if (blocked) {
      this.player.stop();
    }
    if (this.cursor.up.downDuration(250)) {
      this.player.startJump();
    }
    if (this.cursor.up.isDown) {
      this.player.continueJump();
    }
    if (this.dropkey.isDown) {
      this.dropItem();
    }
    this.lightSprite.reset(game.camera.x-50, game.camera.y-50);
    this.updateShadowTexture();
  }

  updateShadowTexture() {
    if (this.dark) {
      if (!this.map.properties.dark) {
	this.shadowTexture.context.fillStyle = 'rgb(100, 100, 100)';
      } else {
	this.shadowTexture.context.fillStyle = 'rgb(10, 10, 10)';
      }
    } else {
      this.shadowTexture.context.fillStyle = 'rgb(128, 128, 128)';
    }
    this.shadowTexture.context.fillRect(0, 0, this.game.width+100, this.game.height+100);

    var x = this.player.x - this.game.camera.x + 50;
    var y = this.player.y - this.game.camera.y + 50;

    if (config.state.equipped == 'flashlight') {
      this.drawLight(x, y, 150 + game.rnd.integerInRange(1,20), 1.0);
    }
  }

  drawLight(x, y, radius, brightness) {
    var gradient = this.shadowTexture.context.createRadialGradient(
      x, y, 0.0,
      x, y, radius);
    gradient.addColorStop(0, 'rgba(255, 255, 255, ' + brightness + ')');
    gradient.addColorStop(1, 'rgba(255, 255, 200, 0.0)');

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

    this.shadowTexture.dirty = true;
  }
}
<|endoftext|>


<commit_before>(function($) {

	Symphony.Language.add({
		'today': false,
		'yesterday': false,
		'tomorrow': false
	});

	Symphony.DateTime = {

		// Reduce timestamp to days
		reduce: function(timestamp) {
			return Math.floor((this.clearTime(timestamp) + 7200000) / 86400000);
		},

		// Given a timestamp, set the hours and minutes of the resulting
		// date to 0, for use with dates detection
		clearTime: function(timestamp) {
			if(timestamp == '') return timestamp;

			var date = new Date(parseInt(timestamp));
			date.setHours(0);
			date.setMinutes(0);

			return date.getTime();
		}
	};

	/**
	 * The Date and Time extension provides an interface to add
	 * one or more single dates or date ranges to an entry.
	 *
	 * @author: Nils Hörrmann, post@nilshoerrmann.de
	 * @source: http://github.com/nilshoerrmann/datetime
	 */
	$(document).ready(function() {

		// Date and time
		$('div.field-datetime').each(function datetime() {
			var field = $(this),
				help = field.find('i a.help'),
				instructions = field.find('div.help'),
				datetime = field.find('.dark.frame'),
				dates = datetime.find('ol'),
				headers = dates.find('header'),
				width = 0;

		/*---- Events -----------------------------------------------------------*/

			// Destructor
			datetime.on('constructstop.duplicator constructshow.duplicator', 'li', function(event) {
				var item = $(this),
					destructor = item.find('a.destructor');

				if(width < 1) {
					width = destructor.width();
				}

				if(width > 0) {
					item.find('header div').css('margin-right', width + 10);
				}
			});

			// Constructing
			datetime.on('constructshow.duplicator', 'li', function(event) {
				var item = $(this),
					input = item.find('input.start'),
					all = item.prevAll(),
					prev;

				// Prepopulate with previous date, if possible
				if(datetime.is('.prepopulate') && all.length > 0 && !(dates.is('.destructing') && all.length == 1)) {
					prev = all.filter(':first').find('input.start');
					input.val(prev.val()).attr('data-timestamp', prev.attr('data-timestamp'));
				}
			});
			datetime.on('constructstop.duplicator', 'li', function(event) {
				var item = $(this),
					input = item.find('input.start');

				// Store and contextualise date
				input.data('validated', input.val());
				contextualise(input);
			});

			// Visualising
			datetime.on('focus click', 'input', function(event) {
				var input = $(this);

				// Set focus
				datetime.find('.focus').removeClass('focus');
				input.parent().addClass('focus');

				// Visualise
				visualise(input);
			});

			// Setting
			datetime.on('setdate.datetime', 'li', function(event, range, focus, mode) {
				var item = $(this),
					start = item.find('input.start'),
					end = item.find('input.end'),
					from = mergeTimes(start.attr('data-timestamp'), range.start, mode),
					to;

				// Move multiple day range to single day
				if(mode === 'single') {
					to = mergeTimes(start.attr('data-timestamp'), range.end, mode);
				}
				else {
					to = mergeTimes(end.attr('data-timestamp'), range.end, mode);
				}

				// Date range
				if(range.start && range.end) {
					validate(start, from, false);
					validate(end, to, false);
					end.slideDown('fast');
					item.addClass('range');
				}

				// Single date
				else {
					validate(start, from, false);
					empty(end);
					item.removeClass('range');
				}

				// Visualise
				item.trigger('visualise', [{
					start: from,
					end: to
				}, focus]);
			});
			datetime.on('settime.datetime', 'li', function(event, first, last, mode, focus) {
				var item = $(this),
					start = item.find('.start'),
					end = item.find('.end'),
					range = {
						start: null,
						end: null
					},
					from, to;

				// Start time
				from = new Date(parseInt(start.attr('data-timestamp')));
				from.setHours(first.hours);
				from.setMinutes(first.minutes);
				range.start = from.getTime();

				// End time, date range over multiple days
				if(mode == 'multiple' && last != null) {
					to = new Date(parseInt(end.attr('data-timestamp')));
					to.setHours(last.hours);
					to.setMinutes(last.minutes);
					range.end = to.getTime();
				}

				// End time, date range on single day
				else if(mode == 'single' && last != null) {
					to = from;
					to.setHours(last.hours);
					to.setMinutes(last.minutes);
					range.end = to.getTime();
				}

				// Set focus
				if(focus == 'start') {
					focus = range.start;
				}
				else {
					focus = range.end;
				}

				// Visualise
				item.trigger('setdate', [range, focus, mode]);
			});

			// Keypress
			if(!datetime.is('.simple')) {
				datetime.on('keydown.datetime', 'input', function(event) {
					var input = $(this);

					// If tab is pressed while the user is in the first
					// date, allow the focus to shifted to the end date
					// instead of the calendar.
					if(event.which == 9 && !event.shiftKey && input.is('.start')) {
						input.nextAll('input.end').show().focus();
						event.preventDefault();
					}
				});
			}

			// Validating
			datetime.on('blur.datetime', 'input', function(event) {
				var input = $(this),
					date = input.val(),
					validated = input.data('validated');

				// Remove focus
				input.parent().removeClass('focus');

				// Empty date
				if(date == '') {
					empty(input);
				}

				// Validate
				else if(date != validated) {
					validate(input, date, true);
				}
			});

			// Help
			help.on('click.datetime', function(event) {

				// Show help
				if(instructions.is(':hidden')) {
					instructions.slideDown('fast');
					help.text(help.attr('data-hide'));
				}

				// Hide help
				else {
					instructions.slideUp('fast');
					help.text(help.attr('data-show'));
				}
			});

		/*---- Functions --------------------------------------------------------*/

			// Visualise date
			var visualise = function(input) {
				var item = input.parents('li'),
					datespan = input.parent(),
					date = input.attr('data-timestamp'),
					start = datespan.find('input.start').attr('data-timestamp'),
					end = datespan.find('input.end').attr('data-timestamp');

				item.trigger('visualise', [{
					start: start,
					end: end
				}, date]);
			};

			// Validate and set date
			var validate = function(input, date, visualise) {
				var item = input.parents('li'),
					datespan = input.parent(),
					calendar = item.find('div.calendar');

				// Call validator
				if(input.attr('data-timestamp') != date) {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: Symphony.Context.get('root') + '/symphony/extension/datetime/get/',
						data: {
							date: date,
							time: Math.min(calendar.find('.timeline').size(), 1)
						},
						success: function(parsed) {

							// Valid date
							if(parsed.status == 'valid') {
								input.attr('data-timestamp', parsed.timestamp).val(parsed.date).removeClass('invalid');

								// Visualise
								if(visualise === true) {
									item.trigger('visualise', [{
										start: datespan.find('.start').attr('data-timestamp'),
										end: datespan.find('.end').attr('data-timestamp')
									}, input.attr('data-timestamp')]);
								}
							}

							// Invalid date
							else {
								input.attr('data-timestamp', '').addClass('invalid');
								visualise(input);
							}

							// Store date
							input.data('validated', parsed.date);

							// Display status
							displayStatus(datespan);

							// Get date context
							contextualise(input);
						}
					});
				}
			};

			// Merge new date with old times
			var mergeTimes = function(current, update, mode) {

				// Empty date
				if(update == null || update == '') {
					return '';
				}

				// New date
				else if(current == null || current == '') {
					return update;
				}

				// Existing date
				else {
					var time, date

					// Set date, keep time
					if(mode == 'date') {
						time = new Date(parseInt(current)),
						date = new Date(parseInt(update));
					}

					// Set time, keep date
					else {
						time = new Date(parseInt(update)),
						date = new Date(parseInt(current));
					}

					// Set hours and minutes
					date.setHours(time.getHours());
					date.setMinutes(time.getMinutes());

					return date.getTime();
				}
			}

			// Empty date
			var empty = function(input) {
				var item = input.parents('li'),
					datespan = input.parent(),
					end = datespan.find('.end');

				// Empty dates are valid
				input.removeClass('invalid');

				// Merge with end date
				if(input.is('.start') && end.val() != '') {
					input.val(end.val());
					end.val('');

					// Keep errors
					if(end.is('.invalid')) {
						end.removeClass('invalid');
						input.addClass('invalid');
					}
				}

				// Display status
				displayStatus(datespan);

				// Hide end date
				end.attr('data-timestamp', '').val('').slideUp('fast', function() {
					item.removeClass('range');
				});
			};

			// Display validity status
			var displayStatus = function(datespan) {

				// At least one date is invalid
				if(datespan.find('input.invalid').size() > 0) {
					datespan.addClass('invalid');
				}

				// All dates are valid
				else {
					datespan.removeClass('invalid');
				}
			};

			// Get context
			var contextualise = function(input) {
				var datespan = input.parent(),
					time = parseInt(input.attr('data-timestamp')),
					now = new Date(),
					day, today, yesterday, tomorrow, label;

				// Reduze timestamps to days:
				day = Symphony.DateTime.reduce(time);
				today = Symphony.DateTime.reduce(now.getTime());

				// Create label
				if(day == today) {
					label = Symphony.Language.get('today');
				}
				else if(today - day == 1) {
					label = Symphony.Language.get('yesterday');
				}
				else if(day - today == 1) {
					label = Symphony.Language.get('tomorrow');
				}

				// Attach label
				if(label) {
					input.next('em.label').text(label).fadeIn('fast');
				}

				// Detach label
				else {
					input.next('em.label').fadeOut('fast');
				}
			};

		/*---- Initialisation ---------------------------------------------------*/

			// Create calendar and timer
			dates.symphonyCalendar();
			dates.symphonyTimer();

			// Initialise dates
			dates.find('input').each(function() {
				var input = $(this);

				// Store date
				input.data('validated', input.val());

				// Contexualise
				contextualise(input);

				// Visualise calendar once
				if(input.is('.start')) {
					visualise(input);
				}
			}).load();

			// Set errors
			dates.find('input.invalid').parent('div').addClass('invalid');

			// Initialise datetime
			if(!datetime.is('.single')) {

				// Multiple dates
				dates.symphonyDuplicator({
					orderable: false,
					collapsible: false,
					minimum: (datetime.is('.prepopulate') ? 1 : 0),
				});

				// Orderable dates
				datetime.symphonyOrderable({
					items: 'li',
					handles: 'header',
					ignore: ''
				});
			}

			// Collapsible calendar
			datetime.symphonyCollapsible({
					items: 'li',
					handles: 'header',
					ignore: 'input'
				})
				.on('dblclick.datetime', 'input', function toggleAll(event) {

					// Expand/collapse all
					$(this).parent().trigger('dblclick');
				})
				.on('click.datetime', 'input', function toggleInput(event) {
					var input = $(this),
						item = input.parents('li');

					// Expand
					if(item.is('.collapsed')) {
						item.trigger('expand.collapsible');
					}
				});
		});

	});

})(jQuery.noConflict());
<commit_msg>Make sure calendar is opened when navigating by keyboard<commit_after>(function($) {

	Symphony.Language.add({
		'today': false,
		'yesterday': false,
		'tomorrow': false
	});

	Symphony.DateTime = {

		// Reduce timestamp to days
		reduce: function(timestamp) {
			return Math.floor((this.clearTime(timestamp) + 7200000) / 86400000);
		},

		// Given a timestamp, set the hours and minutes of the resulting
		// date to 0, for use with dates detection
		clearTime: function(timestamp) {
			if(timestamp == '') return timestamp;

			var date = new Date(parseInt(timestamp));
			date.setHours(0);
			date.setMinutes(0);

			return date.getTime();
		}
	};

	/**
	 * The Date and Time extension provides an interface to add
	 * one or more single dates or date ranges to an entry.
	 *
	 * @author: Nils Hörrmann, post@nilshoerrmann.de
	 * @source: http://github.com/nilshoerrmann/datetime
	 */
	$(document).ready(function() {

		// Date and time
		$('div.field-datetime').each(function datetime() {
			var field = $(this),
				help = field.find('i a.help'),
				instructions = field.find('div.help'),
				datetime = field.find('.dark.frame'),
				dates = datetime.find('ol'),
				headers = dates.find('header'),
				width = 0;

		/*---- Events -----------------------------------------------------------*/

			// Destructor
			datetime.on('constructstop.duplicator constructshow.duplicator', 'li', function(event) {
				var item = $(this),
					destructor = item.find('a.destructor');

				if(width < 1) {
					width = destructor.width();
				}

				if(width > 0) {
					item.find('header div').css('margin-right', width + 10);
				}
			});

			// Constructing
			datetime.on('constructshow.duplicator', 'li', function(event) {
				var item = $(this),
					input = item.find('input.start'),
					all = item.prevAll(),
					prev;

				// Prepopulate with previous date, if possible
				if(datetime.is('.prepopulate') && all.length > 0 && !(dates.is('.destructing') && all.length == 1)) {
					prev = all.filter(':first').find('input.start');
					input.val(prev.val()).attr('data-timestamp', prev.attr('data-timestamp'));
				}
			});
			datetime.on('constructstop.duplicator', 'li', function(event) {
				var item = $(this),
					input = item.find('input.start');

				// Store and contextualise date
				input.data('validated', input.val());
				contextualise(input);
			});

			// Visualising
			datetime.on('focus click', 'input', function(event) {
				var input = $(this);

				// Set focus
				datetime.find('.focus').removeClass('focus');
				input.parent().addClass('focus');

				// Visualise
				visualise(input);
			});

			// Setting
			datetime.on('setdate.datetime', 'li', function(event, range, focus, mode) {
				var item = $(this),
					start = item.find('input.start'),
					end = item.find('input.end'),
					from = mergeTimes(start.attr('data-timestamp'), range.start, mode),
					to;

				// Move multiple day range to single day
				if(mode === 'single') {
					to = mergeTimes(start.attr('data-timestamp'), range.end, mode);
				}
				else {
					to = mergeTimes(end.attr('data-timestamp'), range.end, mode);
				}

				// Date range
				if(range.start && range.end) {
					validate(start, from, false);
					validate(end, to, false);
					end.slideDown('fast');
					item.addClass('range');
				}

				// Single date
				else {
					validate(start, from, false);
					empty(end);
					item.removeClass('range');
				}

				// Visualise
				item.trigger('visualise', [{
					start: from,
					end: to
				}, focus]);
			});
			datetime.on('settime.datetime', 'li', function(event, first, last, mode, focus) {
				var item = $(this),
					start = item.find('.start'),
					end = item.find('.end'),
					range = {
						start: null,
						end: null
					},
					from, to;

				// Start time
				from = new Date(parseInt(start.attr('data-timestamp')));
				from.setHours(first.hours);
				from.setMinutes(first.minutes);
				range.start = from.getTime();

				// End time, date range over multiple days
				if(mode == 'multiple' && last != null) {
					to = new Date(parseInt(end.attr('data-timestamp')));
					to.setHours(last.hours);
					to.setMinutes(last.minutes);
					range.end = to.getTime();
				}

				// End time, date range on single day
				else if(mode == 'single' && last != null) {
					to = from;
					to.setHours(last.hours);
					to.setMinutes(last.minutes);
					range.end = to.getTime();
				}

				// Set focus
				if(focus == 'start') {
					focus = range.start;
				}
				else {
					focus = range.end;
				}

				// Visualise
				item.trigger('setdate', [range, focus, mode]);
			});

			// Keypress
			if(!datetime.is('.simple')) {
				datetime.on('keydown.datetime', 'input', function(event) {
					var input = $(this);

					// Tab key
					if(event.which == 9 && !event.shiftKey && input.is('.start')) {
						var item = input.parents('li');

						event.preventDefault();

						// Show end date
						input.nextAll('input.end').show().focus();

						// Expand calendar
						if(item.is('.collapsed')) {
							item.trigger('expand.collapsible');
						}
					}
				});
			}

			// Validating
			datetime.on('blur.datetime', 'input', function(event) {
				var input = $(this),
					date = input.val(),
					validated = input.data('validated');

				// Remove focus
				input.parent().removeClass('focus');

				// Empty date
				if(date == '') {
					empty(input);
				}

				// Validate
				else if(date != validated) {
					validate(input, date, true);
				}
			});

			// Help
			help.on('click.datetime', function(event) {

				// Show help
				if(instructions.is(':hidden')) {
					instructions.slideDown('fast');
					help.text(help.attr('data-hide'));
				}

				// Hide help
				else {
					instructions.slideUp('fast');
					help.text(help.attr('data-show'));
				}
			});

		/*---- Functions --------------------------------------------------------*/

			// Visualise date
			var visualise = function(input) {
				var item = input.parents('li'),
					datespan = input.parent(),
					date = input.attr('data-timestamp'),
					start = datespan.find('input.start').attr('data-timestamp'),
					end = datespan.find('input.end').attr('data-timestamp');

				item.trigger('visualise', [{
					start: start,
					end: end
				}, date]);
			};

			// Validate and set date
			var validate = function(input, date, visualise) {
				var item = input.parents('li'),
					datespan = input.parent(),
					calendar = item.find('div.calendar');

				// Call validator
				if(input.attr('data-timestamp') != date) {
					$.ajax({
						type: 'GET',
						dataType: 'json',
						url: Symphony.Context.get('root') + '/symphony/extension/datetime/get/',
						data: {
							date: date,
							time: Math.min(calendar.find('.timeline').size(), 1)
						},
						success: function(parsed) {

							// Valid date
							if(parsed.status == 'valid') {
								input.attr('data-timestamp', parsed.timestamp).val(parsed.date).removeClass('invalid');

								// Visualise
								if(visualise === true) {
									item.trigger('visualise', [{
										start: datespan.find('.start').attr('data-timestamp'),
										end: datespan.find('.end').attr('data-timestamp')
									}, input.attr('data-timestamp')]);
								}
							}

							// Invalid date
							else {
								input.attr('data-timestamp', '').addClass('invalid');
								visualise(input);
							}

							// Store date
							input.data('validated', parsed.date);

							// Display status
							displayStatus(datespan);

							// Get date context
							contextualise(input);
						}
					});
				}
			};

			// Merge new date with old times
			var mergeTimes = function(current, update, mode) {

				// Empty date
				if(update == null || update == '') {
					return '';
				}

				// New date
				else if(current == null || current == '') {
					return update;
				}

				// Existing date
				else {
					var time, date

					// Set date, keep time
					if(mode == 'date') {
						time = new Date(parseInt(current)),
						date = new Date(parseInt(update));
					}

					// Set time, keep date
					else {
						time = new Date(parseInt(update)),
						date = new Date(parseInt(current));
					}

					// Set hours and minutes
					date.setHours(time.getHours());
					date.setMinutes(time.getMinutes());

					return date.getTime();
				}
			}

			// Empty date
			var empty = function(input) {
				var item = input.parents('li'),
					datespan = input.parent(),
					end = datespan.find('.end');

				// Empty dates are valid
				input.removeClass('invalid');

				// Merge with end date
				if(input.is('.start') && end.val() != '') {
					input.val(end.val());
					end.val('');

					// Keep errors
					if(end.is('.invalid')) {
						end.removeClass('invalid');
						input.addClass('invalid');
					}
				}

				// Display status
				displayStatus(datespan);

				// Hide end date
				end.attr('data-timestamp', '').val('').slideUp('fast', function() {
					item.removeClass('range');
				});
			};

			// Display validity status
			var displayStatus = function(datespan) {

				// At least one date is invalid
				if(datespan.find('input.invalid').size() > 0) {
					datespan.addClass('invalid');
				}

				// All dates are valid
				else {
					datespan.removeClass('invalid');
				}
			};

			// Get context
			var contextualise = function(input) {
				var datespan = input.parent(),
					time = parseInt(input.attr('data-timestamp')),
					now = new Date(),
					day, today, yesterday, tomorrow, label;

				// Reduze timestamps to days:
				day = Symphony.DateTime.reduce(time);
				today = Symphony.DateTime.reduce(now.getTime());

				// Create label
				if(day == today) {
					label = Symphony.Language.get('today');
				}
				else if(today - day == 1) {
					label = Symphony.Language.get('yesterday');
				}
				else if(day - today == 1) {
					label = Symphony.Language.get('tomorrow');
				}

				// Attach label
				if(label) {
					input.next('em.label').text(label).fadeIn('fast');
				}

				// Detach label
				else {
					input.next('em.label').fadeOut('fast');
				}
			};

		/*---- Initialisation ---------------------------------------------------*/

			// Create calendar and timer
			dates.symphonyCalendar();
			dates.symphonyTimer();

			// Initialise dates
			dates.find('input').each(function() {
				var input = $(this);

				// Store date
				input.data('validated', input.val());

				// Contexualise
				contextualise(input);

				// Visualise calendar once
				if(input.is('.start')) {
					visualise(input);
				}
			}).load();

			// Set errors
			dates.find('input.invalid').parent('div').addClass('invalid');

			// Initialise datetime
			if(!datetime.is('.single')) {

				// Multiple dates
				dates.symphonyDuplicator({
					orderable: false,
					collapsible: false,
					minimum: (datetime.is('.prepopulate') ? 1 : 0),
				});

				// Orderable dates
				datetime.symphonyOrderable({
					items: 'li',
					handles: 'header',
					ignore: ''
				});
			}

			// Collapsible calendar
			datetime.symphonyCollapsible({
					items: 'li',
					handles: 'header',
					ignore: 'input'
				})
				.on('dblclick.datetime', 'input', function toggleAll(event) {

					// Expand/collapse all
					$(this).parent().trigger('dblclick');
				})
				.on('click.datetime', 'input', function toggleInput(event) {
					var input = $(this),
						item = input.parents('li');

					// Expand
					if(item.is('.collapsed')) {
						item.trigger('expand.collapsible');
					}
				});
		});

	});

})(jQuery.noConflict());
<|endoftext|>


<commit_before>// ==========================================================================
// GDS Functions
// ==========================================================================

// Show/Hide content

function ShowHideContent() {
  var self = this;
  self.showHideRadioToggledContent = function () {
    $(".block-label input[type='radio']").each(function () {

      var $radio = $(this);
      var $radioGroupName = $radio.attr('name');
      var $radioLabel = $radio.parent('label');

      var dataTarget = $radioLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (dataTarget) {

        // Set aria-controls
        $radio.attr('aria-controls', dataTarget);

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $radio.closest('form').find(".block-label input[name=" + $radioGroupName + "]").each(function () {
            var $this = $(this);

            var groupDataTarget = $this.parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.hide();
            // Set aria-expanded and aria-hidden for hidden content
            $this.attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

          var $dataTarget = $('#' + dataTarget);
          $dataTarget.show();
          // Set aria-expanded and aria-hidden for clicked radio
          $radio.attr('aria-expanded', 'true');
          $dataTarget.attr('aria-hidden', 'false');

        });

      } else {
        // If the data-target attribute is undefined for a radio button,
        // hide visible data-target content for radio buttons in the same group

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $(".block-label input[name=" + $radioGroupName + "]").each(function () {

            var groupDataTarget = $(this).parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.hide();
            // Set aria-expanded and aria-hidden for hidden content
            $(this).attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

        });
      }

    });
  }
  self.showHideCheckboxToggledContent = function () {

    $(".block-label input[type='checkbox']").each(function() {

      var $checkbox = $(this);
      var $checkboxLabel = $(this).parent();

      var $dataTarget = $checkboxLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

        // Set aria-controls
        $checkbox.attr('aria-controls', $dataTarget);

        // Set aria-expanded and aria-hidden
        $checkbox.attr('aria-expanded', 'false');
        $('#'+$dataTarget).attr('aria-hidden', 'true');

        // For checkboxes revealing hidden content
        $checkbox.on('click', function() {

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          // Toggle hidden content
          $('#'+$dataTarget).toggle();

          // Update aria-expanded and aria-hidden attributes
          $(this).attr('aria-expanded', state);
          $('#'+$dataTarget).attr('aria-hidden', !state);

        });
      }

    });
  }
}

$(document).ready(function() {

  // Turn off jQuery animation
  jQuery.fx.off = true;

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Where .block-label uses the data-target attribute
  // to toggle hidden content
  var toggleContent = new ShowHideContent();
  toggleContent.showHideRadioToggledContent();
  toggleContent.showHideCheckboxToggledContent();

});

// ==========================================================================
// Rural Payments Functions
// ==========================================================================

// Show Dialog

function showDialog() {

  var dialogData = {
    lastFocus : null
  }

  if ($('.dialog').length > 0) {

    // Open dialog

    $('a[data-toggle=dialog]').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      var anchor = $(this)

      var data = '#' + anchor.attr('data-target');

      openDialog(data, anchor); // Pass data value into function

    });

    // Open dialog

    function openDialog(data, anchor) {
      dialogData.lastFocus = anchor;

      var dialog = $(data);
      dialog.attr('aria-hidden', 'false')
          .find('.dialog-content').focus()
          .attr('tabindex', '-1');

      dialog.trap();
    }

    // Close dialog only if visible

    function closeDialog() {
      var dialog = $('.dialog[aria-hidden=false]')

      dialog.attr('aria-hidden', 'true')
          .find('.dialog-content').blur()
          .attr('tabindex', '0');

      dialog.untrap();

      dialogData.lastFocus.focus();
      dialogData.lastFocus.blur();
    }

    // Stop bubbling

    $('.dialog-holder').on('click', function (e) {

      e.stopPropagation();

    });

    $('.dialog-close').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      closeDialog();

    });

    $('.dialog-cancel').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      closeDialog();

    });

    // Document binding events

    $(document).bind({

      click: function (e) {

        closeDialog();

      },

      keyup: function (e) {

          if (e.keyCode == 27) {

            closeDialog();

          }

      }

    });

  }

};

// Toggle tabs

function toggleTabs() {

  if ($('.tabs').length>0) {

    $('.tabs:not(pre .tabs)').tabs();

  }

};

// Table sortable

function tableSortable() {

  if ($('.js-table-sortable').length > 0) {

    var min = 4;

    $('.js-table-sortable').each(function() {

      $this = $(this);

      var rows = $this.find('tbody tr').length;

      if (rows >= min) {
        $this.find('thead [data-sort]').addClass('sortable'); // add classes for link styling purposes
        $this.stupidtable(); // initiate plugin
      }

    });

  }

};

// Multiple checkboxes

function formMultipleCheckboxes() {

  if ($('.form-checkboxes').length > 0) {

    $('.form-checkboxes > li').on('click', function(event) {

      var target   = $(event.target);
      var checkbox = $(this).find("input[type='checkbox']");

      if (target.is("input[type='checkbox']")) {

        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          $(this).removeClass('focused');
        } else {
          $(this).addClass('selected');
          $(this).addClass('focused');
        }

        return;

      }

      event.preventDefault();

      if (!checkbox.prop('checked')) {

        $(this).addClass('selected');
        $(this).addClass('focused');

        checkbox.prop('checked', true);

      } else {

        $(this).removeClass('selected');
        $(this).removeClass('focused');

        checkbox.prop('checked', false);

      }

    });

  }

};

// Form validation

function formValidation() {

  $('.validation-list a[href^="#"]').on('click', function(e) {

    e.preventDefault();

    // Declare variables
    var link = $(this),
        id   = link.attr('href');

    // Get focus
    $(id).focus();

    // Smooth movement to error
    $('html, body').animate({

      scrollTop: ($(id).offset().top) - 20

    }, 500);

  });

};

// Collapsibles

function collapsibles() {

  $('.collapsible .collapsible-item').each(function() {

      var code = $(this).closest('.language-markup');

      // Do not run funtion if inside language markup (Not to be used in production)
      if (!code.hasClass('language-markup')) {

        // Variables
        var $this    = $(this),
            $header  = $(this).find('.collapsible-heading h3'),
            $content = $(this).find('.collapsible-content');

        // Create a unique ID
        var $id = 'collapsible-' + $(this).index();

        // Add button inside $header
        $header.wrapInner('<button aria-expanded="false" aria-controls="' + $id + '">');
        var $button = $header.children('button');

        // Add attributes to collapsible content
        $content.attr({
          'id' : $id,
          'aria-hidden' : true,
          'style' : 'display: none;'
        });

        // Toggle state
        $button.on('click', function(e) {

          e.preventDefault();

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          $button.attr('aria-expanded', state);
          $content.attr('aria-hidden', !state).toggle();

        });

      }

  });

};

// Toggle

function toggleContent() {

  $('.toggle').each(function(index) {

    // Variables
    var $link    = $(this).find('.toggle-link'),
        $content = $(this).find('.toggle-content'),
        $id      = 'toggle-' + (index ++);

    // Add attributes to toggler link
    $link.attr('aria-controls', $id).attr({
      'aria-expanded' : false
    });

    // Add attributes to toggle content
    $content.attr({
      'id' : $id,
      'aria-hidden' : true,
      'style' : 'display: none;'
    });

    // Toggle state
    $link.on('click', function(e) {

      e.preventDefault();

      var state = $(this).attr('aria-expanded') === 'false' ? true : false;

      $link.attr('aria-expanded', state);
      $content.attr('aria-hidden', !state).toggle();

    });

  });

};

// Sole trader details

function soleTraderDetails() {

  if ($('#form-sole-trader-details').length>0) {

    // Declare variables

    var businessOwner = $('#business-owner'),
        firstName     = $('#first-name'),
        lastName      = $('#last-name'),
        email         = $('#email');

    // Detect changes on interaction

    businessOwner.change(function() {

      var checkButtonHasValue = false;

      if(this.checked) {

        checkButtonHasValue = true;

        firstName.val('Sydney').attr('disabled', 'disabled');
        lastName.val('Bechett').attr('disabled', 'disabled');
        email.val('defra-user-1@kainos.com').attr('disabled', 'disabled');

        return false;

      } else {

        $('#form-sole-trader-details').find('input').val('').removeAttr('disabled'); // Clear form values and remvoe disabled attributes

      }

    });

  }

};

// Confirm sole trader details

function confirmSoleTraderDetails() {

  if ($('#form-confirm-sole-trader-details').length>0) {

    // Declare my variables

    var form     = $("#form-confirm-sole-trader-details"),
        button   = form.find('.button'),
        check    = form.find('input:checkbox');

    // Detect changes on interaction

    check.change(function() {

      var checkButtonHasValue = false;

      if(this.checked) {

        checkButtonHasValue = true;

        button.removeAttr('disabled');

        return false;

      } else {

        button.attr('disabled', 'disabled');

      }

    });

  }

};

// Land query

function landQuery() {

  if ($('#form-land-query').length>0) {

    // Declare my variables

    var form   = $("#form-land-query"),
        button = form.find('.button'),
        radio  = form.find('input:radio');

    // Detect changes on interaction

    radio.change(function() {

      var radioButtonHasValue = false;

      radio.each(function() {

        if(this.checked) {

          radioButtonHasValue = true;

          return false;

        }

      });

      // Enabled button

      if (radioButtonHasValue) {

        button.removeAttr('disabled');

      }

      // Submit the form

      $('button[type=submit]').on('click', function(e) {

        e.preventDefault();

        if ($('#radio-1').is(':checked')) {

            window.location.href = "query-sbi";

          } else {

           window.location.href = "query";

        }

      });

    });

  }

};

// Inline edit

function inlineEdit() {

  if ($('.js-inline-edit').length>0) {

    // Toggle details

    $('.toggle-details').on('click', function(e) {

      e.preventDefault();

      var parent = $(this).closest('tbody');

      if ((parent).hasClass('open')) {

        $(this).text('Show');
        parent.removeAttr('class', 'open');

      } else {

        $(this).text('Hide');
        parent.addClass('open');

      }

    });

    // Inline editing

    $('.inline-edit').on('click', function(e) {

      e.preventDefault();

      var parent = $(this).closest('tr');
      var value = parent.find('.inline-value');
      var input = parent.find('.inline-input');

      if ((input).hasClass('js-hidden')) {

        $(this).text('Save');
        input.removeClass('js-hidden');
        value.addClass('js-hidden');

      } else {

        $(this).text('Edit');
        value.removeClass('js-hidden');
        input.addClass('js-hidden');

      }

    });

  }

};

// Clickable table rows

function clickableTableRows() {

  if ($('.js-table-rows-clickable').length>0) {

    var tableRow = $('.js-table-rows-clickable tbody tr');

    $(tableRow).on('click', function() {

      if ( $(this).data('link')) {

        window.document.location = $(this).data('link'); // Go to link

      }

    });

  }

};

// Document ready

(function() {
  toggleTabs();
  formValidation();
  formMultipleCheckboxes();
  showDialog();
  collapsibles();
  toggleContent();
  tableSortable();
  landQuery();
  inlineEdit();
  soleTraderDetails();
  confirmSoleTraderDetails();
  clickableTableRows();
})();

<commit_msg>Disabled JS function for populating form fields for sole trader details<commit_after>// ==========================================================================
// GDS Functions
// ==========================================================================

// Show/Hide content

function ShowHideContent() {
  var self = this;
  self.showHideRadioToggledContent = function () {
    $(".block-label input[type='radio']").each(function () {

      var $radio = $(this);
      var $radioGroupName = $radio.attr('name');
      var $radioLabel = $radio.parent('label');

      var dataTarget = $radioLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (dataTarget) {

        // Set aria-controls
        $radio.attr('aria-controls', dataTarget);

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $radio.closest('form').find(".block-label input[name=" + $radioGroupName + "]").each(function () {
            var $this = $(this);

            var groupDataTarget = $this.parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.hide();
            // Set aria-expanded and aria-hidden for hidden content
            $this.attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

          var $dataTarget = $('#' + dataTarget);
          $dataTarget.show();
          // Set aria-expanded and aria-hidden for clicked radio
          $radio.attr('aria-expanded', 'true');
          $dataTarget.attr('aria-hidden', 'false');

        });

      } else {
        // If the data-target attribute is undefined for a radio button,
        // hide visible data-target content for radio buttons in the same group

        $radio.on('click', function () {

          // Select radio buttons in the same group
          $(".block-label input[name=" + $radioGroupName + "]").each(function () {

            var groupDataTarget = $(this).parent('label').attr('data-target');
            var $groupDataTarget = $('#' + groupDataTarget);

            // Hide toggled content
            $groupDataTarget.hide();
            // Set aria-expanded and aria-hidden for hidden content
            $(this).attr('aria-expanded', 'false');
            $groupDataTarget.attr('aria-hidden', 'true');
          });

        });
      }

    });
  }
  self.showHideCheckboxToggledContent = function () {

    $(".block-label input[type='checkbox']").each(function() {

      var $checkbox = $(this);
      var $checkboxLabel = $(this).parent();

      var $dataTarget = $checkboxLabel.attr('data-target');

      // Add ARIA attributes

      // If the data-target attribute is defined
      if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) {

        // Set aria-controls
        $checkbox.attr('aria-controls', $dataTarget);

        // Set aria-expanded and aria-hidden
        $checkbox.attr('aria-expanded', 'false');
        $('#'+$dataTarget).attr('aria-hidden', 'true');

        // For checkboxes revealing hidden content
        $checkbox.on('click', function() {

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          // Toggle hidden content
          $('#'+$dataTarget).toggle();

          // Update aria-expanded and aria-hidden attributes
          $(this).attr('aria-expanded', state);
          $('#'+$dataTarget).attr('aria-hidden', !state);

        });
      }

    });
  }
}

$(document).ready(function() {

  // Turn off jQuery animation
  jQuery.fx.off = true;

  // Use GOV.UK selection-buttons.js to set selected
  // and focused states for block labels
  var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']");
  new GOVUK.SelectionButtons($blockLabels);

  // Details/summary polyfill
  // See /javascripts/vendor/details.polyfill.js

  // Where .block-label uses the data-target attribute
  // to toggle hidden content
  var toggleContent = new ShowHideContent();
  toggleContent.showHideRadioToggledContent();
  toggleContent.showHideCheckboxToggledContent();

});

// ==========================================================================
// Rural Payments Functions
// ==========================================================================

// Show Dialog

function showDialog() {

  var dialogData = {
    lastFocus : null
  }

  if ($('.dialog').length > 0) {

    // Open dialog

    $('a[data-toggle=dialog]').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      var anchor = $(this)

      var data = '#' + anchor.attr('data-target');

      openDialog(data, anchor); // Pass data value into function

    });

    // Open dialog

    function openDialog(data, anchor) {
      dialogData.lastFocus = anchor;

      var dialog = $(data);
      dialog.attr('aria-hidden', 'false')
          .find('.dialog-content').focus()
          .attr('tabindex', '-1');

      dialog.trap();
    }

    // Close dialog only if visible

    function closeDialog() {
      var dialog = $('.dialog[aria-hidden=false]')

      dialog.attr('aria-hidden', 'true')
          .find('.dialog-content').blur()
          .attr('tabindex', '0');

      dialog.untrap();

      dialogData.lastFocus.focus();
      dialogData.lastFocus.blur();
    }

    // Stop bubbling

    $('.dialog-holder').on('click', function (e) {

      e.stopPropagation();

    });

    $('.dialog-close').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      closeDialog();

    });

    $('.dialog-cancel').on('click', function (e) {

      e.preventDefault();
      e.stopPropagation();

      closeDialog();

    });

    // Document binding events

    $(document).bind({

      click: function (e) {

        closeDialog();

      },

      keyup: function (e) {

          if (e.keyCode == 27) {

            closeDialog();

          }

      }

    });

  }

};

// Toggle tabs

function toggleTabs() {

  if ($('.tabs').length>0) {

    $('.tabs:not(pre .tabs)').tabs();

  }

};

// Table sortable

function tableSortable() {

  if ($('.js-table-sortable').length > 0) {

    var min = 4;

    $('.js-table-sortable').each(function() {

      $this = $(this);

      var rows = $this.find('tbody tr').length;

      if (rows >= min) {
        $this.find('thead [data-sort]').addClass('sortable'); // add classes for link styling purposes
        $this.stupidtable(); // initiate plugin
      }

    });

  }

};

// Multiple checkboxes

function formMultipleCheckboxes() {

  if ($('.form-checkboxes').length > 0) {

    $('.form-checkboxes > li').on('click', function(event) {

      var target   = $(event.target);
      var checkbox = $(this).find("input[type='checkbox']");

      if (target.is("input[type='checkbox']")) {

        if ($(this).hasClass('selected')) {
          $(this).removeClass('selected');
          $(this).removeClass('focused');
        } else {
          $(this).addClass('selected');
          $(this).addClass('focused');
        }

        return;

      }

      event.preventDefault();

      if (!checkbox.prop('checked')) {

        $(this).addClass('selected');
        $(this).addClass('focused');

        checkbox.prop('checked', true);

      } else {

        $(this).removeClass('selected');
        $(this).removeClass('focused');

        checkbox.prop('checked', false);

      }

    });

  }

};

// Form validation

function formValidation() {

  $('.validation-list a[href^="#"]').on('click', function(e) {

    e.preventDefault();

    // Declare variables
    var link = $(this),
        id   = link.attr('href');

    // Get focus
    $(id).focus();

    // Smooth movement to error
    $('html, body').animate({

      scrollTop: ($(id).offset().top) - 20

    }, 500);

  });

};

// Collapsibles

function collapsibles() {

  $('.collapsible .collapsible-item').each(function() {

      var code = $(this).closest('.language-markup');

      // Do not run funtion if inside language markup (Not to be used in production)
      if (!code.hasClass('language-markup')) {

        // Variables
        var $this    = $(this),
            $header  = $(this).find('.collapsible-heading h3'),
            $content = $(this).find('.collapsible-content');

        // Create a unique ID
        var $id = 'collapsible-' + $(this).index();

        // Add button inside $header
        $header.wrapInner('<button aria-expanded="false" aria-controls="' + $id + '">');
        var $button = $header.children('button');

        // Add attributes to collapsible content
        $content.attr({
          'id' : $id,
          'aria-hidden' : true,
          'style' : 'display: none;'
        });

        // Toggle state
        $button.on('click', function(e) {

          e.preventDefault();

          var state = $(this).attr('aria-expanded') === 'false' ? true : false;

          $button.attr('aria-expanded', state);
          $content.attr('aria-hidden', !state).toggle();

        });

      }

  });

};

// Toggle

function toggleContent() {

  $('.toggle').each(function(index) {

    // Variables
    var $link    = $(this).find('.toggle-link'),
        $content = $(this).find('.toggle-content'),
        $id      = 'toggle-' + (index ++);

    // Add attributes to toggler link
    $link.attr('aria-controls', $id).attr({
      'aria-expanded' : false
    });

    // Add attributes to toggle content
    $content.attr({
      'id' : $id,
      'aria-hidden' : true,
      'style' : 'display: none;'
    });

    // Toggle state
    $link.on('click', function(e) {

      e.preventDefault();

      var state = $(this).attr('aria-expanded') === 'false' ? true : false;

      $link.attr('aria-expanded', state);
      $content.attr('aria-hidden', !state).toggle();

    });

  });

};

// Sole trader details

function soleTraderDetails() {

  if ($('#form-sole-trader-details').length>0) {

    // Declare variables

    var businessOwner = $('#business-owner'),
        firstName     = $('#first-name'),
        lastName      = $('#last-name'),
        email         = $('#email');

    // Detect changes on interaction

    businessOwner.change(function() {

      var checkButtonHasValue = false;

      if(this.checked) {

        checkButtonHasValue = true;

        firstName.val('Sydney').attr('disabled', 'disabled');
        lastName.val('Bechett').attr('disabled', 'disabled');
        email.val('defra-user-1@kainos.com').attr('disabled', 'disabled');

        return false;

      } else {

        $('#form-sole-trader-details').find('input').val('').removeAttr('disabled'); // Clear form values and remvoe disabled attributes

      }

    });

  }

};

// Confirm sole trader details

function confirmSoleTraderDetails() {

  if ($('#form-confirm-sole-trader-details').length>0) {

    // Declare my variables

    var form     = $("#form-confirm-sole-trader-details"),
        button   = form.find('.button'),
        check    = form.find('input:checkbox');

    // Detect changes on interaction

    check.change(function() {

      var checkButtonHasValue = false;

      if(this.checked) {

        checkButtonHasValue = true;

        button.removeAttr('disabled');

        return false;

      } else {

        button.attr('disabled', 'disabled');

      }

    });

  }

};

// Land query

function landQuery() {

  if ($('#form-land-query').length>0) {

    // Declare my variables

    var form   = $("#form-land-query"),
        button = form.find('.button'),
        radio  = form.find('input:radio');

    // Detect changes on interaction

    radio.change(function() {

      var radioButtonHasValue = false;

      radio.each(function() {

        if(this.checked) {

          radioButtonHasValue = true;

          return false;

        }

      });

      // Enabled button

      if (radioButtonHasValue) {

        button.removeAttr('disabled');

      }

      // Submit the form

      $('button[type=submit]').on('click', function(e) {

        e.preventDefault();

        if ($('#radio-1').is(':checked')) {

            window.location.href = "query-sbi";

          } else {

           window.location.href = "query";

        }

      });

    });

  }

};

// Inline edit

function inlineEdit() {

  if ($('.js-inline-edit').length>0) {

    // Toggle details

    $('.toggle-details').on('click', function(e) {

      e.preventDefault();

      var parent = $(this).closest('tbody');

      if ((parent).hasClass('open')) {

        $(this).text('Show');
        parent.removeAttr('class', 'open');

      } else {

        $(this).text('Hide');
        parent.addClass('open');

      }

    });

    // Inline editing

    $('.inline-edit').on('click', function(e) {

      e.preventDefault();

      var parent = $(this).closest('tr');
      var value = parent.find('.inline-value');
      var input = parent.find('.inline-input');

      if ((input).hasClass('js-hidden')) {

        $(this).text('Save');
        input.removeClass('js-hidden');
        value.addClass('js-hidden');

      } else {

        $(this).text('Edit');
        value.removeClass('js-hidden');
        input.addClass('js-hidden');

      }

    });

  }

};

// Clickable table rows

function clickableTableRows() {

  if ($('.js-table-rows-clickable').length>0) {

    var tableRow = $('.js-table-rows-clickable tbody tr');

    $(tableRow).on('click', function() {

      if ( $(this).data('link')) {

        window.document.location = $(this).data('link'); // Go to link

      }

    });

  }

};

// Document ready

(function() {
  toggleTabs();
  formValidation();
  formMultipleCheckboxes();
  showDialog();
  collapsibles();
  toggleContent();
  tableSortable();
  landQuery();
  inlineEdit();
  //soleTraderDetails();
  confirmSoleTraderDetails();
  clickableTableRows();
})();

<|endoftext|>


<commit_before>/*  MoST Subtitle Player :: Implementation Overview

Code is inserted into the target web page, making syncing possible.

Subtitles are downloaded via DownSub (but we could have used the api).

A transparent overlay is created as a div using Zepto; see addOverlay.

*/

// Tip: Use the 'debugger' command to insert a breakpoint!

/*  Developer's notes (strange behavior)

In order to access the global variable 'player' at Viki when debugging using
Chrome's Developer Tools, the 'Elements' tab must be active.

*/

// One subtitle writer for each language.
var writers = [];

$(document).ready(function () {

    function init(message, sender, callback) {
        clean();

        // Initiate communication.
        startSync();
        addOverlay(message.style);
        writers = [];
        for (var i = 0; i < message.languages.length; i++) {
            var srt = message.subtitles[message.languages[i]];
            //debugger;
            writers[i] = new Writer(message.languages[i], srt);
            writers[i].play();
        }
    }

    chrome.extension.onMessage.addListener(init);

});

function clean() {
    // Stop the old "instance" if there is one.
    for (var i = 0; i < writers.length; i++) {
        writers[i].stop();
    }

    //$(".most-subtitles").remove();
    $("#most-overlay").remove();
}

function Writer(language, srt) {
    // The decoded srt file is organized into pages.
    this.pages = parseSubtitles(srt);
    this.current;

    // Text is continuously written as html.
    this.element = document.createElement("div");
    this.element.className = "most-subtitles most-" + language;
    $("#most-overlay")[0].appendChild(this.element);

    this.timer;

    this.play = function () {
        this.timer = true;

        var that = this;

        // To be run many times per second.
        function updateRepeatedly() {
            var period = 50;  // sleep time between updates

            // Get the local playback time (in milliseconds, starting at 0).
            var syncEl = document.getElementById("most-sync");
            var local = new Date().getTime() - parseInt(syncEl.innerHTML);

            // Write current subtitle page to screen.
            for (var i = 0; i < that.pages.length; i++) {  // TODO binary search?
                var page = that.pages[i];
                // the " + period" here is just for fine tuning, not optimal
                if (page['loc0'] <= local + period
                        && local + period <= page['loc1']
                        && that.current != i) {
                    that.show(page['s'], page['loc1']-local, i);
                }
            }

            // Reschedule, creating an infinite loop.
            if (that.timer) {
                that.timer = window.setTimeout(updateRepeatedly, period);
            }
        };

        updateRepeatedly();
    }

    this.stop = function() {
        this.timer = false;
    }

    // Show text, typically a subtitle page.
    this.show = function(text, duration, uid) {
        // Remove old text. (This is an exceptional case.)
        if (this.current !== undefined) {
            this.hide(this.current);
        }

        // Write the text to screen.
        var textEl = document.createElement("div");
        textEl.className = "uid_" + uid;
        textEl.innerHTML = text;
        this.element.appendChild(textEl);

        // Don't rewrite it a lot.
        this.current = uid;

        // Remember to remove it after a while.
        var that = this;
        window.setTimeout(function () {
            if (that.current === uid) {
                that.hide(uid);
                that.current = undefined;
            }
        }, duration);
    }

    // Hide text. Inverse of 'show'.
    this.hide = function(uid) {
        $(".uid_" + uid).remove();
    }

    this.show("Loaded " + this.pages.length + " pages.", 2000, "info");

    //debugger;

}

// Ugly hack independent of this scope (only its string will be injected).
function specialCode () {
    // Will hold the unix time minus local playback time (in milliseconds).
    $("body").append("

");

    // Determine how the target player will tell its current position
    // (in seconds).
    var getCurrentTime = function() {
        // look for the regular player, subtitle editor (flash or html5)
        if ("player" in window) {
            return player.getCurrentTime();
        }
        if ("subber_player_flash_api" in window) {
            return subber_player_flash_api.player.currentTime();
        }
        if ("subber_player" in window) {
            return subber_player.player.currentTime();
        }
    }

    // Export this position continuously in html format (using the DOM).
    function syncForever() {
        var local = Math.round(getCurrentTime() * 1000);
        var syncVal = new Date().getTime() - local;
        document.getElementById("most-sync").innerHTML = syncVal;
        window.setTimeout(syncForever, 100);
    };

    syncForever();
}

function startSync() {
    // Inject the ugly hack into the web page.
    var script = document.createElement('script');
    script.appendChild(document.createTextNode(
        '('+ specialCode +')();'));
    (document.body || document.head || document.documentElement)
        .appendChild(script);
}

function addOverlay(style) {
    // Create the overlay
    overlay = $("

");
    $("body").append(overlay);

    // Find the positioning of the video player, or use (bad) defaults.
    var video = $("#flashObject")[0] || $("#subber_player")[0];
    var videoRect = video ? video.getBoundingClientRect()
                          : {'width': 600, 'left': 20, 'bottom': 20};

    // Configure the looks and position.
    /*
    shadow = "0 0 black";  // transparent text shadow:
    for (var i=-1; i<=1; i++) for (var j=-1; j<=1; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 1), " + shadow;
    for (var i=-2; i<=2; i++) for (var j=-2; j<=2; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 0.4), " + shadow;
    for (var i=-3; i<=3; i++) for (var j=-3; j<=3; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 0.1), " + shadow;
    */

    overlay.css({
        position: "fixed",
        width: videoRect.width + "px",
        height: videoRect.height + "px",
        left: videoRect.left,
        top: videoRect.top,
        //background: "rgba(255, 150, 0, 0.5)",
        zIndex: "99999999",
        pointerEvents: "none",
        textAlign: "center"
    });

    // Set the subtitle style
    var styleEl = document.createElement("style");
    styleEl.innerHTML = style;
    $("head").append(styleEl);
}

// Convert an srt time string to integer.
function strToMs(loc) {
    var h, m, s, ms;
    [h, m, s, ms] = loc.replace(',', ':').split(':');
    [h, m, s, ms] = [parseInt(h), parseInt(m), parseInt(s), parseInt(ms)];
    return ((h*60 + m)*60 + s)*1000 + ms;
}

// Turn an srt into computation-friendly form: pages.
function parseSubtitles(srt) {
    var pages = [];

    var srt2 = srt.replace(/\r\n|\r|\n/g, '\n')  // Normalize newlines.
                  .trim(srt)
                  .split('\n\n');

    // Parse each page.
    for (var i = 0; i < srt2.length; i++) {
        var a, b, c, d, e, loc0, loc1;
        a = srt2[i];
        [b, c] = [a.slice(0, a.indexOf("\n")), a.slice(a.indexOf("\n")+1)];
        [d, e] = [c.slice(0, c.indexOf("\n")), c.slice(c.indexOf("\n")+1)];
        [loc0, loc1] = d.split(" --> ");

        // The following line improves security but comes at the cost of
        // not supporting arbitrary html markup.
        e = e.replace(/<\/?[^>]+(>|$)/g, function(part) {
            var accept = ['', '', '
', '
', '', ''];
            for (var i = 0; i < accept.length; i++) {
                if (part === accept[i]) return part;
            }
            return "";
        });

        pages.push({'loc0': strToMs(loc0), 'loc1': strToMs(loc1), 's': e});
    }

    return pages;
}

<commit_msg>Fix hide bug when paused<commit_after>/*  MoST Subtitle Player :: Implementation Overview

Code is inserted into the target web page, making syncing possible.

Subtitles are downloaded via DownSub (but we could have used the api).

A transparent overlay is created as a div using Zepto; see addOverlay.

*/

// Tip: Use the 'debugger' command to insert a breakpoint!

/*  Developer's notes (strange behavior)

In order to access the global variable 'player' at Viki when debugging using
Chrome's Developer Tools, the 'Elements' tab must be active.

*/

// One subtitle writer for each language.
var writers = [];

$(document).ready(function () {

    function init(message, sender, callback) {
        clean();

        // Initiate communication.
        startSync();
        addOverlay(message.style);
        writers = [];
        for (var i = 0; i < message.languages.length; i++) {
            var srt = message.subtitles[message.languages[i]];
            //debugger;
            writers[i] = new Writer(message.languages[i], srt);
            writers[i].play();
        }
    }

    chrome.extension.onMessage.addListener(init);

});

function clean() {
    // Stop the old "instance" if there is one.
    for (var i = 0; i < writers.length; i++) {
        writers[i].stop();
    }

    //$(".most-subtitles").remove();
    $("#most-overlay").remove();
}

function Writer(language, srt) {
    // The decoded srt file is organized into pages.
    this.pages = parseSubtitles(srt);
    this.current;

    // Text is continuously written as html.
    this.element = document.createElement("div");
    this.element.className = "most-subtitles most-" + language;
    $("#most-overlay")[0].appendChild(this.element);

    this.timer;

    this.play = function () {
        this.timer = true;

        var that = this;

        // To be run many times per second.
        function updateRepeatedly() {
            var period = 50;  // sleep time between updates

            // Get the local playback time (in milliseconds, starting at 0).
            var syncEl = document.getElementById("most-sync");
            var local = new Date().getTime() - parseInt(syncEl.innerHTML);

            // Write current subtitle page to screen.
            for (var i = 0; i < that.pages.length; i++) {  // TODO binary search?
                var page = that.pages[i];
                // the " + period" here is just for fine tuning, not optimal
                if (page['loc0'] <= local + period
                        && local + period <= page['loc1']
                        && that.current != i) {
                    that.show(page['s'], page['loc1']-local, language + "-" + i);
                }
            }

            // Reschedule, creating an infinite loop.
            if (that.timer) {
                that.timer = window.setTimeout(updateRepeatedly, period);
            }
        };

        updateRepeatedly();
    }

    this.stop = function() {
        this.timer = false;
    }

    // Show text, typically a subtitle page.
    this.show = function(text, duration, uid) {
        // Remove old text. (This is an exceptional case.)
        if (this.current !== undefined) {
            this.hide(this.current);
        }

        // Write the text to screen.
        var textEl = document.createElement("div");
        textEl.className = "uid-" + uid;
        textEl.innerHTML = text;
        this.element.appendChild(textEl);

        // Don't rewrite it a lot.
        this.current = uid;

        // Remember to remove it after a while.
        var that = this;
        window.setTimeout(function () {  // TODO: don't remove it if paused.
            if (that.current === uid) {
                that.hide(uid);
                that.current = undefined;
            }
        }, duration);
    }

    // Hide text. Inverse of 'show'.
    this.hide = function(uid) {
        $(".uid-" + uid).remove();
    }

    this.show("Loaded " + this.pages.length + " pages.", 2000, language + "-info");

    //debugger;

}

// Ugly hack independent of this scope (only its string will be injected).
function specialCode () {
    // Will hold the unix time minus local playback time (in milliseconds).
    $("body").append("

");

    // Determine how the target player will tell its current position
    // (in seconds).
    var getCurrentTime = function() {
        // look for the regular player, subtitle editor (flash or html5)
        if ("player" in window) {
            return player.getCurrentTime();
        }
        if ("subber_player_flash_api" in window) {
            return subber_player_flash_api.player.currentTime();
        }
        if ("subber_player" in window) {
            return subber_player.player.currentTime();
        }
    }

    // Export this position continuously in html format (using the DOM).
    function syncForever() {
        var local = Math.round(getCurrentTime() * 1000);
        var syncVal = new Date().getTime() - local;
        document.getElementById("most-sync").innerHTML = syncVal;
        window.setTimeout(syncForever, 100);
    };

    syncForever();
}

function startSync() {
    // Inject the ugly hack into the web page.
    var script = document.createElement('script');
    script.appendChild(document.createTextNode(
        '('+ specialCode +')();'));
    (document.body || document.head || document.documentElement)
        .appendChild(script);
}

function addOverlay(style) {
    // Create the overlay
    overlay = $("

");
    $("body").append(overlay);

    // Find the positioning of the video player, or use (bad) defaults.
    var video = $("#flashObject")[0] || $("#subber_player")[0];
    var videoRect = video ? video.getBoundingClientRect()
                          : {'width': 600, 'left': 20, 'bottom': 20};

    // Configure the looks and position.
    /*
    shadow = "0 0 black";  // transparent text shadow:
    for (var i=-1; i<=1; i++) for (var j=-1; j<=1; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 1), " + shadow;
    for (var i=-2; i<=2; i++) for (var j=-2; j<=2; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 0.4), " + shadow;
    for (var i=-3; i<=3; i++) for (var j=-3; j<=3; j++)
        shadow = i + "px " + j + "px rgba(0, 0, 0, 0.1), " + shadow;
    */

    overlay.css({
        position: "fixed",
        width: videoRect.width + "px",
        height: videoRect.height + "px",
        left: videoRect.left,
        top: videoRect.top,
        //background: "rgba(255, 150, 0, 0.5)",
        zIndex: "99999999",
        pointerEvents: "none",
        textAlign: "center"
    });

    // Set the subtitle style
    var styleEl = document.createElement("style");
    styleEl.innerHTML = style;
    $("head").append(styleEl);
}

// Convert an srt time string to integer.
function strToMs(loc) {
    var h, m, s, ms;
    [h, m, s, ms] = loc.replace(',', ':').split(':');
    [h, m, s, ms] = [parseInt(h), parseInt(m), parseInt(s), parseInt(ms)];
    return ((h*60 + m)*60 + s)*1000 + ms;
}

// Turn an srt into computation-friendly form: pages.
function parseSubtitles(srt) {
    var pages = [];

    var srt2 = srt.replace(/\r\n|\r|\n/g, '\n')  // Normalize newlines.
                  .trim(srt)
                  .split('\n\n');

    // Parse each page.
    for (var i = 0; i < srt2.length; i++) {
        var a, b, c, d, e, loc0, loc1;
        a = srt2[i];
        [b, c] = [a.slice(0, a.indexOf("\n")), a.slice(a.indexOf("\n")+1)];
        [d, e] = [c.slice(0, c.indexOf("\n")), c.slice(c.indexOf("\n")+1)];
        [loc0, loc1] = d.split(" --> ");

        // The following line improves security but comes at the cost of
        // not supporting arbitrary html markup.
        e = e.replace(/<\/?[^>]+(>|$)/g, function(part) {
            var accept = ['', '', '
', '
', '', ''];
            for (var i = 0; i < accept.length; i++) {
                if (part === accept[i]) return part;
            }
            return "";
        });

        pages.push({'loc0': strToMs(loc0), 'loc1': strToMs(loc1), 's': e});
    }

    return pages;
}

<|endoftext|>