<commit_before>document.addEventListener("deviceready", function() {
	console.log(window.plugin)
	window.plugin.backgroundMode.enable()
})

var BLE = {}

BLE.init = function() {
	BLE.createBeaconRegion()
	BLE.createDelegate()
	cordova.plugins.locationManager.setDelegate(BLE.delegate)
	cordova.plugins.locationManager.requestWhenInUseAuthorization()
	cordova.plugins.locationManager.startMonitoringForRegion(BLE.beaconRegion).fail(console.error).done()
}

BLE.error = console.log.bind(console)

BLE.createDelegate = function() {

	BLE.delegate = new cordova.plugins.locationManager.Delegate().implement({

	    didDetermineStateForRegion: function (pluginResult) {

	        console.log('[DOM] didDetermineStateForRegion: ' + JSON.stringify(pluginResult))

	        cordova.plugins.locationManager.appendToDeviceLog('[DOM] didDetermineStateForRegion: ' + JSON.stringify(pluginResult))
	    },

	    didStartMonitoringForRegion: function (pluginResult) {
	        console.log('didStartMonitoringForRegion:', pluginResult)

	        console.log('didStartMonitoringForRegion:' + JSON.stringify(pluginResult))
	    },

	    didRangeBeaconsInRegion: function (pluginResult) {
	        console.log('[DOM] didRangeBeaconsInRegion: ' + JSON.stringify(pluginResult))
	    }
	})
}

BLE.createBeaconRegion = function() {
    var uuid = 'DA5336AE-2042-453A-A57F-F80DD34DFCD9',
    	identifier = 'beaconAtTheMacBooks'
    	// minor = 1000, // optional, defaults to wildcard if left empty
    	// major = 5 // optional, defaults to wildcard if left empty

    BLE.beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid, major, minor)
}<commit_msg>Stupid fix<commit_after>document.addEventListener("deviceready", function() {
	console.log(window.plugin)
	window.plugin.backgroundMode.enable()
})

var BLE = {}

BLE.init = function() {
	BLE.createBeaconRegion()
	BLE.createDelegate()
	cordova.plugins.locationManager.setDelegate(BLE.delegate)
	cordova.plugins.locationManager.requestWhenInUseAuthorization()
	cordova.plugins.locationManager.startMonitoringForRegion(BLE.beaconRegion).fail(console.error).done()
}

BLE.error = console.log.bind(console)

BLE.createDelegate = function() {

	BLE.delegate = new cordova.plugins.locationManager.Delegate().implement({

	    didDetermineStateForRegion: function (pluginResult) {

	        alert('[DOM] didDetermineStateForRegion: ' + JSON.stringify(pluginResult))

	        cordova.plugins.locationManager.appendToDeviceLog('[DOM] didDetermineStateForRegion: ' + JSON.stringify(pluginResult))
	    },

	    didStartMonitoringForRegion: function (pluginResult) {
	        console.log('didStartMonitoringForRegion:', pluginResult)

	        alert('didStartMonitoringForRegion:' + JSON.stringify(pluginResult))
	    },

	    didRangeBeaconsInRegion: function (pluginResult) {
	        alert('[DOM] didRangeBeaconsInRegion: ' + JSON.stringify(pluginResult))
	    }
	})
}

BLE.createBeaconRegion = function() {
    var uuid = 'DA5336AE-2042-453A-A57F-F80DD34DFCD9',
    	identifier = 'beaconAtTheMacBooks'
    	// minor = 1000, // optional, defaults to wildcard if left empty
    	// major = 5 // optional, defaults to wildcard if left empty

    BLE.beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid, major, minor)
}<|endoftext|>


<commit_before>//All working 23/2/15 - 3pm
var restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    server = restify.createServer({
        name: "localr"
    }),
    uuid = require('node-uuid'),
    getDetails = require("./getDetails.js"),
    checkin = require("./checkin.js"),
    register = require("./register.js");
// Setting server dependancys
server.use(restify.CORS({
    origins: ['*'], // defaults to ['*']
    credentials: true, // defaults to false
    headers: ['authorization', 'content-type', 'accept', 'origin'],
    methods: ['GET', 'PUT', 'POST', 'HEAD', 'DELETE'] // sets expose-headers
}));
server.use(restify.bodyParser());
server.use(restify.queryParser());
server.use(restify.authorizationParser());
restify.CORS.ALLOW_HEADERS.push('authorization');
// Creating Server
server.listen(8080, function() {
    var users = "/users",
        business = "/business";
    console.log('Incoming request being handled.');
    // Get details for user
    server.get({path: users + "/get"}, function(req, res, next) {
        getDetails.getDetails(req, res, next, 'users');
    });
    // Get details for business
    server.get({path: business + "/get"}, function(req, res, next) {
        getDetails.getDetails(req, res, next, 'business');
    });
    //Register a new user just a simple check if it exists if not, adding by creating the json and pushing it to couchdb
    server.put({path: users + "/register"}, function(req, res, next) {
        register.register(req, res, next, 'users');
    });
    // Register business.
    server.put({path: business + "/register"}, function(req, res, next){
        register.register(req, res, next, 'business');
    });
    // The way this works is by having there name in at the moment e.g DOMAIN/checkin?user=USERNAME&location=7817587295719 This will then add 10 points at the moment
    server.put({path: users + "/checkin"}, function(req, res, next) {
        checkin.checkin(req,res,next);
    });
});<commit_msg>path test<commit_after>//All working 23/2/15 - 3pm
var restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    server = restify.createServer({
        name: "localr"
    }),
    uuid = require('node-uuid'),
    getDetails = require("./getDetails.js"),
    checkin = require("./checkin.js"),
    register = require("./register.js");
// Setting server dependancys
server.use(restify.CORS({
    origins: ['*'], // defaults to ['*']
    credentials: true, // defaults to false
    headers: ['authorization', 'content-type', 'accept', 'origin'],
    methods: ['GET', 'PUT', 'POST', 'HEAD', 'DELETE'] // sets expose-headers
}));
server.use(restify.bodyParser());
server.use(restify.queryParser());
server.use(restify.authorizationParser());
restify.CORS.ALLOW_HEADERS.push('authorization');
// Creating Server
server.listen(8080, function() {
    var users = "/users",
        business = "/business";
    console.log('Incoming request being handled.');
    // Get details for user
    server.get("/users/get", function(req, res, next) {
        getDetails.getDetails(req, res, next, 'users');
    });
    // Get details for business
    server.get({path: business + "/get"}, function(req, res, next) {
        getDetails.getDetails(req, res, next, 'business');
    });
    //Register a new user just a simple check if it exists if not, adding by creating the json and pushing it to couchdb
    server.put({path: users + "/register"}, function(req, res, next) {
        register.register(req, res, next, 'users');
    });
    // Register business.
    server.put({path: business + "/register"}, function(req, res, next){
        register.register(req, res, next, 'business');
    });
    // The way this works is by having there name in at the moment e.g DOMAIN/checkin?user=USERNAME&location=7817587295719 This will then add 10 points at the moment
    server.put({path: users + "/checkin"}, function(req, res, next) {
        checkin.checkin(req,res,next);
    });
});<|endoftext|>


<commit_before>const planets = ['Mercury', 'Venus', 'Moon', 'Mars', 'Ceres', 'Jupiter', 'Io', 'Europa', 'Ganymede', 'Callisto', 'Saturn', 'Enceladus', 'Titan', 'Hyperion', 'Phoebe', 'Uranus', 'Oberon', 'Titania', 'Neptune', 'Pluto', 'Charon', 'Canceron', 'Aquaria', 'Caprica', 'Virgon', 'Leonis', 'Picon', 'Scorpia', 'Aerelon', 'Gemenon', 'Libris', 'Sagittaron', 'Tauron', 'Ragnar', 'Kobol', 'Feros', 'Tuchanka', 'Elaaden', 'Noveria', 'Virmire', 'Ilos', 'Palaven', 'Menae', 'Rannoch', 'Thessia', 'Namakli', 'Illium', 'Tatooine', 'Hoth', 'Endor', 'Coruscant', 'Alderaan', 'Naboo', 'Anoat', 'Bespin', 'Corellia', 'Dagobah', 'Dantooine', 'Geonosis', 'Jakku', 'Kamino', 'Kessel', 'Yavin', 'Jedha', 'Scarif', 'Mustafar', 'Eros', 'Lusitania', 'Ariel', 'Beaumonde', 'Hera', 'Persephone', 'Whitefall', 'Sihnon', 'Solaris', 'Arrakis', 'Caladan', 'Kaitain', 'Giedi Prime', 'Cybertron', 'K-PAX', 'Nirn', 'Omega', 'Citadel', 'Pandora', 'Triton', 'Rhea', 'Umbriel', 'Miranda', 'Proteus', 'Galatea'];
const colors = ['Amber', 'Amethyst', 'Aquamarine', 'Awesome', 'Azure', 'Begonia', 'Beige', 'Black', 'Blue', 'Bronze', 'Brown', 'Burgundy', 'Canary', 'Cherry', 'Coral', 'Cyan', 'Emerald', 'Gold', 'Green', 'Indigo', 'Jade', 'Magenta', 'Mint', 'Mustard', 'Navy', 'Olive', 'Opal', 'Orange', 'Pink', 'Pistachio', 'Red', 'Rose', 'Ruby', 'Salmon', 'Sapphire', 'Scarlet', 'Sepia', 'Silver', 'Turquoise', 'Ultramarine', 'Vermilion', 'Violet', 'White', 'Yellow'];

export function tableNameByAddress(address) {
  const planetIdx = parseInt(address.substr(9, 8), 16) % planets.length;
  const colorIdx = parseInt(address.substr(12, 6), 16) % colors.length;

  return `${colors[colorIdx]} ${planets[planetIdx]}`;
}
<commit_msg>Gold → Golden for tableName<commit_after>const planets = ['Mercury', 'Venus', 'Moon', 'Mars', 'Ceres', 'Jupiter', 'Io', 'Europa', 'Ganymede', 'Callisto', 'Saturn', 'Enceladus', 'Titan', 'Hyperion', 'Phoebe', 'Uranus', 'Oberon', 'Titania', 'Neptune', 'Pluto', 'Charon', 'Canceron', 'Aquaria', 'Caprica', 'Virgon', 'Leonis', 'Picon', 'Scorpia', 'Aerelon', 'Gemenon', 'Libris', 'Sagittaron', 'Tauron', 'Ragnar', 'Kobol', 'Feros', 'Tuchanka', 'Elaaden', 'Noveria', 'Virmire', 'Ilos', 'Palaven', 'Menae', 'Rannoch', 'Thessia', 'Namakli', 'Illium', 'Tatooine', 'Hoth', 'Endor', 'Coruscant', 'Alderaan', 'Naboo', 'Anoat', 'Bespin', 'Corellia', 'Dagobah', 'Dantooine', 'Geonosis', 'Jakku', 'Kamino', 'Kessel', 'Yavin', 'Jedha', 'Scarif', 'Mustafar', 'Eros', 'Lusitania', 'Ariel', 'Beaumonde', 'Hera', 'Persephone', 'Whitefall', 'Sihnon', 'Solaris', 'Arrakis', 'Caladan', 'Kaitain', 'Giedi Prime', 'Cybertron', 'K-PAX', 'Nirn', 'Omega', 'Citadel', 'Pandora', 'Triton', 'Rhea', 'Umbriel', 'Miranda', 'Proteus', 'Galatea'];
const colors = ['Amber', 'Amethyst', 'Aquamarine', 'Awesome', 'Azure', 'Begonia', 'Beige', 'Black', 'Blue', 'Bronze', 'Brown', 'Burgundy', 'Canary', 'Cherry', 'Coral', 'Cyan', 'Emerald', 'Golden', 'Green', 'Indigo', 'Jade', 'Magenta', 'Mint', 'Mustard', 'Navy', 'Olive', 'Opal', 'Orange', 'Pink', 'Pistachio', 'Red', 'Rose', 'Ruby', 'Salmon', 'Sapphire', 'Scarlet', 'Sepia', 'Silver', 'Turquoise', 'Ultramarine', 'Vermilion', 'Violet', 'White', 'Yellow'];

export function tableNameByAddress(address) {
  const planetIdx = parseInt(address.substr(9, 8), 16) % planets.length;
  const colorIdx = parseInt(address.substr(12, 6), 16) % colors.length;

  return `${colors[colorIdx]} ${planets[planetIdx]}`;
}
<|endoftext|>


<commit_before>var es = require('event-stream');
var gutil = require('gulp-util');
var browserify = require('browserify');
var path = require('path');

module.exports = function(opts) {
  if(!opts) opts = {};
  var ctrOpts = {};
  var buffer = [];
  var temp = [];
  var bundler = '';

  function endStream() {
    if (buffer.length === 0) return this.emit('end');
    var self = this;

    buffer.map(function (file) {
      if (gutil.isNull(file.contents)) return cb(null, file); // pass along
      if (gutil.isStream(file.contents)) {
        ctrOpts.entries = file.contents;
      }
      if(gutil.isBuffer(file.contents)) {
        temp.push(file.contents);
        ctrOpts.entries = es.readArray(temp);
      }
      ctrOpts.basedir = file.base;

      bundler = browserify(ctrOpts);
      bundler.on('error', function(){
        throw err;
      });

      if(opts.transform) {
        opts.transform.forEach(bundler.transform);
      }

      self.emit('prebundle', bundler);

      bundler.bundle(opts).pipe(es.wait(function(err, src){
        var newFile = new gutil.File({
          cwd: file.cwd,
          base: file.base,
          contents: new Buffer(src)
        });

        self.emit('postbundle', src);
        self.emit('data', newFile);
        self.emit('end');
      }));
    });
  }
  return es.through(buffer.push.bind(buffer), endStream);
};<commit_msg>error reporting<commit_after>var es = require('event-stream');
var gutil = require('gulp-util');
var browserify = require('browserify');
var path = require('path');

module.exports = function(opts) {
  if(!opts) opts = {};
  var ctrOpts = {};
  var buffer = [];
  var temp = [];
  var bundler = '';

  function endStream() {
    if (buffer.length === 0) return this.emit('end');
    var self = this;

    buffer.map(function (file) {
      if (gutil.isNull(file.contents)) return cb(null, file); // pass along
      if (gutil.isStream(file.contents)) {
        ctrOpts.entries = file.contents;
      }
      if(gutil.isBuffer(file.contents)) {
        temp.push(file.contents);
        ctrOpts.entries = es.readArray(temp);
      }
      ctrOpts.basedir = file.base;

      bundler = browserify(ctrOpts);
      bundler.on('error', self.emit.bind(this, 'error'));

      if(opts.transform) {
        opts.transform.forEach(bundler.transform);
      }

      self.emit('prebundle', bundler);

      bundler.bundle(opts).pipe(es.wait(function(err, src){
        var newFile = new gutil.File({
          cwd: file.cwd,
          base: file.base,
          contents: new Buffer(src)
        });

        self.emit('postbundle', src);
        self.emit('data', newFile);
        self.emit('end');
      }));
    });
  }
  return es.through(buffer.push.bind(buffer), endStream);
};<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    assign = require('object-assign'),
    AppDispatcher = require('../dispatcher/AppDispatcher'),
    AppConstants = require('../constants/AppConstants');

var _currentEvent = {name: '', location: ''};
var _observations = [];

var EventDetailStore = assign({}, EventEmitter.prototype, {
  getCurrentEvent: function() {
    return _currentEvent;
  },

  getAllObservations: function() {
    return _observations;
  },

  /**
   * Trigger an event
   * @param {string} eventName The name of the event
   */
  emitEvent: function(eventName) {
    this.emit(eventName);
  },

  /**
   * Register a callback to invoke when an event is triggered
   * @param {string} eventName The name of the event
   * @param {function} callback The callback function to invoke when the event is triggered
   */
  addEventListener: function(eventName, callback) {
    this.on(eventName, callback);
  },

  /**
   * Prevent a callback from being invoked when an event is triggered
   * @param {string} eventName The name of the event
   * @param {function} callback Stops the callback function from being invoked when the event is triggered
   */
  removeEventListener: function(eventName, callback) {
    this.removeListener(eventName, callback);
  }
});

// Register callback to handle all updates
AppDispatcher.register(function(payload) {
  switch(payload.actionType) {

    // Set the current event from data coming from the payload
    // then emit an edit event from EventDetailStore which will update
    // any components listening to it
    case AppConstants.EVENT_EDIT:
      _currentEvent = payload.event;
      EventDetailStore.emitEvent('edit');
      break;

    // Set the current event
    case AppConstants.UPDATE_CURRENT_EVENT:
      _currentEvent = payload.event;
      EventDetailStore.emitEvent('update-current-event');
      break;

    default:
      // no op
  }
});

module.exports = EventDetailStore;
<commit_msg>Fixed event name<commit_after>var EventEmitter = require('events').EventEmitter,
    assign = require('object-assign'),
    AppDispatcher = require('../dispatcher/AppDispatcher'),
    AppConstants = require('../constants/AppConstants');

var _currentEvent = {name: '', location: ''};
var _observations = [];

var EventDetailStore = assign({}, EventEmitter.prototype, {
  getCurrentEvent: function() {
    return _currentEvent;
  },

  getAllObservations: function() {
    return _observations;
  },

  /**
   * Trigger an event
   * @param {string} eventName The name of the event
   */
  emitEvent: function(eventName) {
    this.emit(eventName);
  },

  /**
   * Register a callback to invoke when an event is triggered
   * @param {string} eventName The name of the event
   * @param {function} callback The callback function to invoke when the event is triggered
   */
  addEventListener: function(eventName, callback) {
    this.on(eventName, callback);
  },

  /**
   * Prevent a callback from being invoked when an event is triggered
   * @param {string} eventName The name of the event
   * @param {function} callback Stops the callback function from being invoked when the event is triggered
   */
  removeEventListener: function(eventName, callback) {
    this.removeListener(eventName, callback);
  }
});

// Register callback to handle all updates
AppDispatcher.register(function(payload) {
  switch(payload.actionType) {

    // Set the current event from data coming from the payload
    // then emit an edit event from EventDetailStore which will update
    // any components listening to it
    case AppConstants.EVENT_EDIT:
      _currentEvent = payload.event;
      EventDetailStore.emitEvent('edit');
      break;

    // Set the current event
    case AppConstants.UPDATE_CURRENT_EVENT:
      _currentEvent = payload.event;
      EventDetailStore.emitEvent('updateCurrentEvent');
      break;

    default:
      // no op
  }
});

module.exports = EventDetailStore;
<|endoftext|>


<commit_before>'use strict';

/**
 * @class
 * @augments {HumanEntity}
 * @augments {LivingEntity}
 * @augments {OfflinePlayer}
 */

var Player = new Class( function ( bukkitObject ) {

	var rawMethods = bukkitObject.getClass().getMethods();

	for ( var i in this ) {
		this[ i ] = this[ i ].bind( bukkitObject );
	}

	for ( var i in rawMethods ) {
		var method = rawMethods[ i ].getName().toString();

		if ( !( method in this ) ) {
			this[ method ] = function ( /* arguments */ ) {

				var args = [];

				for ( var key in arguments ) {
					args.push( 'arguments[ "' + key + '" ]' );
				}

				return eval( 'bukkitObject[ this ]( ' + args.join() + ' );' );
			}.bind( method );
		}
	}
} );

Player.extends( require( './HumanEntity.js' ) );
Player.extends( require( './LivingEntity.js' ) );
Player.extends( require( './OfflinePlayer.js' ) );

/**
 * Gets the Location where this player will respawn.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getSpawnLocation = function () {

	var location;

	var Location = require( './Location.js' );

	var location = this.getBedSpawnLocation();

	if ( location ) {
		location = new Location( location );

	} else {
		location = new Location( this.getWorld().getSpawnLocation() );
	}

	return location;
};

/**
 * Get this players previously set compass target.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getCompassTarget = function () {

	var Location = require( './Location.js' );

	return new Location( this.getCompassTarget() );
};

/**
 * Gets this current players location.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getLocation = function () {

	var Location = require( './Location.js' );

	return new Location( this.getLocation() );
};

/**
 * Changes this players current location to the target location.
 * @implements Player
 * @param {Location} location
 */

Player.prototype.setLocation = function ( location ) {

	var errors = [];

	if ( location.x === undefined ) {
		errors.push( 'x is undefined' );
	}

	if ( location.y === undefined ) {
		errors.push( 'y is undefined' );
	}

	if ( location.z === undefined ) {
		errors.push( 'z is undefined' );
	}

	if ( errors.length ) {
		throw new Error( 'Error in (Player.js).setLocation( ' + JSON.stringify( location ) +' ): ' + errors );
	}

	var playerLocation = this.getLocation();

	var world;

	if ( location.world ) {
		world = org.bukkit.Bukkit.getWorld( location.world );

	} else {
		world = playerLocation.getWorld();
	}

	var bukkitLocation = new org.bukkit.Location(
		world,
		location.x     || playerLocation.getX(),
		location.y     || playerLocation.getY(),
		location.z     || playerLocation.getZ(),
		location.yaw   || playerLocation.getYaw(),
		location.pitch || playerLocation.getPitch()
	);

	this.teleport( bukkitLocation );
};

/**
 * Gets if this player is online or not.
 * @implements Player
 * @return {boolean}
 */

Player.prototype.isOnline = function () {

	return this.isOnline();
};

/**
 * Says a message as this player.
 * @implements Player
 * @param {String} message
 * @example
 * player.chat( 'hi!' );
 */

Player.prototype.chat = function ( message ) {

	if ( message.match( /^\// ) ) {
		message = ''.reset() + message;
	}

	this.chat( message );
};

/**
 * Runs a command as this player.
 * @implements Player
 * @param {String} command
 * @example
 * player.run( '/command' );
 */

Player.prototype.run = function ( command ) {

	this.performCommand( command.replace( /^\//, '' ) );
};

/**
 * Gets this players IP address.
 * @implements Player
 * @return {String} ip
 * @example
 * var ip = player.getIp;
 */

Player.prototype.getIp = function () {

	return this.getAddress().getHostName();
};

/**
 * Gets if this player is allowed to fly or not currently.
 * @implements Player
 * @return {Boolean} canFly
 * @example
 * var canFly = player.canFly();
 */

Player.prototype.canFly = function () {

	return this.getAllowFlight();
};

/**
 * Gets the display name of this player.
 * @implements Player
 * @return {String} displayName
 * @example
 * var displayName = player.getDisplayName();
 */

Player.prototype.getDisplayName = function () {

	return this.getDisplayName();
};

/**
 * Returns true if the player's time is relative to the server time, otherwise the player's time is absolute and will not change its current time unless done so with setTime().
 * @implements Player
 * @return {Boolean}
 * @example
 * var timeRelative = player.isTimeRelative();
 */

Player.prototype.isTimeRelative = function () {

	return this.isPlayerTimeRelative();
};

/**
 * Restores the normal condition where the player's time is synchronized with the server time.
 * @implements Player
 * @example
 * player.resetTime();
 */

Player.prototype.resetTime = function () {

	this.resetPlayerTime();
};

/**
 * Sets the current time on the player's client. The time will be kept synchronized to its world time with the specified offset.
 * @param {Number} time
 * @implements Player
 * @example
 * player.setTime( 1000 );
 */

Player.prototype.setTime = function ( time ) {

	this.setPlayerTime( time, true );
};

/**
 * When using fixed time the player's time will stay fixed at the specified time parameter. It's up to the caller to continue updating the player's time.
 * @param {Number} time
 * @implements Player
 * @example
 * player.setFixedTime( 1000 );
 */

Player.prototype.setFixedTime = function ( time ) {

	this.setPlayerTime( time, false );
};

/*
https://hub.spigotmc.org/javadocs/spigot/

Returns whether the player is sleeping ignored.
isSleepingIgnored()

isSprinting()
Gets whether the player is sprinting or not.

kickPlayer(String message)
Kicks player with custom kick message.

loadData()
Loads the players current location, health, inventory, motion, and other information from the username.dat file, in the world/player folder.

	saveData()
Saves the players current location, health, inventory, motion, and other information into the username.dat file, in the world/player folder

playEffect(Location loc, Effect effect, T data)
Plays an effect to just this player.

playNote(Location loc, Instrument instrument, Note note)
Play a note for a player at a location.

playSound(Location location, String sound, float volume, float pitch)
Play a sound for a player at the location.

removeAchievement(Achievement achievement)
Removes the given achievement and any children achievements that the player has.

resetPlayerWeather()
Restores the normal condition where the player's weather is controlled by server conditions.

void	sendRawMessage(String message)
Sends this sender a message raw

void	sendMap(MapView map)
Render a map and send it to the player in its entirety.
*/

module.exports = Player;

/*
isOnGround()
*/<commit_msg>Player methods and documentation<commit_after>'use strict';

/**
 * @class
 * @augments {HumanEntity}
 * @augments {LivingEntity}
 * @augments {OfflinePlayer}
 * @example
 * var player = MC.getPlayer( 'kookster' );
 *
 * MC.command( '/command', function ( event ) {
 *
 * 	var player = event.getPlayer();
 * } );
 *
 * MC.event( 'player.PlayerChatEvent', function ( event ) {
 *
 * 	var player = event.getPlayer();
 * } );
 */

var Player = new Class( function ( bukkitObject ) {

	var rawMethods = bukkitObject.getClass().getMethods();

	for ( var i in this ) {
		this[ i ] = this[ i ].bind( bukkitObject );
	}

	for ( var i in rawMethods ) {
		var method = rawMethods[ i ].getName().toString();

		if ( !( method in this ) ) {
			this[ method ] = function ( /* arguments */ ) {

				var args = [];

				for ( var key in arguments ) {
					args.push( 'arguments[ "' + key + '" ]' );
				}

				return eval( 'bukkitObject[ this ]( ' + args.join() + ' );' );
			}.bind( method );
		}
	}
} );

Player.extends( require( './HumanEntity.js' ) );
Player.extends( require( './LivingEntity.js' ) );
Player.extends( require( './OfflinePlayer.js' ) );

/**
 * Gets the Location where this player will respawn.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getSpawnLocation = function () {

	var location;

	var Location = require( './Location.js' );

	var location = this.getBedSpawnLocation();

	if ( location ) {
		location = new Location( location );

	} else {
		location = new Location( this.getWorld().getSpawnLocation() );
	}

	return location;
};

/**
 * Get this players previously set compass target.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getCompassTarget = function () {

	var Location = require( './Location.js' );

	return new Location( this.getCompassTarget() );
};

/**
 * Gets this current players location.
 * @implements Player
 * @return {Location}
 */

Player.prototype.getLocation = function () {

	var Location = require( './Location.js' );

	return new Location( this.getLocation() );
};

/**
 * Changes this players current location to the target location.
 * @implements Player
 * @param {Location} location
 */

Player.prototype.setLocation = function ( location ) {

	var errors = [];

	if ( location.x === undefined ) {
		errors.push( 'x is undefined' );
	}

	if ( location.y === undefined ) {
		errors.push( 'y is undefined' );
	}

	if ( location.z === undefined ) {
		errors.push( 'z is undefined' );
	}

	if ( errors.length ) {
		throw new Error( 'Error in (Player.js).setLocation( ' + JSON.stringify( location ) +' ): ' + errors );
	}

	var playerLocation = this.getLocation();

	var world;

	if ( location.world ) {
		world = org.bukkit.Bukkit.getWorld( location.world );

	} else {
		world = playerLocation.getWorld();
	}

	var bukkitLocation = new org.bukkit.Location(
		world,
		location.x     || playerLocation.getX(),
		location.y     || playerLocation.getY(),
		location.z     || playerLocation.getZ(),
		location.yaw   || playerLocation.getYaw(),
		location.pitch || playerLocation.getPitch()
	);

	this.teleport( bukkitLocation );
};

/**
 * Gets if this player is online or not.
 * @implements Player
 * @return {boolean}
 */

Player.prototype.isOnline = function () {

	return this.isOnline();
};

/**
 * Says a message as this player.
 * @implements Player
 * @param {String} message
 * @example
 * player.chat( 'hi!' );
 */

Player.prototype.chat = function ( message ) {

	if ( message.match( /^\// ) ) {
		message = ''.reset() + message;
	}

	this.chat( message );
};

/**
 * Runs a command as this player.
 * @implements Player
 * @param {String} command
 * @example
 * player.run( '/command' );
 */

Player.prototype.run = function ( command ) {

	this.performCommand( command.replace( /^\//, '' ) );
};

/**
 * Gets this players IP address.
 * @implements Player
 * @return {String} ip
 * @example
 * var ip = player.getIp;
 */

Player.prototype.getIp = function () {

	return this.getAddress().getHostName();
};

/**
 * Gets if this player is allowed to fly or not currently.
 * @implements Player
 * @return {Boolean} canFly
 * @example
 * var canFly = player.canFly();
 */

Player.prototype.canFly = function () {

	return this.getAllowFlight();
};

/**
 * Gets the display name of this player.
 * @implements Player
 * @return {String} displayName
 * @example
 * var displayName = player.getDisplayName();
 */

Player.prototype.getDisplayName = function () {

	return this.getDisplayName();
};

/**
 * Returns true if the player's time is relative to the server time, otherwise the player's time is absolute and will not change its current time unless done so with setTime().
 * @implements Player
 * @return {Boolean}
 * @example
 * var timeRelative = player.isTimeRelative();
 */

Player.prototype.isTimeRelative = function () {

	return this.isPlayerTimeRelative();
};

/**
 * Restores the normal condition where the player's time is synchronized with the server time.
 * @implements Player
 * @example
 * player.resetTime();
 */

Player.prototype.resetTime = function () {

	this.resetPlayerTime();
};

/**
 * Sets the current time on the player's client. The time will be kept synchronized to its world time with the specified offset.
 * @param {Number} time
 * @implements Player
 * @example
 * player.setTime( 1000 );
 */

Player.prototype.setTime = function ( time ) {

	this.setPlayerTime( time, true );
};

/**
 * When using fixed time the player's time will stay fixed at the specified time parameter. It's up to the caller to continue updating the player's time.
 * @param {Number} time
 * @implements Player
 * @example
 * player.setFixedTime( 1000 );
 */

Player.prototype.setFixedTime = function ( time ) {

	this.setPlayerTime( time, false );
};

/*
https://hub.spigotmc.org/javadocs/spigot/

Returns whether the player is sleeping ignored.
isSleepingIgnored()

isSprinting()
Gets whether the player is sprinting or not.

kickPlayer(String message)
Kicks player with custom kick message.

loadData()
Loads the players current location, health, inventory, motion, and other information from the username.dat file, in the world/player folder.

	saveData()
Saves the players current location, health, inventory, motion, and other information into the username.dat file, in the world/player folder

playEffect(Location loc, Effect effect, T data)
Plays an effect to just this player.

playNote(Location loc, Instrument instrument, Note note)
Play a note for a player at a location.

playSound(Location location, String sound, float volume, float pitch)
Play a sound for a player at the location.

removeAchievement(Achievement achievement)
Removes the given achievement and any children achievements that the player has.

resetPlayerWeather()
Restores the normal condition where the player's weather is controlled by server conditions.

void	sendRawMessage(String message)
Sends this sender a message raw

void	sendMap(MapView map)
Render a map and send it to the player in its entirety.
*/

module.exports = Player;

/*
isOnGround()
*/<|endoftext|>


<commit_before>import { gql } from "@apollo/client"
import { Icon } from "@blueprintjs/core"
import "@blueprintjs/core/lib/css/blueprint.css"
import { IconNames } from "@blueprintjs/icons"
import API from "api"
import AppContext from "components/AppContext"
import ConfirmDestructive from "components/ConfirmDestructive"
import { parseHtmlWithLinkTo } from "components/editor/LinkAnet"
import LinkTo from "components/LinkTo"
import Messages from "components/Messages"
import Model, {
  INVISIBLE_CUSTOM_FIELDS_FIELD,
  NOTE_TYPE
} from "components/Model"
import RelatedObjectNoteModal from "components/RelatedObjectNoteModal"
import _isEmpty from "lodash/isEmpty"
import _isEqualWith from "lodash/isEqualWith"
import { Person } from "models"
import moment from "moment"
import PropTypes from "prop-types"
import React, { useContext, useEffect, useRef, useState } from "react"
import { Button, Card, Col, Offcanvas, Row } from "react-bootstrap"
import NotificationBadge from "react-notification-badge"
import Settings from "settings"
import utils from "utils"
import "./BlueprintOverrides.css"

const GQL_DELETE_NOTE = gql`
  mutation($uuid: String!) {
    deleteNote(uuid: $uuid)
  }
`

export { GRAPHQL_NOTES_FIELDS } from "components/Model"

export const EXCLUDED_ASSESSMENT_FIELDS = [
  "__recurrence",
  "__periodStart",
  "__relatedObjectType",
  INVISIBLE_CUSTOM_FIELDS_FIELD
]

const EXCLUDED_NOTE_TYPES = [NOTE_TYPE.ASSESSMENT, NOTE_TYPE.PARTNER_ASSESSMENT]

const RelatedObjectNotes = ({
  notesElemId,
  relatedObject,
  notes: notesProp
}) => {
  const { currentUser } = useContext(AppContext)
  const notesFiltered = notesProp.filter(
    note => !EXCLUDED_NOTE_TYPES.includes(note.type)
  )
  const latestNotesProp = useRef(notesFiltered)
  const notesPropUnchanged = _isEqualWith(
    latestNotesProp.current,
    notesFiltered,
    utils.treatFunctionsAsEqual
  )

  const [error, setError] = useState(null)
  const [
    showRelatedObjectNoteModalKey,
    setShowRelatedObjectNoteModalKey
  ] = useState(null)
  const [noteType, setNoteType] = useState(null)
  const [notes, setNotes] = useState(notesFiltered)
  const [show, setShow] = useState(false)

  useEffect(() => {
    if (!notesPropUnchanged) {
      latestNotesProp.current = notesFiltered
      setError(null)
      setNotes(notesFiltered)
    }
  }, [notesPropUnchanged, notesFiltered])

  const noNotes = _isEmpty(notes)
  const nrNotes = noNotes ? 0 : notes.length
  const badgeLabel = nrNotes > 10 ? "10+" : null

  const handleClose = () => setShow(false)
  const handleShow = () => setShow(true)

  return (
    <>
      <Button onClick={handleShow} title="Show notes">
        <NotificationBadge
          count={nrNotes}
          label={badgeLabel}
          style={{ fontSize: "8px", marginRight: "-8px", marginTop: "-2px" }}
          effect={["none", "none"]}
        />
        <Icon icon={IconNames.COMMENT} />
      </Button>

      <Offcanvas
        show={show}
        onHide={handleClose}
        placement="end"
        backdrop={false}
        style={{ zIndex: "1200", marginTop: "140px" }}
      >
        <Offcanvas.Header closeButton>
          <Offcanvas.Title>Notes</Offcanvas.Title>
        </Offcanvas.Header>
        <Offcanvas.Body>
          <Messages error={error} />

            <Button
              variant="primary"
              style={{ margin: "5px" }}
              onClick={() =>
                showRelatedObjectNoteModal("new", NOTE_TYPE.FREE_TEXT)
              }
            >
              Post a new note
            </Button>

          <RelatedObjectNoteModal
            note={{
              type: noteType,
              noteRelatedObjects: [{ ...relatedObject }]
            }}
            currentObject={relatedObject}
            showModal={showRelatedObjectNoteModalKey === "new"}
            onCancel={cancelRelatedObjectNoteModal}
            onSuccess={hideNewRelatedObjectNoteModal}
          />
          {noNotes && (

              No notes

          )}

            {notes.map(note => {
              const updatedAt = moment(note.updatedAt).format(
                Settings.dateFormats.forms.displayShort.withTime
              )
              const byMe = Person.isEqual(currentUser, note.author)
              const canEdit =
                note.type !== NOTE_TYPE.PARTNER_ASSESSMENT &&
                note.type !== NOTE_TYPE.ASSESSMENT &&
                (byMe || currentUser.isAdmin())
              const isJson = note.type !== NOTE_TYPE.FREE_TEXT
              const jsonFields =
                isJson && note.text ? utils.parseJsonSafe(note.text) : {}
              const noteText = isJson
                ? jsonFields.text
                : parseHtmlWithLinkTo(note.text)
              return (
                <Card
                  key={note.uuid}
                  variant="primary"
                  style={{ marginBottom: "1rem" }}
                >
                  <Card.Header>
                    <Row>
                      <Col xs={8}>
                        <Row>

                            {updatedAt}{" "}

                        </Row>
                        <Row>
                          <LinkTo modelType="Person" model={note.author} />
                        </Row>
                      </Col>
                      <Col xs={4} className="text-end">
                        {canEdit && (
                          <>
                            <Button
                              title="Edit note"
                              onClick={() =>
                                showRelatedObjectNoteModal(note.uuid)
                              }
                              size="xs"
                              variant="outline-secondary"
                            >
                              <Icon icon={IconNames.EDIT} />
                            </Button>

                            <RelatedObjectNoteModal
                              note={note}
                              currentObject={relatedObject}
                              showModal={
                                showRelatedObjectNoteModalKey === note.uuid
                              }
                              onCancel={cancelRelatedObjectNoteModal}
                              onSuccess={hideEditRelatedObjectNoteModal}
                              onDelete={hideDeleteRelatedObjectNoteModal}
                            />

                              <ConfirmDestructive
                                onConfirm={() => deleteNote(note.uuid)}
                                objectType="note"
                                objectDisplay={"#" + note.uuid}
                                title="Delete note"
                                variant="outline-danger"
                                buttonSize="xs"
                              >
                                <Icon icon={IconNames.TRASH} />
                              </ConfirmDestructive>

                          </>
                        )}
                      </Col>
                    </Row>
                  </Card.Header>
                  <Card.Body>

                      {note.type === NOTE_TYPE.CHANGE_RECORD &&
                        (jsonFields.oldValue === jsonFields.newValue ? (

                            Field {jsonFields.changedField} was unchanged
                            ('{jsonFields.oldValue}'):

                        ) : (

                            Field {jsonFields.changedField} was changed
                            from '{jsonFields.oldValue}' to{" "}
                            '{jsonFields.newValue}':

                        ))}

                      {noteText}

                  </Card.Body>
                </Card>
              )
            })}

        </Offcanvas.Body>
      </Offcanvas>
    </>
  )

  function showRelatedObjectNoteModal(key, type) {
    setError(null)
    setShowRelatedObjectNoteModalKey(key)
    setNoteType(type)
  }

  function cancelRelatedObjectNoteModal() {
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
  }

  function hideNewRelatedObjectNoteModal(note) {
    notes.unshift(note) // add new note at the front
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
    setNotes(notes)
  }

  function hideEditRelatedObjectNoteModal(note) {
    const newNotes = notes.filter(item => item.uuid !== note.uuid) // remove old note
    const roUuids = note?.noteRelatedObjects.map(nro => nro.relatedObjectUuid)
    if (roUuids?.includes(relatedObject?.relatedObjectUuid)) {
      newNotes.unshift(note) // add updated note at the front
    }
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
    setNotes(newNotes)
  }

  function hideDeleteRelatedObjectNoteModal(uuid) {
    setShowRelatedObjectNoteModalKey(null)
    deleteNote(uuid)
  }

  function deleteNote(uuid) {
    const newNotes = notes.filter(item => item.uuid !== uuid) // remove note
    API.mutation(GQL_DELETE_NOTE, { uuid })
      .then(data => {
        setError(null)
        setNotes(newNotes) // remove note
      })
      .catch(error => {
        setError(error)
      })
  }
}
RelatedObjectNotes.propTypes = {
  notesElemId: PropTypes.string.isRequired,
  notes: PropTypes.arrayOf(Model.notePropType),
  relatedObject: Model.relatedObjectPropType
}
RelatedObjectNotes.defaultProps = {
  notesElemId: "notes-view",
  notes: []
}

export default RelatedObjectNotes
<commit_msg>NCI-Agency/anet#3698: Make the Offcanvas offset respond to the TopBar height<commit_after>import { gql } from "@apollo/client"
import { Icon } from "@blueprintjs/core"
import "@blueprintjs/core/lib/css/blueprint.css"
import { IconNames } from "@blueprintjs/icons"
import API from "api"
import AppContext from "components/AppContext"
import ConfirmDestructive from "components/ConfirmDestructive"
import { parseHtmlWithLinkTo } from "components/editor/LinkAnet"
import LinkTo from "components/LinkTo"
import Messages from "components/Messages"
import Model, {
  INVISIBLE_CUSTOM_FIELDS_FIELD,
  NOTE_TYPE
} from "components/Model"
import RelatedObjectNoteModal from "components/RelatedObjectNoteModal"
import ResponsiveLayoutContext from "components/ResponsiveLayoutContext"
import _isEmpty from "lodash/isEmpty"
import _isEqualWith from "lodash/isEqualWith"
import { Person } from "models"
import moment from "moment"
import PropTypes from "prop-types"
import React, { useContext, useEffect, useRef, useState } from "react"
import { Button, Card, Col, Offcanvas, Row } from "react-bootstrap"
import NotificationBadge from "react-notification-badge"
import Settings from "settings"
import utils from "utils"
import "./BlueprintOverrides.css"

const GQL_DELETE_NOTE = gql`
  mutation($uuid: String!) {
    deleteNote(uuid: $uuid)
  }
`

export { GRAPHQL_NOTES_FIELDS } from "components/Model"

export const EXCLUDED_ASSESSMENT_FIELDS = [
  "__recurrence",
  "__periodStart",
  "__relatedObjectType",
  INVISIBLE_CUSTOM_FIELDS_FIELD
]

const EXCLUDED_NOTE_TYPES = [NOTE_TYPE.ASSESSMENT, NOTE_TYPE.PARTNER_ASSESSMENT]

const RelatedObjectNotes = ({
  notesElemId,
  relatedObject,
  notes: notesProp
}) => {
  const { currentUser } = useContext(AppContext)
  const { topbarOffset } = useContext(ResponsiveLayoutContext)
  const notesFiltered = notesProp.filter(
    note => !EXCLUDED_NOTE_TYPES.includes(note.type)
  )
  const latestNotesProp = useRef(notesFiltered)
  const notesPropUnchanged = _isEqualWith(
    latestNotesProp.current,
    notesFiltered,
    utils.treatFunctionsAsEqual
  )

  const [error, setError] = useState(null)
  const [
    showRelatedObjectNoteModalKey,
    setShowRelatedObjectNoteModalKey
  ] = useState(null)
  const [noteType, setNoteType] = useState(null)
  const [notes, setNotes] = useState(notesFiltered)
  const [show, setShow] = useState(false)

  useEffect(() => {
    if (!notesPropUnchanged) {
      latestNotesProp.current = notesFiltered
      setError(null)
      setNotes(notesFiltered)
    }
  }, [notesPropUnchanged, notesFiltered])

  const noNotes = _isEmpty(notes)
  const nrNotes = noNotes ? 0 : notes.length
  const badgeLabel = nrNotes > 10 ? "10+" : null

  const handleClose = () => setShow(false)
  const handleShow = () => setShow(true)

  return (
    <>
      <Button onClick={handleShow} title="Show notes">
        <NotificationBadge
          count={nrNotes}
          label={badgeLabel}
          style={{ fontSize: "8px", marginRight: "-8px", marginTop: "-2px" }}
          effect={["none", "none"]}
        />
        <Icon icon={IconNames.COMMENT} />
      </Button>

      <Offcanvas
        show={show}
        onHide={handleClose}
        placement="end"
        backdrop={false}
        style={{ zIndex: "1200", marginTop: topbarOffset }}
      >
        <Offcanvas.Header closeButton>
          <Offcanvas.Title>Notes</Offcanvas.Title>
        </Offcanvas.Header>
        <Offcanvas.Body>
          <Messages error={error} />

            <Button
              variant="primary"
              style={{ margin: "5px" }}
              onClick={() =>
                showRelatedObjectNoteModal("new", NOTE_TYPE.FREE_TEXT)
              }
            >
              Post a new note
            </Button>

          <RelatedObjectNoteModal
            note={{
              type: noteType,
              noteRelatedObjects: [{ ...relatedObject }]
            }}
            currentObject={relatedObject}
            showModal={showRelatedObjectNoteModalKey === "new"}
            onCancel={cancelRelatedObjectNoteModal}
            onSuccess={hideNewRelatedObjectNoteModal}
          />
          {noNotes && (

              No notes

          )}

            {notes.map(note => {
              const updatedAt = moment(note.updatedAt).format(
                Settings.dateFormats.forms.displayShort.withTime
              )
              const byMe = Person.isEqual(currentUser, note.author)
              const canEdit =
                note.type !== NOTE_TYPE.PARTNER_ASSESSMENT &&
                note.type !== NOTE_TYPE.ASSESSMENT &&
                (byMe || currentUser.isAdmin())
              const isJson = note.type !== NOTE_TYPE.FREE_TEXT
              const jsonFields =
                isJson && note.text ? utils.parseJsonSafe(note.text) : {}
              const noteText = isJson
                ? jsonFields.text
                : parseHtmlWithLinkTo(note.text)
              return (
                <Card
                  key={note.uuid}
                  variant="primary"
                  style={{ marginBottom: "1rem" }}
                >
                  <Card.Header>
                    <Row>
                      <Col xs={8}>
                        <Row>

                            {updatedAt}{" "}

                        </Row>
                        <Row>
                          <LinkTo modelType="Person" model={note.author} />
                        </Row>
                      </Col>
                      <Col xs={4} className="text-end">
                        {canEdit && (
                          <>
                            <Button
                              title="Edit note"
                              onClick={() =>
                                showRelatedObjectNoteModal(note.uuid)
                              }
                              size="xs"
                              variant="outline-secondary"
                            >
                              <Icon icon={IconNames.EDIT} />
                            </Button>

                            <RelatedObjectNoteModal
                              note={note}
                              currentObject={relatedObject}
                              showModal={
                                showRelatedObjectNoteModalKey === note.uuid
                              }
                              onCancel={cancelRelatedObjectNoteModal}
                              onSuccess={hideEditRelatedObjectNoteModal}
                              onDelete={hideDeleteRelatedObjectNoteModal}
                            />

                              <ConfirmDestructive
                                onConfirm={() => deleteNote(note.uuid)}
                                objectType="note"
                                objectDisplay={"#" + note.uuid}
                                title="Delete note"
                                variant="outline-danger"
                                buttonSize="xs"
                              >
                                <Icon icon={IconNames.TRASH} />
                              </ConfirmDestructive>

                          </>
                        )}
                      </Col>
                    </Row>
                  </Card.Header>
                  <Card.Body>

                      {note.type === NOTE_TYPE.CHANGE_RECORD &&
                        (jsonFields.oldValue === jsonFields.newValue ? (

                            Field {jsonFields.changedField} was unchanged
                            ('{jsonFields.oldValue}'):

                        ) : (

                            Field {jsonFields.changedField} was changed
                            from '{jsonFields.oldValue}' to{" "}
                            '{jsonFields.newValue}':

                        ))}

                      {noteText}

                  </Card.Body>
                </Card>
              )
            })}

        </Offcanvas.Body>
      </Offcanvas>
    </>
  )

  function showRelatedObjectNoteModal(key, type) {
    setError(null)
    setShowRelatedObjectNoteModalKey(key)
    setNoteType(type)
  }

  function cancelRelatedObjectNoteModal() {
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
  }

  function hideNewRelatedObjectNoteModal(note) {
    notes.unshift(note) // add new note at the front
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
    setNotes(notes)
  }

  function hideEditRelatedObjectNoteModal(note) {
    const newNotes = notes.filter(item => item.uuid !== note.uuid) // remove old note
    const roUuids = note?.noteRelatedObjects.map(nro => nro.relatedObjectUuid)
    if (roUuids?.includes(relatedObject?.relatedObjectUuid)) {
      newNotes.unshift(note) // add updated note at the front
    }
    setError(null)
    setShowRelatedObjectNoteModalKey(null)
    setNoteType(null)
    setNotes(newNotes)
  }

  function hideDeleteRelatedObjectNoteModal(uuid) {
    setShowRelatedObjectNoteModalKey(null)
    deleteNote(uuid)
  }

  function deleteNote(uuid) {
    const newNotes = notes.filter(item => item.uuid !== uuid) // remove note
    API.mutation(GQL_DELETE_NOTE, { uuid })
      .then(data => {
        setError(null)
        setNotes(newNotes) // remove note
      })
      .catch(error => {
        setError(error)
      })
  }
}
RelatedObjectNotes.propTypes = {
  notesElemId: PropTypes.string.isRequired,
  notes: PropTypes.arrayOf(Model.notePropType),
  relatedObject: Model.relatedObjectPropType
}
RelatedObjectNotes.defaultProps = {
  notesElemId: "notes-view",
  notes: []
}

export default RelatedObjectNotes
<|endoftext|>


<commit_before>'use strict';

const Alexa = require('alexa-sdk');
const Launch = require('./intents/Launch');
const Blackjack = require('./intents/Blackjack');
const Betting = require('./intents/Betting');
const SideBet = require('./intents/SideBet');
const Suggest = require('./intents/Suggest');
const TakeSuggestion = require('./intents/TakeSuggestion');
const Rules = require('./intents/Rules');
const ChangeRules = require('./intents/ChangeRules');
const TakeInsurance = require('./intents/TakeInsurance');
const DeclineInsurance = require('./intents/DeclineInsurance');
const Repeat = require('./intents/Repeat');
const HighScore = require('./intents/HighScore');
const Help = require('./intents/Help');
const Exit = require('./intents/Exit');
const Reset = require('./intents/Reset');
const Training = require('./intents/Training');
const Unhandled = require('./intents/Unhandled');
const gameService = require('./GameService');
const bjUtils = require('./BlackjackUtils');
const tournament = require('./tournament');
const playgame = require('./PlayGame');
const request = require('request');
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});

const APP_ID = 'amzn1.ask.skill.8fb6e399-d431-4943-a797-7a6888e7c6ce';
let newUser;

const suggestHandlers = Alexa.CreateStateHandler('SUGGESTION', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': TakeSuggestion.handleNoIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'RulesIntent': Rules.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.YesIntent': TakeSuggestion.handleYesIntent,
  'AMAZON.NoIntent': TakeSuggestion.handleNoIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const resetHandlers = Alexa.CreateStateHandler('CONFIRMRESET', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Reset.handleNoReset,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.FallbackIntent': Reset.handleRepeat,
  'AMAZON.RepeatIntent': Reset.handleRepeat,
  'AMAZON.HelpIntent': Reset.handleRepeat,
  'AMAZON.YesIntent': Reset.handleYesReset,
  'AMAZON.NoIntent': Reset.handleNoReset,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const newGameHandlers = Alexa.CreateStateHandler('NEWGAME', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'ResetIntent': Reset.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'ChangeRulesIntent': ChangeRules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': Betting.handleIntent,
  'AMAZON.NoIntent': Exit.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const firstTimeHandlers = Alexa.CreateStateHandler('FIRSTTIMEPLAYER', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'ResetIntent': Reset.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'ChangeRulesIntent': ChangeRules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': Betting.handleIntent,
  'AMAZON.NoIntent': Exit.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const insuranceHandlers = Alexa.CreateStateHandler('INSURANCEOFFERED', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': TakeInsurance.handleIntent,
  'AMAZON.NoIntent': DeclineInsurance.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const inGameHandlers = Alexa.CreateStateHandler('INGAME', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'AMAZON.YesIntent': Blackjack.handleYesIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

// These states are only accessible during tournament play
const joinHandlers = Alexa.CreateStateHandler('JOINTOURNAMENT', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': tournament.handlePass,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': tournament.handleJoin,
  'AMAZON.NoIntent': tournament.handlePass,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': tournament.handlePass,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

// Handlers for our skill
const handlers = {
  'NewSession': function() {
    initialize(this.attributes, this.event.request.locale, this.event.session.user.userId, () => {
      tournament.getTournamentComplete(this.event.request.locale, this.attributes, (result) => {
        // If there is an active tournament, go to the start tournament state
        if (tournament.canEnterTournament(this.attributes)) {
          // Great, enter the tournament!
          this.handler.state = 'JOINTOURNAMENT';
          tournament.promptToEnter(this.event.request.locale,
              this.attributes, (speech, reprompt) => {
            bjUtils.emitResponse(this, null, null, result + speech, reprompt);
          });
        } else {
          if (result && (result.length > 0)) {
            this.attributes.tournamentResult = result;
          }
          if (this.event.request.type === 'IntentRequest') {
            this.emit(this.event.request.intent.name);
          } else {
            this.emit('LaunchRequest');
          }
        }
      });
    });
  },
  // Some intents don't make sense for a new session - so just launch instead
  'LaunchRequest': Launch.handleIntent,
  'SuggestIntent': Launch.handleIntent,
  'ResetIntent': Launch.handleIntent,
  'ChangeRulesIntent': Launch.handleIntent,
  'AMAZON.YesIntent': Launch.handleIntent,
  'AMAZON.NoIntent': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
};

if (process.env.DASHBOTKEY) {
  const dashbot = require('dashbot')(process.env.DASHBOTKEY).alexa;
  exports.handler = dashbot.handler(runGame);
} else {
  exports.handler = runGame;
}

function runGame(event, context, callback) {
  const alexa = Alexa.handler(event, context);

  alexa.appId = APP_ID;
  if (!event.session.sessionId || event.session['new']) {
    const doc = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    doc.get({TableName: 'PlayBlackjack',
            ConsistentRead: true,
            Key: {userId: event.session.user.userId}},
            (err, data) => {
      if (err || (data.Item === undefined)) {
        if (err) {
          console.log('Error reading attributes ' + err);
        } else {
          newUser = true;
          request.post({url: process.env.SERVICEURL + 'blackjack/newUser'}, (err, res, body) => {
          });
        }
      } else {
        Object.assign(event.session.attributes, data.Item.mapAttr);
      }

      execute();
    });
  } else {
    execute();
  }

  function execute() {
    event.session.attributes.userId = event.session.user.userId;
    bjUtils.setEvent(event);
    bjUtils.readSuggestions(event.session.attributes, () => {
      alexa.registerHandlers(handlers, resetHandlers, newGameHandlers, firstTimeHandlers,
        insuranceHandlers, joinHandlers, inGameHandlers, suggestHandlers);
      alexa.execute();
    });
  }
}

function initialize(attributes, locale, userId, callback) {
  // Some initiatlization
  attributes.playerLocale = locale;
  attributes.numRounds = (attributes.numRounds + 1) || 1;
  attributes.newUser = newUser;
  attributes.temp = {firsthand: true};

  // If they don't have a game, create one
  if (!attributes.currentGame) {
    gameService.initializeGame(attributes, userId);

    // Now read the progressive jackpot amount
    bjUtils.getProgressivePayout(attributes, (jackpot) => {
      attributes[attributes.currentGame].progressiveJackpot = jackpot;
      callback();
    });
  } else {
    // Standard should have progressive; some customers will have this game
    // without progressive, so set it for them
    const game = attributes[attributes.currentGame];
    if (attributes.currentGame === 'standard') {
      if (!game.progressive) {
        game.progressive = {bet: 5, starting: 2500, jackpotRate: 1.25};

        // Also stuff sidebet in as a possible action if bet is there
        if (game.possibleActions &&
          (game.possibleActions.indexOf('bet') >= 0) &&
          (game.possibleActions.indexOf('sidebet') < 0)) {
          game.possibleActions.push('sidebet');
        }
      }

      // You should also be able to reset the standard game
      game.canReset = true;
    }

    // It's possible you are stuck in shuffle state if you ran out of cards
    // and money at the same time - if so, let's fix that here
    if (attributes && attributes.standard && attributes.standard.possibleActions
      && (attributes.standard.possibleActions.indexOf('shuffle') > -1)) {
      console.log('Player stuck in shuffle state!');
      playgame.playBlackjackAction(attributes, locale, userId, {action: 'shuffle'}, () => {
        getProgressive();
      });
    } else {
      getProgressive();
    }

    function getProgressive() {
      // Now read the progressive jackpot amount
      if (game.progressive) {
        bjUtils.getProgressivePayout(attributes, (jackpot) => {
          game.progressiveJackpot = jackpot;
          callback();
        });
      } else {
        callback();
      }
    }
  }
}

function saveState(userId, attributes) {
  const formData = {};

  formData.savedb = JSON.stringify({
    userId: userId,
    attributes: attributes,
  });

  const params = {
    url: process.env.SERVICEURL + 'blackjack/saveState',
    formData: formData,
  };

  request.post(params, (err, res, body) => {
    if (err) {
      console.log(err);
    }
  });
}
<commit_msg>Cancel leaves in join tournament<commit_after>'use strict';

const Alexa = require('alexa-sdk');
const Launch = require('./intents/Launch');
const Blackjack = require('./intents/Blackjack');
const Betting = require('./intents/Betting');
const SideBet = require('./intents/SideBet');
const Suggest = require('./intents/Suggest');
const TakeSuggestion = require('./intents/TakeSuggestion');
const Rules = require('./intents/Rules');
const ChangeRules = require('./intents/ChangeRules');
const TakeInsurance = require('./intents/TakeInsurance');
const DeclineInsurance = require('./intents/DeclineInsurance');
const Repeat = require('./intents/Repeat');
const HighScore = require('./intents/HighScore');
const Help = require('./intents/Help');
const Exit = require('./intents/Exit');
const Reset = require('./intents/Reset');
const Training = require('./intents/Training');
const Unhandled = require('./intents/Unhandled');
const gameService = require('./GameService');
const bjUtils = require('./BlackjackUtils');
const tournament = require('./tournament');
const playgame = require('./PlayGame');
const request = require('request');
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});

const APP_ID = 'amzn1.ask.skill.8fb6e399-d431-4943-a797-7a6888e7c6ce';
let newUser;

const suggestHandlers = Alexa.CreateStateHandler('SUGGESTION', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': TakeSuggestion.handleNoIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'RulesIntent': Rules.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.YesIntent': TakeSuggestion.handleYesIntent,
  'AMAZON.NoIntent': TakeSuggestion.handleNoIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const resetHandlers = Alexa.CreateStateHandler('CONFIRMRESET', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Reset.handleNoReset,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.FallbackIntent': Reset.handleRepeat,
  'AMAZON.RepeatIntent': Reset.handleRepeat,
  'AMAZON.HelpIntent': Reset.handleRepeat,
  'AMAZON.YesIntent': Reset.handleYesReset,
  'AMAZON.NoIntent': Reset.handleNoReset,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const newGameHandlers = Alexa.CreateStateHandler('NEWGAME', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'ResetIntent': Reset.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'ChangeRulesIntent': ChangeRules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': Betting.handleIntent,
  'AMAZON.NoIntent': Exit.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const firstTimeHandlers = Alexa.CreateStateHandler('FIRSTTIMEPLAYER', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'ResetIntent': Reset.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'ChangeRulesIntent': ChangeRules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': Betting.handleIntent,
  'AMAZON.NoIntent': Exit.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const insuranceHandlers = Alexa.CreateStateHandler('INSURANCEOFFERED', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': TakeInsurance.handleIntent,
  'AMAZON.NoIntent': DeclineInsurance.handleIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

const inGameHandlers = Alexa.CreateStateHandler('INGAME', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': Launch.handleIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'SuggestIntent': Suggest.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.FallbackIntent': Repeat.handleIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'AMAZON.YesIntent': Blackjack.handleYesIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

// These states are only accessible during tournament play
const joinHandlers = Alexa.CreateStateHandler('JOINTOURNAMENT', {
  'NewSession': function() {
    this.handler.state = '';
    this.emitWithState('NewSession');
  },
  'LaunchRequest': tournament.handlePass,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.YesIntent': tournament.handleJoin,
  'AMAZON.NoIntent': tournament.handlePass,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
});

// Handlers for our skill
const handlers = {
  'NewSession': function() {
    initialize(this.attributes, this.event.request.locale, this.event.session.user.userId, () => {
      tournament.getTournamentComplete(this.event.request.locale, this.attributes, (result) => {
        // If there is an active tournament, go to the start tournament state
        if (tournament.canEnterTournament(this.attributes)) {
          // Great, enter the tournament!
          this.handler.state = 'JOINTOURNAMENT';
          tournament.promptToEnter(this.event.request.locale,
              this.attributes, (speech, reprompt) => {
            bjUtils.emitResponse(this, null, null, result + speech, reprompt);
          });
        } else {
          if (result && (result.length > 0)) {
            this.attributes.tournamentResult = result;
          }
          if (this.event.request.type === 'IntentRequest') {
            this.emit(this.event.request.intent.name);
          } else {
            this.emit('LaunchRequest');
          }
        }
      });
    });
  },
  // Some intents don't make sense for a new session - so just launch instead
  'LaunchRequest': Launch.handleIntent,
  'SuggestIntent': Launch.handleIntent,
  'ResetIntent': Launch.handleIntent,
  'ChangeRulesIntent': Launch.handleIntent,
  'AMAZON.YesIntent': Launch.handleIntent,
  'AMAZON.NoIntent': Launch.handleIntent,
  'BettingIntent': Betting.handleIntent,
  'PlaceSideBetIntent': SideBet.handlePlaceIntent,
  'RemoveSideBetIntent': SideBet.handleRemoveIntent,
  'BlackjackIntent': Blackjack.handleIntent,
  'RulesIntent': Rules.handleIntent,
  'HighScoreIntent': HighScore.handleIntent,
  'EnableTrainingIntent': Training.handleEnableIntent,
  'DisableTrainingIntent': Training.handleDisableIntent,
  'AMAZON.RepeatIntent': Repeat.handleIntent,
  'AMAZON.HelpIntent': Help.handleIntent,
  'AMAZON.StopIntent': Exit.handleIntent,
  'AMAZON.CancelIntent': Exit.handleIntent,
  'Unhandled': Unhandled.handleIntent,
  'SessionEndedRequest': function() {
    saveState(this.event.session.user.userId, this.attributes);
  },
};

if (process.env.DASHBOTKEY) {
  const dashbot = require('dashbot')(process.env.DASHBOTKEY).alexa;
  exports.handler = dashbot.handler(runGame);
} else {
  exports.handler = runGame;
}

function runGame(event, context, callback) {
  const alexa = Alexa.handler(event, context);

  alexa.appId = APP_ID;
  if (!event.session.sessionId || event.session['new']) {
    const doc = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    doc.get({TableName: 'PlayBlackjack',
            ConsistentRead: true,
            Key: {userId: event.session.user.userId}},
            (err, data) => {
      if (err || (data.Item === undefined)) {
        if (err) {
          console.log('Error reading attributes ' + err);
        } else {
          newUser = true;
          request.post({url: process.env.SERVICEURL + 'blackjack/newUser'}, (err, res, body) => {
          });
        }
      } else {
        Object.assign(event.session.attributes, data.Item.mapAttr);
      }

      execute();
    });
  } else {
    execute();
  }

  function execute() {
    event.session.attributes.userId = event.session.user.userId;
    bjUtils.setEvent(event);
    bjUtils.readSuggestions(event.session.attributes, () => {
      alexa.registerHandlers(handlers, resetHandlers, newGameHandlers, firstTimeHandlers,
        insuranceHandlers, joinHandlers, inGameHandlers, suggestHandlers);
      alexa.execute();
    });
  }
}

function initialize(attributes, locale, userId, callback) {
  // Some initiatlization
  attributes.playerLocale = locale;
  attributes.numRounds = (attributes.numRounds + 1) || 1;
  attributes.newUser = newUser;
  attributes.temp = {firsthand: true};

  // If they don't have a game, create one
  if (!attributes.currentGame) {
    gameService.initializeGame(attributes, userId);

    // Now read the progressive jackpot amount
    bjUtils.getProgressivePayout(attributes, (jackpot) => {
      attributes[attributes.currentGame].progressiveJackpot = jackpot;
      callback();
    });
  } else {
    // Standard should have progressive; some customers will have this game
    // without progressive, so set it for them
    const game = attributes[attributes.currentGame];
    if (attributes.currentGame === 'standard') {
      if (!game.progressive) {
        game.progressive = {bet: 5, starting: 2500, jackpotRate: 1.25};

        // Also stuff sidebet in as a possible action if bet is there
        if (game.possibleActions &&
          (game.possibleActions.indexOf('bet') >= 0) &&
          (game.possibleActions.indexOf('sidebet') < 0)) {
          game.possibleActions.push('sidebet');
        }
      }

      // You should also be able to reset the standard game
      game.canReset = true;
    }

    // It's possible you are stuck in shuffle state if you ran out of cards
    // and money at the same time - if so, let's fix that here
    if (attributes && attributes.standard && attributes.standard.possibleActions
      && (attributes.standard.possibleActions.indexOf('shuffle') > -1)) {
      console.log('Player stuck in shuffle state!');
      playgame.playBlackjackAction(attributes, locale, userId, {action: 'shuffle'}, () => {
        getProgressive();
      });
    } else {
      getProgressive();
    }

    function getProgressive() {
      // Now read the progressive jackpot amount
      if (game.progressive) {
        bjUtils.getProgressivePayout(attributes, (jackpot) => {
          game.progressiveJackpot = jackpot;
          callback();
        });
      } else {
        callback();
      }
    }
  }
}

function saveState(userId, attributes) {
  const formData = {};

  formData.savedb = JSON.stringify({
    userId: userId,
    attributes: attributes,
  });

  const params = {
    url: process.env.SERVICEURL + 'blackjack/saveState',
    formData: formData,
  };

  request.post(params, (err, res, body) => {
    if (err) {
      console.log(err);
    }
  });
}
<|endoftext|>


<commit_before>function Message(display, text, number) {

    if (display == 'show') {

        $('#message').html(
            'ALERTE'+
            '
'+
            ''+text+''+
            '
'+
            ''+number+''
        );
        $('#message').show();
    }
    else {

        $('#message').hide();
    }
}

function setUltrason(value) {

    if (value < 0){

        value = (1 * value) * - 1;
    }

    if (value > 100){

        value = 100 ;
    }

    value = parseInt(value);

    value = 100 - value ;

    left = $('#valUltrasonLeft');
    right = $('#valUltrasonRight');

    left.removeClass('close').removeClass('middle').removeClass('far');
    right.removeClass('close').removeClass('middle').removeClass('far');

    if (value <= 50) {

        left.addClass('far');
        right.addClass('far');
        Message('hide', '', '');
    }
    else if (value > 50 && value < 80) {

        left.addClass('middle');
        right.addClass('middle');
        Message('hide', '', '');
    }
    else if (value > 80) {

        left.addClass('close');
        right.addClass('close');
        Message('show', 'Proximité', Value+'cm');
    }

    left.css('width', value+'px');
    right.css('width', value+'px');
}

function setVolts(volt){

    $('#valVolt').html(volt+'v');
    $('#faVolt').removeClass('fa-battery-empty').removeClass('fa-battery-quarter').removeClass('fa-battery-half').removeClass('fa-battery-three-quarters').removeClass('fa-battery-full');

    if (volt < 7) {

        $('#faVolt').addClass('fa-battery-empty');
        $('#faVolt').css('color', 'red');
    }
    else if (volt >= 7 && volt <= 8) {

        $('#faVolt').addClass('fa-battery-quarter');
        $('#faVolt').css('color', 'red');
    }
    else if (volt > 8 && volt <= 10){

        $('#faVolt').addClass('fa-battery-half');
        $('#faVolt').css('color', 'yellow');
    }
    else if (volt > 10 && volt <= 12){

        $('#faVolt').addClass('fa-battery-three-quarters');
        $('#faVolt').css('color', 'green');
    }
    else if (volt > 12 && volt <=15){

        $('#faVolt').addClass('fa-battery-full');
        $('#faVolt').css('color', 'green');
    }
    else {

        $('#faVolt').addClass('fa-battery-empty');
        $('#faVolt').css('color', 'red');
    }
}

function setTemperature(temperature){

    gauge = new Gauge($('#temperature'), {
        values: {
            0 : '0',
            20: '20',
            40: '40',
            60: '60',
            80: '80',
            100: '100'
        },
        colors: {
            0 : '#000',
            50: '#ffa500',
            70: '#f00',
        },
        angles: [
            130,
            410
        ],
        lineWidth: 5,
        arrowWidth: 7,
        inset:true,
        value: temperature
    });
};

function setCompteur(vitesse){

    vitesse = vitesse / 255 * 100;

    gauge = new Gauge($('#vitesse'), {
        values: {
            0 : '0',
            20: '50',
            40: '100',
            60: '150',
            80: '200',
            100: '255',
        },
        colors: {
            0 : '#000',
            80: '#f00'
        },
        angles: [
            130,
            410
        ],
        lineWidth: 5,
        arrowWidth: 7,
        inset:true,
        value: vitesse
    });
};

function setCpu(cpu){

    $('#valCpu').html(cpu+'%');

    if (cpu < 60) {

        $('#faCpu').css('color', 'green');
    }
    else if (cpu >= 60 && cpu <= 80) {

        $('#faCpu').css('color', 'yellow');
    }
    else if (cpu > 80 && cpu <= 100){

        $('#faCpu').css('color', 'red');
    }
};

function onOpen(talk) {

    console.log("Connecté");
};

function onClose(talk) {

    console.log("Déconnecté");
};

function onError(talk) {
    console.log('error: ' + talk.data);
    websocket.close();
};

function CrossPiSay(talk) {

    iSplit = talk.data.split(' ');
    Module = iSplit[0];
    Value = iSplit[1];

    if (Module === 'Cpu'){

        setCpu(Value);
    }
    else if (Module === 'Temperature') {

        setTemperature(Value);
    }
    else if (Module === 'Ultrasons') {

        setUltrason(Value);
    }
    else if (Module === 'Volts') {

        setVolts(Value);
    }
    else if (Module === 'Collision') {

        if (Value == 0) {

            Message('show', 'Collision', Value);
        }
    }
    else if (Module === 'Leds') {

        if (Value == 'on') {

            $('#faLeds').addClass('light');
            leds = 'on';
        }
        else {

            $('#faLeds').removeClass('light');
            leds = 'off';
        }
    }
}

function CrossPiDo(that) {

    websocket.send(that);
};

$(function() {

    document.body.addEventListener('touchmove', function(event) {
        event.preventDefault();
    }, false);

    websocket = new WebSocket('ws://192.168.0.24:1234/');
    websocket.onopen = function(talk) {onOpen(talk)};
    websocket.onclose = function(talk) { onClose(talk) };
    websocket.onmessage = function(talk) { CrossPiSay(talk) };
    websocket.onerror = function(talk) { onError(talk) };

    var joystickLeft = document.getElementById('joystickLeft');
    var joystickRight = document.getElementById('joystickRight');
    var vitesseZero ;
    var directionZero ;
    var turnLeft ;
    var turnRight ;
    var move ;
    var JsLeft ;
    var JsRight ;
    var leds ;
    var AutoPilot ;

    setTemperature(0);
    setCompteur(0);
    setCpu(0);
    setVolts(0);
});

speedLeft = 0;
speedRight = 0;
turnLeft = 0;
turnRight = 0;
move = 'none';
JsLeft = 'off';
JsRight = 'off';
leds = 'off';
AutoPilot = 'off';

setInterval( function() {

    if ( websocket.readyState == websocket.OPEN ) {

        if (JsLeft == 'on' && JsRight == 'off') {

            MotorLeft = speedLeft ;
            MotorRight = speedRight ;
            turnLeft = 0 ;
            turnRight = 0 ;

            setCompteur(MotorLeft);
        }
        else if (JsLeft == 'on' && JsRight == 'on') {

            MotorLeft = speedLeft - turnLeft ;
            MotorRight = speedRight - turnRight ;

            if (MotorLeft < 0) {

                MotorLeft = 0;
            }

            if (MotorRight < 0) {

                MotorRight = 0;
            }

            if (MotorLeft >= MotorRight){

                setCompteur(MotorLeft);
            }
            else {

                setCompteur(MotorRight);
            }
        }
        else if (JsLeft == 'off' && JsRight == 'on') {

            if (turnLeft > turnRight) {

                move = 'rotateLeft';
                MotorLeft = turnLeft ;
                MotorRight = turnLeft ;
                setCompteur(MotorLeft);
            }
            else {

                move = 'rotateRight';
                MotorLeft = turnRight ;
                MotorRight = turnRight ;
                setCompteur(MotorRight);
            }
        }
        else {

            move = 'none';
            MotorLeft = 0 ;
            MotorRight = 0 ;
            speedLeft = 0 ;
            speedRight = 0 ;
            turnLeft = 0 ;
            turnRight = 0 ;
            setCompteur(0);
        }

        if (AutoPilot == 'off') {

            CrossPiDo('Motors '+move+' '+MotorLeft+' '+MotorRight);
        }
    }
    else {

        websocket = new WebSocket('ws://192.168.0.24:1234/');
    }
}, 250 );

$('#leds').click(function() {

    if (leds == 'off') {

        CrossPiDo('Leds on');
    }
    else {

        CrossPiDo('Leds off');
    }
});

joystickLeft.addEventListener('touchstart', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];
        vitesseZero = touch.pageY;
        $('#rotate').hide();
        JsLeft = 'on';
    }
}, false);

joystickLeft.addEventListener('touchmove', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];

        vitesse = touch.pageY - vitesseZero ;
        vitesse = vitesse / 75 * 255;
        vitesse = parseInt(vitesse);

        if (vitesse < 0) {

            vitesse = (1 * vitesse) * - 1;

            if (vitesse <= 255) {

                joystickLeft.style.top = touch.pageY + 'px';

                pointer = (255 - vitesse) / 5.1 ;
                $('#pointer').css('top', pointer+'%');
            }
            else {

                vitesse = 255 ;
            }

            speedLeft = vitesse ;
            speedRight = vitesse ;
            move = 'go' ;
            $('#back').hide();
        }
        else {

            if (vitesse <= 255) {

                joystickLeft.style.top = touch.pageY + 'px';

                pointer = vitesse / 5.1 ;
                pointer = (1 * pointer) + (1 * 50);
                $('#pointer').css('top', pointer+'%');
            }
            else {

                vitesse = 255 ;
            }

            speedLeft = vitesse ;
            speedRight = vitesse ;
            move = 'back' ;
            $('#back').show();
        }
    }
}, false);

joystickLeft.addEventListener('touchend', function() {

    joystickLeft.style.top = '70%';
    $('#pointer').css('top', '50%');
    $('#back').hide();
    $('#rotate').show();
    JsLeft = 'off';
}, false);

joystickRight.addEventListener('touchstart', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];
        directionZero = touch.pageX;
        JsRight = 'on';
    }
}, false);

joystickRight.addEventListener('touchmove', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];

        direction = touch.pageX - directionZero ;
        direction = direction / 75 * 255;
        direction = parseInt(direction);

        if (direction < 0) {

            direction = (1 * direction) * - 1;

            if (direction <= 255) {

                joystickRight.style.left = touch.pageX + 'px';

                pointer = (255 - direction) / 5.1 ;
                $('#pointer').css('left', pointer+'%');
            }
            else {

                direction = 255 ;
            }

            turnLeft = direction ;
            turnRight = 0 ;
        }
        else {

            if (direction <= 255) {

                joystickRight.style.left = touch.pageX + 'px';

                pointer = direction / 5.1 ;
                pointer = (1 * pointer) + (1 * 50);
                $('#pointer').css('left', pointer+'%');
            }
            else {

                direction = 255 ;
            }

            turnLeft = 0 ;
            turnRight = direction ;
        }
    }
}, false);

joystickRight.addEventListener('touchend', function(e) {

    joystickRight.style.left = '80%';
    $('#pointer').css('left', '50%');
    JsRight = 'off';
}, false);
<commit_msg>Update CrossPi.js<commit_after>function Message(display, text, number) {

    if (display == 'show') {

        $('#message').html(
            'ALERTE'+
            '
'+
            ''+text+''+
            '
'+
            ''+number+''
        );
        $('#message').show();
    }
    else {

        $('#message').hide();
    }
}

function setUltrason(value) {

    if (value < 0){

        value = (1 * value) * - 1;
    }

    if (value > 100){

        value = 100 ;
    }

    value = parseInt(value);

    value = 100 - value ;

    left = $('#valUltrasonLeft');
    right = $('#valUltrasonRight');

    left.removeClass('close').removeClass('middle').removeClass('far');
    right.removeClass('close').removeClass('middle').removeClass('far');

    if (value <= 50) {

        left.addClass('far');
        right.addClass('far');
        Message('hide', '', '');
    }
    else if (value > 50 && value < 80) {

        left.addClass('middle');
        right.addClass('middle');
        Message('hide', '', '');
    }
    else if (value > 80) {

        left.addClass('close');
        right.addClass('close');
        Message('show', 'Proximité', Value+'cm');
    }

    left.css('width', value+'px');
    right.css('width', value+'px');
}

function setVolts(volt){

    $('#valVolt').html(volt+'v');
    $('#faVolt').removeClass('fa-battery-empty').removeClass('fa-battery-quarter').removeClass('fa-battery-half').removeClass('fa-battery-three-quarters').removeClass('fa-battery-full');

    if (volt < 7) {

        $('#faVolt').addClass('fa-battery-empty');
        $('#faVolt').css('color', 'red');
    }
    else if (volt >= 7 && volt <= 8) {

        $('#faVolt').addClass('fa-battery-quarter');
        $('#faVolt').css('color', 'red');
    }
    else if (volt > 8 && volt <= 10){

        $('#faVolt').addClass('fa-battery-half');
        $('#faVolt').css('color', 'yellow');
    }
    else if (volt > 10 && volt <= 12){

        $('#faVolt').addClass('fa-battery-three-quarters');
        $('#faVolt').css('color', 'green');
    }
    else if (volt > 12 && volt <=15){

        $('#faVolt').addClass('fa-battery-full');
        $('#faVolt').css('color', 'green');
    }
    else {

        $('#faVolt').addClass('fa-battery-empty');
        $('#faVolt').css('color', 'red');
    }
}

function setTemperature(temperature){

    gauge = new Gauge($('#temperature'), {
        values: {
            0 : '0',
            20: '20',
            40: '40',
            60: '60',
            80: '80',
            100: '100'
        },
        colors: {
            0 : '#000',
            50: '#ffa500',
            70: '#f00',
        },
        angles: [
            130,
            410
        ],
        lineWidth: 5,
        arrowWidth: 7,
        inset:true,
        value: temperature
    });
};

function setCompteur(vitesse){

    vitesse = vitesse / 255 * 100;

    gauge = new Gauge($('#vitesse'), {
        values: {
            0 : '0',
            20: '50',
            40: '100',
            60: '150',
            80: '200',
            100: '255',
        },
        colors: {
            0 : '#000',
            80: '#f00'
        },
        angles: [
            130,
            410
        ],
        lineWidth: 5,
        arrowWidth: 7,
        inset:true,
        value: vitesse
    });
};

function setCpu(cpu){

    $('#valCpu').html(cpu+'%');

    if (cpu < 60) {

        $('#faCpu').css('color', 'green');
    }
    else if (cpu >= 60 && cpu <= 80) {

        $('#faCpu').css('color', 'yellow');
    }
    else if (cpu > 80 && cpu <= 100){

        $('#faCpu').css('color', 'red');
    }
};

function onOpen(talk) {

    console.log("Connecté");
};

function onClose(talk) {

    console.log("Déconnecté");
};

function onError(talk) {
    console.log('error: ' + talk.data);
    websocket.close();
};

function CrossPiSay(talk) {

    iSplit = talk.data.split(' ');
    Module = iSplit[0];
    Value = iSplit[1];

    if (Module === 'Cpu'){

        setCpu(Value);
    }
    else if (Module === 'Temperature') {

        setTemperature(Value);
    }
    else if (Module === 'Ultrasons') {

        setUltrason(Value);
    }
    else if (Module === 'Volts') {

        setVolts(Value);
    }
    else if (Module === 'Collision') {

        if (Value == 0) {

            Message('show', 'Collision', Value);
        }
    }
    else if (Module === 'Leds') {

        if (Value == 'on') {

            $('#faLeds').addClass('light');
            leds = 'on';
        }
        else {

            $('#faLeds').removeClass('light');
            leds = 'off';
        }
    }
}

function CrossPiDo(that) {

    websocket.send(that);
};

$(function() {

    document.body.addEventListener('touchmove', function(event) {
        event.preventDefault();
    }, false);

// Changez l'Ip par la votre
    websocket = new WebSocket('ws://192.168.0.24:1234/');
    websocket.onopen = function(talk) {onOpen(talk)};
    websocket.onclose = function(talk) { onClose(talk) };
    websocket.onmessage = function(talk) { CrossPiSay(talk) };
    websocket.onerror = function(talk) { onError(talk) };

    var joystickLeft = document.getElementById('joystickLeft');
    var joystickRight = document.getElementById('joystickRight');
    var vitesseZero ;
    var directionZero ;
    var turnLeft ;
    var turnRight ;
    var move ;
    var JsLeft ;
    var JsRight ;
    var leds ;
    var AutoPilot ;

    setTemperature(0);
    setCompteur(0);
    setCpu(0);
    setVolts(0);
});

speedLeft = 0;
speedRight = 0;
turnLeft = 0;
turnRight = 0;
move = 'none';
JsLeft = 'off';
JsRight = 'off';
leds = 'off';
AutoPilot = 'off';

setInterval( function() {

    if ( websocket.readyState == websocket.OPEN ) {

        if (JsLeft == 'on' && JsRight == 'off') {

            MotorLeft = speedLeft ;
            MotorRight = speedRight ;
            turnLeft = 0 ;
            turnRight = 0 ;

            setCompteur(MotorLeft);
        }
        else if (JsLeft == 'on' && JsRight == 'on') {

            MotorLeft = speedLeft - turnLeft ;
            MotorRight = speedRight - turnRight ;

            if (MotorLeft < 0) {

                MotorLeft = 0;
            }

            if (MotorRight < 0) {

                MotorRight = 0;
            }

            if (MotorLeft >= MotorRight){

                setCompteur(MotorLeft);
            }
            else {

                setCompteur(MotorRight);
            }
        }
        else if (JsLeft == 'off' && JsRight == 'on') {

            if (turnLeft > turnRight) {

                move = 'rotateLeft';
                MotorLeft = turnLeft ;
                MotorRight = turnLeft ;
                setCompteur(MotorLeft);
            }
            else {

                move = 'rotateRight';
                MotorLeft = turnRight ;
                MotorRight = turnRight ;
                setCompteur(MotorRight);
            }
        }
        else {

            move = 'none';
            MotorLeft = 0 ;
            MotorRight = 0 ;
            speedLeft = 0 ;
            speedRight = 0 ;
            turnLeft = 0 ;
            turnRight = 0 ;
            setCompteur(0);
        }

        if (AutoPilot == 'off') {

            CrossPiDo('Motors '+move+' '+MotorLeft+' '+MotorRight);
        }
    }
    else {

        // Changez l'Ip par la votre
        websocket = new WebSocket('ws://192.168.0.24:1234/');
    }
}, 250 );

$('#leds').click(function() {

    if (leds == 'off') {

        CrossPiDo('Leds on');
    }
    else {

        CrossPiDo('Leds off');
    }
});

joystickLeft.addEventListener('touchstart', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];
        vitesseZero = touch.pageY;
        $('#rotate').hide();
        JsLeft = 'on';
    }
}, false);

joystickLeft.addEventListener('touchmove', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];

        vitesse = touch.pageY - vitesseZero ;
        vitesse = vitesse / 75 * 255;
        vitesse = parseInt(vitesse);

        if (vitesse < 0) {

            vitesse = (1 * vitesse) * - 1;

            if (vitesse <= 255) {

                joystickLeft.style.top = touch.pageY + 'px';

                pointer = (255 - vitesse) / 5.1 ;
                $('#pointer').css('top', pointer+'%');
            }
            else {

                vitesse = 255 ;
            }

            speedLeft = vitesse ;
            speedRight = vitesse ;
            move = 'go' ;
            $('#back').hide();
        }
        else {

            if (vitesse <= 255) {

                joystickLeft.style.top = touch.pageY + 'px';

                pointer = vitesse / 5.1 ;
                pointer = (1 * pointer) + (1 * 50);
                $('#pointer').css('top', pointer+'%');
            }
            else {

                vitesse = 255 ;
            }

            speedLeft = vitesse ;
            speedRight = vitesse ;
            move = 'back' ;
            $('#back').show();
        }
    }
}, false);

joystickLeft.addEventListener('touchend', function() {

    joystickLeft.style.top = '70%';
    $('#pointer').css('top', '50%');
    $('#back').hide();
    $('#rotate').show();
    JsLeft = 'off';
}, false);

joystickRight.addEventListener('touchstart', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];
        directionZero = touch.pageX;
        JsRight = 'on';
    }
}, false);

joystickRight.addEventListener('touchmove', function(event) {

    if (event.targetTouches.length == 1) {

        touch = event.targetTouches[0];

        direction = touch.pageX - directionZero ;
        direction = direction / 75 * 255;
        direction = parseInt(direction);

        if (direction < 0) {

            direction = (1 * direction) * - 1;

            if (direction <= 255) {

                joystickRight.style.left = touch.pageX + 'px';

                pointer = (255 - direction) / 5.1 ;
                $('#pointer').css('left', pointer+'%');
            }
            else {

                direction = 255 ;
            }

            turnLeft = direction ;
            turnRight = 0 ;
        }
        else {

            if (direction <= 255) {

                joystickRight.style.left = touch.pageX + 'px';

                pointer = direction / 5.1 ;
                pointer = (1 * pointer) + (1 * 50);
                $('#pointer').css('left', pointer+'%');
            }
            else {

                direction = 255 ;
            }

            turnLeft = 0 ;
            turnRight = direction ;
        }
    }
}, false);

joystickRight.addEventListener('touchend', function(e) {

    joystickRight.style.left = '80%';
    $('#pointer').css('left', '50%');
    JsRight = 'off';
}, false);
<|endoftext|>