<commit_before>var employeeID = getEmployeeID();

function getEmployeeID(){

	if(localStorage.getItem("numberOfEmployees") == null){
		localStorage.setItem("numberOfEmployees", "0");
	return 0;
	}
	return parseInt(localStorage.getItem("numberOfEmployees"));
}

(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
	$('.modal-trigger').leanModal();

	$("#loginBtn").click(function(event){
        var user = $("#username").val();
        var pass = $("#password").val();

		var result = getUser(user, pass);
        if(result == 0) //Admin
        {
			loadAdminPage(user);
        }
        else if(result == 1) //user
        {
            console.log("Got user: [" + user + "] Password: [" + pass +"]");

            loadUserPage(user);
        }
        else //error
        {
        }

    });

  }); // end of document ready
})(jQuery); // end of jQuery name space

function getUser(user, pass){
    if(user === "Admin" && pass === "Admin")
    {
        return 0;
    }
    else
    {
	for(var i=1; i<=employeeID; i++){
		if(JSON.parse(localStorage.getItem(i.toString())).userName == user){
			if(JSON.parse(localStorage.getItem(i.toString())).password == pass){
				if(JSON.parse(localStorage.getItem(i.toString())).permissions == "on")
					return 0;
				return 1;
			}
			alert("Wrong password! please try again.");
			return -1;
		}
	}
	alert("You are not registered. Please contact the Admin or try again.");
	return -1;
    }
}

function loadAdminPage(user){
	//Change page layout
	$('#parallexPic').attr("src", "Pics/background2.jpg");
	$("#index-banner").css('min-height', '200px');
	$("#cont1").empty();

	$("#cont1").append('
Welcome ' + user);

	$("#cont1").append('
');

	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light lime tooltipped modal-trigger2" href="#modal2" data-position="left" data-delay="50" data-tooltip="Add new user" type="submit" name="action" id = "addBtn"></button>');
	$("#addBtn").append('add');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light red tooltipped modal-trigger3" href="#modal3" data-position="top" data-delay="50" data-tooltip="Delete user" type="submit" name="action" id = "deleteBtn"></button>');
	$("#deleteBtn").append('delete');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light orange tooltipped" data-position="top" data-delay="50" data-tooltip="Clear your selection" type="submit" name="action" id = "clearBtn"></button>');
	$("#clearBtn").append('clear_all');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light grey tooltipped" data-position="right" data-delay="50" data-tooltip="Print your selection" type="submit" name="action" id = "printBtn"></button>');
	$("#printBtn").append('print');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light green tooltipped" data-position="right" data-delay="50" data-tooltip="Submit your selection" type="submit" name="action" id = "submitBtn"></button>');
	$("#submitBtn").append('send');

	$('.tooltipped').tooltip({delay: 50});
	$('.modal-trigger2').leanModal();
	$('.modal-trigger3').leanModal();

	$("#loginAddBtn").click(function(event){
		for(var i=1; i<=employeeID; i++)
			if(JSON.parse(localStorage.getItem(i.toString())).userName == $("#addUserName").val()){
				alert("User exists, please choose another username!");
				return;
		}

		var obj = new Object();
		obj.userName = $("#addUserName").val();
		obj.password = $("#choosePass").val();
		obj.telephone = $("#icon_telephone").val();
		obj.permissions = $('#permissions:checked').val();
		obj.email = $("#email").val();

		alert("Employee Registered!!");
		employeeID++;
		localStorage.setItem(employeeID.toString(), JSON.stringify(obj));
		localStorage.setItem("numberOfEmployees", employeeID.toString());
	});

	$("#delBtn").click(function(event){
		var userToDel = $("#delName").val();
		for(var i=1; i<=employeeID; i++)
			if(JSON.parse(localStorage.getItem(i.toString())).userName == userToDel){
				localStorage.removeItem(i.toString());
				for(var j=(i+1); j<= employeeID; j++)
				{
					var tmpItem = localStorage.getItem(j.toString());
					localStorage.setItem(i.toString(), tmpItem);
					i++;
				}
				localStorage.removeItem(i.toString());
				employeeID--;
				localStorage.setItem("numberOfEmployees", employeeID.toString());
				alert("User deleted successfully!");
				return;
			}
		alert("User doesn't exists, please choose another username and try again!");
	});
}

function loadUserPage(user){

	//Change page layout
	$('#parallexPic').attr("src", "Pics/background2.jpg");
	$("#index-banner").css('min-height', '200px');
	$("#cont1").empty();

	$("#cont1").append('
Welcome ' + user);

	$("#cont1").append('
');

	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light orange tooltipped" data-position="left" data-delay="50" data-tooltip="Clear your selection" type="submit" name="action" id = "clearBtn"></button>');
	$("#clearBtn").append('clear_all');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light red tooltipped" data-position="right" data-delay="50" data-tooltip="Print your selection" type="submit" name="action" id = "printBtn"></button>');
	$("#printBtn").append('print');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light green tooltipped" data-position="right" data-delay="50" data-tooltip="Submit your selection" type="submit" name="action" id = "submitBtn"></button>');
	$("#submitBtn").append('send');

	$('.tooltipped').tooltip({delay: 50});

    $("#dataZone").empty();
    $("#dataZone").append('
');

    //Table Head
    $(".shift-table").append('
');
    $(".thead-inverse").append('
');
    $("#table-title").append('Shift	');
    $("#table-title").append('Sunday	');
    $("#table-title").append('Monday	');
    $("#table-title").append('Tuesday	');
    $("#table-title").append('Wednesday	');
    $("#table-title").append('Thursday	');
    $("#table-title").append('Friday	');
    $("#table-title").append('Saturday	');

    //Table Body
    $(".shift-table").append('
');
    $("#tbot").append('
');
    $("#1").append('Morning	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#tbot").append('
');
    $("#2").append('Noon	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#tbot").append('
');
    $("#3").append('Nighet	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');

    var array = new Array(3);
    for (var i = 0; i < 3; i++) {
        array[i] = new Array(7);
        for(var j = 0; j<7; j++)
            array[i][j] = 0;
    }

    //Add event listener
    $('td').click(function() {

        var i = parseInt($(this).attr('id'));
        var j = i % 10;
        i /= 10;
        i = Math.floor(i);

        //color of the setted shifts
        if(array[i][j] == 0){
            array[i][j] = 1;
            if(i == 0)
                $(this).css('backgroundColor', '#111111');
            else if (i == 1)
                $(this).css('backgroundColor', '#555555');
            else
                $(this).css('backgroundColor', '#999999');

            }
        else {
            array[i][j] = 0;
            $(this).removeAttr("style");
        }
	});

	$("#clearBtn").click(function(event){
		clearTable();
	});

	$('#submitBtn').click(function(event){
		var found = false;
		var obj;
		var foundID;
		for(var i=1; i<=employeeID; i++)
		{
			if(JSON.parse(localStorage.getItem(i.toString())).userName == user){
				obj = JSON.parse(localStorage.getItem(i.toString()));
				obj.morning = [];
				obj.noon = [];
				obj.evening = [];
				foundID = i;
				found = true;
				break;
			}
		}

		if(found)
		{
			for (var i = 0; i < 3; i++) {
				for(var j = 0; j<7; j++){
					if(i == 0)
						if(array[i][j])
							obj.morning.push(returnDay(j));
					if(i == 1)
						if(array[i][j])
							obj.noon.push(returnDay(j));
					if(i == 2)
						if(array[i][j])
							obj.evening.push(returnDay(j));
				}
			}
			localStorage.setItem(foundID.toString(), JSON.stringify(obj));
		}
		alert("Thank you for your shifts. You can exit the browser now!");
		clearTable();
	});

	function clearTable()
	{
		for (var i = 0; i < 3; i++) {
			for(var j = 0; j<7; j++){
				array[i][j] = 0;
				$('td').removeAttr("style");
			}
		}
	}
}

function returnDay(index)
{
	switch(index){
		case 0:
		 return "Sunday";
		 break;
		case 1:
		 return "Monday";
		 break;
		case 2:
		 return "Tuesday";
		 break;
		case 3:
		 return "Wednesday";
		 break;
		case 4:
		 return "Thursday";
		 break;
		case 5:
		 return "Friday";
		 break;
		case 6:
		 return "Saturday";
		 break;
	}

}
<commit_msg>shifts object added to user obj<commit_after>var employeeID = getEmployeeID();

function getEmployeeID(){

	if(localStorage.getItem("numberOfEmployees") == null){
		localStorage.setItem("numberOfEmployees", "0");
	return 0;
	}
	return parseInt(localStorage.getItem("numberOfEmployees"));
}

(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
	$('.modal-trigger').leanModal();

	$("#loginBtn").click(function(event){
        var user = $("#username").val();
        var pass = $("#password").val();

		var userType = getUser(user, pass);
        if(userType == 0) //Admin
        {
			loadAdminPage(user);
        }
        else if(userType == 1) //user
        {
            loadUserPage(user);
        }
        else //error
        {
        }

    });

  }); // end of document ready
})(jQuery); // end of jQuery name space

function getUser(user, pass){
    if(user === "Admin" && pass === "Admin")
    {
        return 0;
    }
    else
    {
	for(var i=1; i<=employeeID; i++){
		if(JSON.parse(localStorage.getItem(i.toString())).userName == user){
			if(JSON.parse(localStorage.getItem(i.toString())).password == pass){
				if(JSON.parse(localStorage.getItem(i.toString())).permissions == "on")
					return 0;
				return 1;
			}
			alert("Wrong password! please try again.");
			return -1;
		}
	}
	alert("You are not registered. Please contact the Admin or try again.");
	return -1;
    }
}

function loadAdminPage(user){
	//Change page layout
	$('#parallexPic').attr("src", "Pics/background2.jpg");
	$("#index-banner").css('min-height', '200px');
	$("#cont1").empty();

	$("#cont1").append('
Welcome ' + user);

	$("#cont1").append('
');

	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light lime tooltipped modal-trigger2" href="#modal2" data-position="left" data-delay="50" data-tooltip="Add new user" type="submit" name="action" id = "addBtn"></button>');
	$("#addBtn").append('add');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light red tooltipped modal-trigger3" href="#modal3" data-position="top" data-delay="50" data-tooltip="Delete user" type="submit" name="action" id = "deleteBtn"></button>');
	$("#deleteBtn").append('delete');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light orange tooltipped" data-position="top" data-delay="50" data-tooltip="Clear your selection" type="submit" name="action" id = "clearBtn"></button>');
	$("#clearBtn").append('clear_all');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light grey tooltipped" data-position="right" data-delay="50" data-tooltip="Print your selection" type="submit" name="action" id = "printBtn"></button>');
	$("#printBtn").append('print');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light green tooltipped" data-position="right" data-delay="50" data-tooltip="Submit your selection" type="submit" name="action" id = "submitBtn"></button>');
	$("#submitBtn").append('send');

	$('.tooltipped').tooltip({delay: 50});
	$('.modal-trigger2').leanModal();
	$('.modal-trigger3').leanModal();

	$("#loginAddBtn").click(function(event){
		for(var i=1; i<=employeeID; i++)
			if(JSON.parse(localStorage.getItem(i.toString())).userName == $("#addUserName").val()){
				alert("User exists, please choose another username!");
				return;
		}

		var obj = new Object();
		obj.userName = $("#addUserName").val();
		obj.password = $("#choosePass").val();
		obj.telephone = $("#icon_telephone").val();
		obj.permissions = $('#permissions:checked').val();
		obj.email = $("#email").val();

		alert("Employee Registered!!");
		employeeID++;
		localStorage.setItem(employeeID.toString(), JSON.stringify(obj));
		localStorage.setItem("numberOfEmployees", employeeID.toString());
	});

	$("#delBtn").click(function(event){
		var userToDel = $("#delName").val();
		for(var i=1; i<=employeeID; i++)
			if(JSON.parse(localStorage.getItem(i.toString())).userName == userToDel){
				localStorage.removeItem(i.toString());
				for(var j=(i+1); j<= employeeID; j++)
				{
					var tmpItem = localStorage.getItem(j.toString());
					localStorage.setItem(i.toString(), tmpItem);
					i++;
				}
				localStorage.removeItem(i.toString());
				employeeID--;
				localStorage.setItem("numberOfEmployees", employeeID.toString());
				alert("User deleted successfully!");
				return;
			}
		alert("User doesn't exists, please choose another username and try again!");
	});
}

function loadUserPage(user){

	//Change page layout
	$('#parallexPic').attr("src", "Pics/background2.jpg");
	$("#index-banner").css('min-height', '200px');
	$("#cont1").empty();

	$("#cont1").append('
Welcome ' + user);

	$("#cont1").append('
');

	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light orange tooltipped" data-position="left" data-delay="50" data-tooltip="Clear your selection" type="submit" name="action" id = "clearBtn"></button>');
	$("#clearBtn").append('clear_all');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light red tooltipped" data-position="right" data-delay="50" data-tooltip="Print your selection" type="submit" name="action" id = "printBtn"></button>');
	$("#printBtn").append('print');
	$("#row1").append('<button class="usrBttns btn-floating btn-large waves-effect waves-light green tooltipped" data-position="right" data-delay="50" data-tooltip="Submit your selection" type="submit" name="action" id = "submitBtn"></button>');
	$("#submitBtn").append('send');

	$('.tooltipped').tooltip({delay: 50});

    $("#dataZone").empty();
    $("#dataZone").append('
');

    //Table Head
    $(".shift-table").append('
');
    $(".thead-inverse").append('
');
    $("#table-title").append('Shift	');
    $("#table-title").append('Sunday	');
    $("#table-title").append('Monday	');
    $("#table-title").append('Tuesday	');
    $("#table-title").append('Wednesday	');
    $("#table-title").append('Thursday	');
    $("#table-title").append('Friday	');
    $("#table-title").append('Saturday	');

    //Table Body
    $(".shift-table").append('
');
    $("#tbot").append('
');
    $("#1").append('Morning	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#1").append('	');
    $("#tbot").append('
');
    $("#2").append('Noon	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#2").append('	');
    $("#tbot").append('
');
    $("#3").append('Nighet	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');
    $("#3").append('	');

    var array = new Array(3);
    for (var i = 0; i < 3; i++) {
        array[i] = new Array(7);
        for(var j = 0; j<7; j++)
            array[i][j] = 0;
    }

    //Add event listener
    $('td').click(function() {

        var i = parseInt($(this).attr('id'));
        var j = i % 10;
        i /= 10;
        i = Math.floor(i);

        //color of the setted shifts
        if(array[i][j] == 0){
            array[i][j] = 1;
            if(i == 0)
                $(this).css('backgroundColor', '#111111');
            else if (i == 1)
                $(this).css('backgroundColor', '#555555');
            else
                $(this).css('backgroundColor', '#999999');

            }
        else {
            array[i][j] = 0;
            $(this).removeAttr("style");
        }
	});

	$("#clearBtn").click(function(event){
		clearTable();
	});

	$('#submitBtn').click(function(event){
		var found = false;
		var obj;
		var foundID;
		for(var i=1; i<=employeeID; i++)
		{
			if(JSON.parse(localStorage.getItem(i.toString())).userName == user){
				obj = JSON.parse(localStorage.getItem(i.toString()));
				obj.shifts = new Object();
				obj.shifts.morning = [];
				obj.shifts.noon = [];
				obj.shifts.evening = [];
				foundID = i;
				found = true;
				break;
			}
		}

		if(found)
		{
			for (var i = 0; i < 3; i++) {
				for(var j = 0; j<7; j++){
					if(i == 0)
						if(array[i][j])
							obj.shifts.morning.push(returnDay(j));
					if(i == 1)
						if(array[i][j])
							obj.shifts.noon.push(returnDay(j));
					if(i == 2)
						if(array[i][j])
							obj.shifts.evening.push(returnDay(j));
				}
			}
			localStorage.setItem(foundID.toString(), JSON.stringify(obj));
		}
		alert("Thank you for your shifts. You can exit the browser now!");
		clearTable();
	});

	function clearTable()
	{
		for (var i = 0; i < 3; i++) {
			for(var j = 0; j<7; j++){
				array[i][j] = 0;
				$('td').removeAttr("style");
			}
		}
	}
}

function returnDay(index)
{
	switch(index){
		case 0:
		 return "Sunday";
		 break;
		case 1:
		 return "Monday";
		 break;
		case 2:
		 return "Tuesday";
		 break;
		case 3:
		 return "Wednesday";
		 break;
		case 4:
		 return "Thursday";
		 break;
		case 5:
		 return "Friday";
		 break;
		case 6:
		 return "Saturday";
		 break;
	}

}
<|endoftext|>


<commit_before>module.exports = function(Plan) {
/*

	Plan.observe('before delete', function(ctx, next) {
	console.log(ctx.where)
		console.log('c' + ctx.where['id']);

		app.models.CanvasItem.find( { where : {planId : ctx.where.id } }, function(err, items) {
			console.log('b');
			console.log('found ' + items.length + ' related');

		} )

		//console.log(CanvasItem);

	  	//console.log('Going to delete %s matching %j',
	   // ctx.Model.pluralModelName,
	   // ctx.where);

	  next();
	});*/

	Plan.observe('before save', function updateTimestamp(ctx, next) {

		// console.log('Going to update %s matching %j',
	 //    ctx.Model.pluralModelName,
	 //    ctx.where);

	  if (ctx.instance) {
	  	//create
	  	ctx.instance.created = new Date();
	    ctx.instance.updated = new Date();
	  } else {
	  	//update
	  	ctx.data.updated = new Date();
	  }

	  next();
	});

};
<commit_msg>delete canvas items when a plan is deleted<commit_after>module.exports = function(Plan) {

	Plan.observe('before delete', function (ctx, next) {

		//delete all canvas item in this plan
		var CanvasItem = ctx.Model.app.models.CanvasItem;

		CanvasItem.find({
			where: {
				planId: ctx.where.id
			}
		}, function (err, items) {
			items.forEach(function (item) {
				CanvasItem.destroyById(item.id, function () {

				});
			});
		});

		next();
	});

	Plan.observe('before save', function updateTimestamp(ctx, next) {

		if (ctx.instance) {
	  	//create
	  	ctx.instance.created = new Date();
	  	ctx.instance.updated = new Date();
	  } else {
	  	//update
	  	ctx.data.updated = new Date();
	  }

	  next();
	});

};
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * A GaugeNode with a NumberDisplay located in the center bottom half of the GaugeNode to
 * display the numerical value. The NumberDisplay can be hidden but is visible by default.
 *
 * @author Jesse Greenberg
 */

define( require => {
  'use strict';

  // modules
  const GaugeNode = require( 'SCENERY_PHET/GaugeNode' );
  const NumberDisplay = require( 'SCENERY_PHET/NumberDisplay' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  const Vector2 = require( 'DOT/Vector2' );

  // constants
  const NUMBER_DISPLAY_DEFAULT_OPTIONS = {
    font: new PhetFont( 16 ),
    backgroundStroke: 'black',
    align: 'center',
    cornerRadius: 5
  };

  class ValueGaugeNode extends GaugeNode {

    /**
     * @param  {Property.<Number>} valueProperty
     * @param  {string} label - label to display
     * @param  {Range} range
     * @param  {Object} options
     */
    constructor( valueProperty, label, range, options ) {

      options = _.extend( {

        // {*|null} options passed to the NumberDisplay, see NumberDisplay for full list
        numberDisplayOptions: null
      }, options );

      options.numberDisplayOptions = _.extend( {}, NUMBER_DISPLAY_DEFAULT_OPTIONS, options.numberDisplayOptions );

      super( valueProperty, label, range, options );

      // @private {boolean}
      this._numberDisplayVisible = true;

      // @private {NumberDisplay} - display for the valueProperty, hidden by default
      this.numberDisplay = new NumberDisplay( valueProperty, range, options.numberDisplayOptions );
      this.addChild( this.numberDisplay );

      assert && assert( this.numberDisplay.matrix.translation.equals( Vector2.ZERO ), 'ValueGaugeNode positions the NumberDisplay' );
      this.numberDisplay.center = new Vector2( 0, this.radius / 2 );
    }

    /**
     * Set whether or not the NumberDisplay inside this GaugeNode is visible.
     *
     * @public
     * @param {boolean} visible
     */
    setNumberDisplayVisible( visible ) {
      if ( visible !== this._numberDisplayVisible ) {
        this._numberDisplayVisible = visible;
        this.numberDisplay.visible = visible;
      }
    }
    set numberDisplayVisible( visible ) { this.setNumberDisplayVisible( visible ); }

    /**
     * Get whether or not the number display inside this GaugeNode is visible.
     *
     * @public
     * @return {boolean}
     */
    getNumberDisplayVisible() {
      return this._numberDisplayVisible;
    }
    get numberDisplayVisible() { return this.getNumberDisplayVisible(); }

    /**
     * @public
     * @override
     */
    dispose() {
      this.numberDisplay.dispose();
      super.dispose();
    }
  }

  return sceneryPhet.register( 'ValueGaugeNode', ValueGaugeNode );
} );
<commit_msg>remove incorrect documentation<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * A GaugeNode with a NumberDisplay located in the center bottom half of the GaugeNode to
 * display the numerical value. The NumberDisplay can be hidden but is visible by default.
 *
 * @author Jesse Greenberg
 */

define( require => {
  'use strict';

  // modules
  const GaugeNode = require( 'SCENERY_PHET/GaugeNode' );
  const NumberDisplay = require( 'SCENERY_PHET/NumberDisplay' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  const Vector2 = require( 'DOT/Vector2' );

  // constants
  const NUMBER_DISPLAY_DEFAULT_OPTIONS = {
    font: new PhetFont( 16 ),
    backgroundStroke: 'black',
    align: 'center',
    cornerRadius: 5
  };

  class ValueGaugeNode extends GaugeNode {

    /**
     * @param  {Property.<Number>} valueProperty
     * @param  {string} label - label to display
     * @param  {Range} range
     * @param  {Object} options
     */
    constructor( valueProperty, label, range, options ) {

      options = _.extend( {

        // {*|null} options passed to the NumberDisplay, see NumberDisplay for full list
        numberDisplayOptions: null
      }, options );

      options.numberDisplayOptions = _.extend( {}, NUMBER_DISPLAY_DEFAULT_OPTIONS, options.numberDisplayOptions );

      super( valueProperty, label, range, options );

      // @private {boolean}
      this._numberDisplayVisible = true;

      // @private {NumberDisplay} - display for the valueProperty
      this.numberDisplay = new NumberDisplay( valueProperty, range, options.numberDisplayOptions );
      this.addChild( this.numberDisplay );

      assert && assert( this.numberDisplay.matrix.translation.equals( Vector2.ZERO ), 'ValueGaugeNode positions the NumberDisplay' );
      this.numberDisplay.center = new Vector2( 0, this.radius / 2 );
    }

    /**
     * Set whether or not the NumberDisplay inside this GaugeNode is visible.
     *
     * @public
     * @param {boolean} visible
     */
    setNumberDisplayVisible( visible ) {
      if ( visible !== this._numberDisplayVisible ) {
        this._numberDisplayVisible = visible;
        this.numberDisplay.visible = visible;
      }
    }
    set numberDisplayVisible( visible ) { this.setNumberDisplayVisible( visible ); }

    /**
     * Get whether or not the number display inside this GaugeNode is visible.
     *
     * @public
     * @return {boolean}
     */
    getNumberDisplayVisible() {
      return this._numberDisplayVisible;
    }
    get numberDisplayVisible() { return this.getNumberDisplayVisible(); }

    /**
     * @public
     * @override
     */
    dispose() {
      this.numberDisplay.dispose();
      super.dispose();
    }
  }

  return sceneryPhet.register( 'ValueGaugeNode', ValueGaugeNode );
} );
<|endoftext|>


<commit_before>var languages = [
    ['en','none'],
    ['zh','Chinese'],
    ['id','Indonesian'],
    ['ja','Japanese'],
    ['kh','Khmer'],
    ['kr','Korean'],
    ['la','Laotian'],
    ['mn','Mongolian'],
    ['my','Myanmar'],
    ['pl','Polish'],
    ['ru','Russian'],
    ['th','Thai'],
    ['uz','Uzbek'],
    ['vn','Vietnamese']
]

function getExternalLeagueTablesData () {
    var adminID = getParameterByName('admin');
    var lst = apiRequest(
        '/?admin='
            + adminID
            + '&page=students'
            + '&cmd=getexternalleaguetables');
    if (false === lst || lst.length === 0) {
        var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
        externalLeagueTablesButton.style.display = 'none';
        return false;
    };
    return lst;
};

function showStudents () {
    var studentList = document.getElementById('student-list');
    var externalLeagueTables = document.getElementById('external-league-tables');
    externalLeagueTables.style.display = 'none';
    studentList.style.display = 'block';
    var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
    var mainDisplayButton = document.getElementById('main-display-button');
    externalLeagueTablesButton.style.display = 'inline';
    mainDisplayButton.style.display = 'none';
};

function showExternalLeagueTables () {
    var lst = getExternalLeagueTablesData();
    if (!lst) return;
    // Zero out the list
    var externalLeagueTablesList = document.getElementById('external-league-tables-list');
    for (var i=0,ilen=externalLeagueTablesList.childNodes.length;i<ilen;i+=1) {
        externalLeagueTablesList.removeChild(externalLeagueTablesList.childNodes[0]);
    }
    console.log("RESULT: "+JSON.stringify(lst,null,2));
    for (var i=0,ilen=lst.length;i<ilen;i+=1) {
        var correctPercentage = lst[i].correctPercentage;
        if (!correctPercentage) {
            correctPercentage = 0;
        }
        var rowTR = document.createElement('tr');
        rowTR.innerHTML = '' + lst[i].name + '	'
            + '' + lst[i].totalAnswers + '	'
            + '' + correctPercentage.toFixed(2) + '	'
        externalLeagueTablesList.appendChild(rowTR);
    }
    var studentList = document.getElementById('student-list');
    var externalLeagueTables = document.getElementById('external-league-tables');
    studentList.style.display = 'none';
    externalLeagueTables.style.display = 'block';
    var mainDisplayButton = document.getElementById('main-display-button');
    var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
    mainDisplayButton.style.display = 'inline';
    externalLeagueTablesButton.style.display = 'none';
};

function addStudent(node) {
    var bubbleOpen = document.getElementsByClassName('bubble-edit');
    if (!bubbleOpen || bubbleOpen.length === 0) {
        var addButton = document.getElementById('add-student-button');
        var saveButton = document.getElementById('save-student-button');
        var studentBoxes = document.getElementById('student-boxes');
        var languageNode = document.getElementById('student-language');
        languageNode.innerHTML = getLanguageOptions();
        addButton.style.display = 'none';
        saveButton.style.display = 'inline';
        studentBoxes.style.display = 'inline';
    }
}

function editStudent(node) {
    var studentBoxes = document.getElementById('student-boxes');
    var bubbleName = document.getElementById('bubble-name');
    if (studentBoxes.style.display === 'inline' || bubbleName) {
        return;
    }
    var editDiv = document.createElement('div');
    var name = node.textContent;
    var emailAndLang = node.getAttribute('alt');
    var email = emailAndLang.replace(/^(?:[a-z]*:)/,'');
    var langtag = emailAndLang.replace(/^([a-z]*):.*/,'$1');
    var id = node.getAttribute('id');
    var status = false;
    if (node.className && node.className.match(/private/)) {
        var status = 'private';
    };
    var checked = '';
    if (status) {
        checked = 'checked="true"';
    }
    var options = getLanguageOptions(langtag);
    editDiv.setAttribute('id',id);
    editDiv.setAttribute('class','bubble-edit');
    editDiv.innerHTML = 'Name: <input id="bubble-name" type="text" size="15" value="' + name + '"/> '
        + 'Email: <input id="bubble-email" type="text" size="25" value="' + email + '"/> '
        + 'External: ' + '<input id="bubble-privacy" type="checkbox" ' + checked +'/> '
        + 'Language: '
        + '<select id="bubble-language">'
        + options
        + '</select> '
        + '<input type="button" value="Save" onclick="saveEditStudent(this.parentNode)"/>'
    node.parentNode.replaceChild(editDiv,node);
}

function getLanguageOptions(langtag) {
    var options = '';
    for (var i=0,ilen=languages.length;i<ilen;i+=1) {
        var lang = languages[i];
        var selected = '';
        if (lang[0] === langtag) {
            selected=' selected="true"';
        }
        options += '<option value="' + lang[0] + '"' + selected +'/>' + lang[1] + '</option>';
    }
    return options;
}

function saveAddStudent(node) {
    // Need to add student ID, for edits
    var addButton = document.getElementById('add-student-button');
    var saveButton = document.getElementById('save-student-button');
    var studentBoxes = document.getElementById('student-boxes');
    var studentName = document.getElementById('student-name');
    var studentEmail = document.getElementById('student-email');
    var studentStatus = document.getElementById('student-status');
    var studentID = document.getElementById('student-id');
    // Values
    var name = studentName.value;
    var email = studentEmail.value;
    var status = studentStatus.checked;
    name = name ? name.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    email = email ? email.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    var id = studentID.value;

    var result = saveStudent(name,email,status,'en',id);

    if (result === 'empty' || result === 'done') {
        studentName.value = null;
        studentEmail.value = null;
        studentID.value = null;
        studentStatus.checked = false;
        // Redecorate
        addButton.style.display = 'inline';
        saveButton.style.display = 'none';
        studentBoxes.style.display = 'none';
    }
}

function saveEditStudent(node){
    var name = document.getElementById('bubble-name').value;
    var email = document.getElementById('bubble-email').value;
    var id = node.id;
    var privacy = document.getElementById('bubble-privacy').checked;
    var lang = document.getElementById('bubble-language').value;

    var result = saveStudent(name,email,privacy,lang,id);

    if (result === 'done') {
        var newNode = castStudentNode([name,email,id,privacy,lang]);
        node.parentNode.replaceChild(newNode,node);
    } else {
        var adminID = getParameterByName('admin');
        var obj = apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=readonestudent'
            , {
                studentid:id
            });
        if (false === obj) return;
        document.getElementById('bubble-name').value = obj.name;
        document.getElementById('bubble-email').value = obj.email;
    }
}

function saveStudent(name,email,status,language,id) {
    name = name ? name.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    email = email ? email.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    if (name && email) {
        // Save
        var adminID = getParameterByName('admin');
        apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=addstudent'
            , {
                email:email,
                name:name,
                studentid:id,
                lang:language,
                privacy:status
            });
        buildStudentList();
        return 'done';
    } else if (!name && !email && !id) {
        return 'empty';
    } else {
        alert('Both name and email are required');
        return 'partial';
    }
}

function buildStudentList (rows) {
    if (!rows) {
        // if rows is nil, call the server.
        var adminID = getParameterByName('admin');
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=readstudents');
        if (false === rows) return;
    }
    rows.sort(function (a,b) {
        // Sort by ???
        return a[0].localeCompare(b[0]);
    });
    // Delete children from container
    var container = document.getElementById('student-list');
    for (var i=0,ilen=container.childNodes.length;i<ilen;i+=1) {
        container.removeChild(container.childNodes[0]);
    }
    // Rebuild container content
    for (var i=0,ilen=rows.length;i<ilen;i+=1) {
        var newNode = castStudentNode(rows[i]);
        container.appendChild(newNode);
        var space = document.createTextNode(' ');
        container.appendChild(space);
    }
}

function castStudentNode (row) {
    // Row is:
    // 0:name
    // 1:email
    // 2:id
    // 3:privacy
    // 4:lang
    var nameSpan = document.createElement('span');
    nameSpan.innerHTML = row[0];
    nameSpan.setAttribute('title',row[4] + ':' + row[1]);
    nameSpan.setAttribute('alt',row[4] + ':' + row[1]);
    nameSpan.setAttribute('id',row[2]);
    if (row[3]) {
        nameSpan.setAttribute('class','bubble private');
    } else {
        nameSpan.setAttribute('class','bubble');
    }
    nameSpan.setAttribute('onclick', 'editStudent(this)');
    return nameSpan;
}
<commit_msg>Conceal league tables button when adding student<commit_after>var languages = [
    ['en','none'],
    ['zh','Chinese'],
    ['id','Indonesian'],
    ['ja','Japanese'],
    ['kh','Khmer'],
    ['kr','Korean'],
    ['la','Laotian'],
    ['mn','Mongolian'],
    ['my','Myanmar'],
    ['pl','Polish'],
    ['ru','Russian'],
    ['th','Thai'],
    ['uz','Uzbek'],
    ['vn','Vietnamese']
]

function getExternalLeagueTablesData () {
    var adminID = getParameterByName('admin');
    var lst = apiRequest(
        '/?admin='
            + adminID
            + '&page=students'
            + '&cmd=getexternalleaguetables');
    if (false === lst || lst.length === 0) {
        var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
        externalLeagueTablesButton.style.display = 'none';
        return false;
    };
    return lst;
};

function showStudents () {
    var studentList = document.getElementById('student-list');
    var externalLeagueTables = document.getElementById('external-league-tables');
    externalLeagueTables.style.display = 'none';
    studentList.style.display = 'block';
    var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
    var mainDisplayButton = document.getElementById('main-display-button');
    externalLeagueTablesButton.style.display = 'inline';
    mainDisplayButton.style.display = 'none';
};

function showExternalLeagueTables () {
    var lst = getExternalLeagueTablesData();
    if (!lst) return;
    // Zero out the list
    var externalLeagueTablesList = document.getElementById('external-league-tables-list');
    for (var i=0,ilen=externalLeagueTablesList.childNodes.length;i<ilen;i+=1) {
        externalLeagueTablesList.removeChild(externalLeagueTablesList.childNodes[0]);
    }
    console.log("RESULT: "+JSON.stringify(lst,null,2));
    for (var i=0,ilen=lst.length;i<ilen;i+=1) {
        var correctPercentage = lst[i].correctPercentage;
        if (!correctPercentage) {
            correctPercentage = 0;
        }
        var rowTR = document.createElement('tr');
        rowTR.innerHTML = '' + lst[i].name + '	'
            + '' + lst[i].totalAnswers + '	'
            + '' + correctPercentage.toFixed(2) + '	'
        externalLeagueTablesList.appendChild(rowTR);
    }
    var studentList = document.getElementById('student-list');
    var externalLeagueTables = document.getElementById('external-league-tables');
    studentList.style.display = 'none';
    externalLeagueTables.style.display = 'block';
    var mainDisplayButton = document.getElementById('main-display-button');
    var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
    mainDisplayButton.style.display = 'inline';
    externalLeagueTablesButton.style.display = 'none';
};

function addStudent(node) {
    var bubbleOpen = document.getElementsByClassName('bubble-edit');
    if (!bubbleOpen || bubbleOpen.length === 0) {
        var addButton = document.getElementById('add-student-button');
        var saveButton = document.getElementById('save-student-button');
        var studentBoxes = document.getElementById('student-boxes');
        var languageNode = document.getElementById('student-language');
        languageNode.innerHTML = getLanguageOptions();
        addButton.style.display = 'none';
        saveButton.style.display = 'inline';
        studentBoxes.style.display = 'inline';
        var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
        externalLeagueTablesButton.style.display = 'none';
    }
}

function editStudent(node) {
    var studentBoxes = document.getElementById('student-boxes');
    var bubbleName = document.getElementById('bubble-name');
    if (studentBoxes.style.display === 'inline' || bubbleName) {
        return;
    }
    var editDiv = document.createElement('div');
    var name = node.textContent;
    var emailAndLang = node.getAttribute('alt');
    var email = emailAndLang.replace(/^(?:[a-z]*:)/,'');
    var langtag = emailAndLang.replace(/^([a-z]*):.*/,'$1');
    var id = node.getAttribute('id');
    var status = false;
    if (node.className && node.className.match(/private/)) {
        var status = 'private';
    };
    var checked = '';
    if (status) {
        checked = 'checked="true"';
    }
    var options = getLanguageOptions(langtag);
    editDiv.setAttribute('id',id);
    editDiv.setAttribute('class','bubble-edit');
    editDiv.innerHTML = 'Name: <input id="bubble-name" type="text" size="15" value="' + name + '"/> '
        + 'Email: <input id="bubble-email" type="text" size="25" value="' + email + '"/> '
        + 'External: ' + '<input id="bubble-privacy" type="checkbox" ' + checked +'/> '
        + 'Language: '
        + '<select id="bubble-language">'
        + options
        + '</select> '
        + '<input type="button" value="Save" onclick="saveEditStudent(this.parentNode)"/>'
    node.parentNode.replaceChild(editDiv,node);
}

function getLanguageOptions(langtag) {
    var options = '';
    for (var i=0,ilen=languages.length;i<ilen;i+=1) {
        var lang = languages[i];
        var selected = '';
        if (lang[0] === langtag) {
            selected=' selected="true"';
        }
        options += '<option value="' + lang[0] + '"' + selected +'/>' + lang[1] + '</option>';
    }
    return options;
}

function saveAddStudent(node) {
    // Need to add student ID, for edits
    var addButton = document.getElementById('add-student-button');
    var saveButton = document.getElementById('save-student-button');
    var studentBoxes = document.getElementById('student-boxes');
    var studentName = document.getElementById('student-name');
    var studentEmail = document.getElementById('student-email');
    var studentStatus = document.getElementById('student-status');
    var studentID = document.getElementById('student-id');
    // Values
    var name = studentName.value;
    var email = studentEmail.value;
    var status = studentStatus.checked;
    name = name ? name.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    email = email ? email.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    var id = studentID.value;

    var result = saveStudent(name,email,status,'en',id);

    if (result === 'empty' || result === 'done') {
        studentName.value = null;
        studentEmail.value = null;
        studentID.value = null;
        studentStatus.checked = false;
        // Redecorate
        addButton.style.display = 'inline';
        saveButton.style.display = 'none';
        studentBoxes.style.display = 'none';
    }
    var externalLeagueTablesButton = document.getElementById('external-league-tables-button');
    externalLeagueTablesButton.style.display = 'inline';
}

function saveEditStudent(node){
    var name = document.getElementById('bubble-name').value;
    var email = document.getElementById('bubble-email').value;
    var id = node.id;
    var privacy = document.getElementById('bubble-privacy').checked;
    var lang = document.getElementById('bubble-language').value;

    var result = saveStudent(name,email,privacy,lang,id);

    if (result === 'done') {
        var newNode = castStudentNode([name,email,id,privacy,lang]);
        node.parentNode.replaceChild(newNode,node);
    } else {
        var adminID = getParameterByName('admin');
        var obj = apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=readonestudent'
            , {
                studentid:id
            });
        if (false === obj) return;
        document.getElementById('bubble-name').value = obj.name;
        document.getElementById('bubble-email').value = obj.email;
    }
}

function saveStudent(name,email,status,language,id) {
    name = name ? name.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    email = email ? email.replace(/^\s+/,'').replace(/\s+$/,'') : '';
    if (name && email) {
        // Save
        var adminID = getParameterByName('admin');
        apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=addstudent'
            , {
                email:email,
                name:name,
                studentid:id,
                lang:language,
                privacy:status
            });
        buildStudentList();
        return 'done';
    } else if (!name && !email && !id) {
        return 'empty';
    } else {
        alert('Both name and email are required');
        return 'partial';
    }
}

function buildStudentList (rows) {
    if (!rows) {
        // if rows is nil, call the server.
        var adminID = getParameterByName('admin');
        var rows = apiRequest(
            '/?admin='
                + adminID
                + '&page=students'
                + '&cmd=readstudents');
        if (false === rows) return;
    }
    rows.sort(function (a,b) {
        // Sort by ???
        return a[0].localeCompare(b[0]);
    });
    // Delete children from container
    var container = document.getElementById('student-list');
    for (var i=0,ilen=container.childNodes.length;i<ilen;i+=1) {
        container.removeChild(container.childNodes[0]);
    }
    // Rebuild container content
    for (var i=0,ilen=rows.length;i<ilen;i+=1) {
        var newNode = castStudentNode(rows[i]);
        container.appendChild(newNode);
        var space = document.createTextNode(' ');
        container.appendChild(space);
    }
}

function castStudentNode (row) {
    // Row is:
    // 0:name
    // 1:email
    // 2:id
    // 3:privacy
    // 4:lang
    var nameSpan = document.createElement('span');
    nameSpan.innerHTML = row[0];
    nameSpan.setAttribute('title',row[4] + ':' + row[1]);
    nameSpan.setAttribute('alt',row[4] + ':' + row[1]);
    nameSpan.setAttribute('id',row[2]);
    if (row[3]) {
        nameSpan.setAttribute('class','bubble private');
    } else {
        nameSpan.setAttribute('class','bubble');
    }
    nameSpan.setAttribute('onclick', 'editStudent(this)');
    return nameSpan;
}
<|endoftext|>


<commit_before>$(document).ready(
  function() {
    console.log('ready');

    var model = new AppModel();
    var handModel = model.handModel;
    var $tbody = $("table tbody")
    var $shapeRow = $tbody.find('tr.shape');
    var $totalRow = $tbody.find('tr.total');
    var $suitRow = {}
    handModel.suits().forEach(
        function(suit) {
            $suitRow[suit.short]=$tbody.find('tr.suit'+suit.short);
        }
    );

    var focusSpades = function() {
	$('input.holding#spades').focus();
    }

    var clearModel = function(e) {
          handModel.clear();
          $('input.holding').val('');
          $('#evaluationscontainer').hide();
	  focusSpades();
    };

     $('input.holding').bind("propertychange change click keyup input paste",
       function(event) {
         var $input = $(this);
         var $form = $(this.form)
         suitLabel = $input.data('suit');
         hString = $input.val().toUpperCase();
         if (hString != $input.val()) {
             $input.val(hString);
         }

         // if the string ends with 1, treat it as ending with 10, except when
         // exiting field, for purposes of validating entry inline
         if (hString.slice(-1)=='1' && event.type !='change' && event.type!='propertychange') {
             hString = hString+'0';
             appended = true;
         } else {
             appended = false;
         }

         var valid = handModel.setHolding(suitLabel,hString);
         if (!valid) {
           $input.addClass('invalid');
         } else {
           $input.removeClass('invalid');
         }

         if (handModel.isComplete() && !appended) {
           $form.find('input[type="submit"]').removeAttr('disabled');
         } else {
           $form.find('input[type="submit"]').attr('disabled','disabled');
         }
       }
    );
     window.onpopstate = function(event) {
         stateHash = handModel.urlHash()
         if (stateHash==null) {
             if (window.location.hash != '') {
                 initializeHash();
             }
         } else if (window.location.hash != '#' + stateHash) {
                 initializeHash();
         }
     }

     this.model = function() { return model; }
     var handleSubmit = function() {
         var container = $('#evaluationscontainer');
         container.hide(250);

         window.location.hash = handModel.urlHash()
         var shape = handModel.shape();
         $shapeRow.find('.key').text(shape.short);
         handModel.suits().forEach(
             function (suit) {
                 $suitRow[suit.short].find('.holding').text(handModel.holding(suit).display);
             }
         );
         var evaluations = model.evaluate();
         var toText = function(val) {
             if (val == null) {
                 return "n/a";
             } else {
                 return val;
             }
         }

         evaluations.forEach(
            function (evaluation) {
                var evalClass = '.' + evaluation['name'];
                var update = function(row,value) {
                    row.find(evalClass).html(toText(value));
                }

                update($shapeRow,evaluation.shape);
                update($totalRow,evaluation.total);
                handModel.suits().forEach(
                    function(suit) {
                        update($suitRow[suit.short],evaluation[suit.short])
                    }
                );
            }
         );

         container.finish();
         container.show('fast');
     }

     var initializeHash=function() {
         hash = window.location.hash
         clearModel();
         if (hash != '' && hash!='#' || hash!=null) {
            hStrings = hash.substring(1).split(',',4);
            map = {'S':'','H':'','D':'','C':'' }
            for (i=0; i<hStrings.length; i++) {
                suit = handModel.suits().entry(i).short;
                map[suit] = hStrings[i];
            }
            $('input.holding').each(
               function(index,entry) {
                   var $entry = $(entry);
                   $entry.val(map[$entry.data('suit')]);
                   $entry.triggerHandler('change');
               }
            );
            if (handModel.isComplete()) {
                handleSubmit();
            } else {
               $('#evaluationscontainer').hide(500);
            }

         }
     }

     initializeHash();

    $('#handentry').submit(
      function(e) {
        e.preventDefault();
        handleSubmit();
      }
    );

    $('input#clear').click(
       function (e) {
          clearModel();
          window.location.hash = '';
       }
    );
    var currentOpenNote = null;
    $('.notes h4').each(
       function() {
           var $this = $(this);
           $this.data('section',$this.next('.section'));
       }
    );

    $('.notes h4').click(function(e) {
         var $this = $(this);
	 if (currentOpenNote != null) {
	     currentOpenNote.data('section').hide(0);
             currentOpenNote.removeClass('selected');
	     if (currentOpenNote.html() == $this.html()) {
		 currentOpenNote = null;
		 return;
	     }
         }
	 currentOpenNote=$this;
	 $this.addClass('selected');
	 currentOpenNote.data('section').show(0);
      }
    );
    $('.notes h4#defaultSection').click();
    focusSpades();
  }
);

<commit_msg>Added feature to keep track of tab selected; really just a test of my understanding of local storage<commit_after>$(document).ready(
  function() {
    console.log('ready');

    var model = new AppModel();
    var handModel = model.handModel;
    var $tbody = $("table tbody")
    var $shapeRow = $tbody.find('tr.shape');
    var $totalRow = $tbody.find('tr.total');
    var $suitRow = {}
    handModel.suits().forEach(
        function(suit) {
            $suitRow[suit.short]=$tbody.find('tr.suit'+suit.short);
        }
    );

    var focusSpades = function() {
	$('input.holding#spades').focus();
    }

    var clearModel = function(e) {
          handModel.clear();
          $('input.holding').val('');
          $('#evaluationscontainer').hide();
	  focusSpades();
    };

     $('input.holding').bind("propertychange change click keyup input paste",
       function(event) {
         var $input = $(this);
         var $form = $(this.form)
         suitLabel = $input.data('suit');
         hString = $input.val().toUpperCase();
         if (hString != $input.val()) {
             $input.val(hString);
         }

         // if the string ends with 1, treat it as ending with 10, except when
         // exiting field, for purposes of validating entry inline
         if (hString.slice(-1)=='1' && event.type !='change' && event.type!='propertychange') {
             hString = hString+'0';
             appended = true;
         } else {
             appended = false;
         }

         var valid = handModel.setHolding(suitLabel,hString);
         if (!valid) {
           $input.addClass('invalid');
         } else {
           $input.removeClass('invalid');
         }

         if (handModel.isComplete() && !appended) {
           $form.find('input[type="submit"]').removeAttr('disabled');
         } else {
           $form.find('input[type="submit"]').attr('disabled','disabled');
         }
       }
    );
     window.onpopstate = function(event) {
         stateHash = handModel.urlHash()
         if (stateHash==null) {
             if (window.location.hash != '') {
                 initializeHash();
             }
         } else if (window.location.hash != '#' + stateHash) {
                 initializeHash();
         }
     }

     this.model = function() { return model; }
     var handleSubmit = function() {
         var container = $('#evaluationscontainer');
         container.hide(250);

         window.location.hash = handModel.urlHash()
         var shape = handModel.shape();
         $shapeRow.find('.key').text(shape.short);
         handModel.suits().forEach(
             function (suit) {
                 $suitRow[suit.short].find('.holding').text(handModel.holding(suit).display);
             }
         );
         var evaluations = model.evaluate();
         var toText = function(val) {
             if (val == null) {
                 return "n/a";
             } else {
                 return val;
             }
         }

         evaluations.forEach(
            function (evaluation) {
                var evalClass = '.' + evaluation['name'];
                var update = function(row,value) {
                    row.find(evalClass).html(toText(value));
                }

                update($shapeRow,evaluation.shape);
                update($totalRow,evaluation.total);
                handModel.suits().forEach(
                    function(suit) {
                        update($suitRow[suit.short],evaluation[suit.short])
                    }
                );
            }
         );

         container.finish();
         container.show('fast');
     }

     var initializeHash=function() {
         hash = window.location.hash
         clearModel();
         if (hash != '' && hash!='#' || hash!=null) {
            hStrings = hash.substring(1).split(',',4);
            map = {'S':'','H':'','D':'','C':'' }
            for (i=0; i<hStrings.length; i++) {
                suit = handModel.suits().entry(i).short;
                map[suit] = hStrings[i];
            }
            $('input.holding').each(
               function(index,entry) {
                   var $entry = $(entry);
                   $entry.val(map[$entry.data('suit')]);
                   $entry.triggerHandler('change');
               }
            );
            if (handModel.isComplete()) {
                handleSubmit();
            } else {
               $('#evaluationscontainer').hide(500);
            }

         }
     }

     initializeHash();

    $('#handentry').submit(
      function(e) {
        e.preventDefault();
        handleSubmit();
      }
    );

    $('input#clear').click(
       function (e) {
          clearModel();
          window.location.hash = '';
       }
    );

    var currentOpenNote = null;
    $('.notes h4').each(
       function() {
           var $this = $(this);
           $this.data('section',$this.next('.section'));
       }
    );

    var myStorage;
    if (typeof(Storage) !== "undefined") {
        myStorage = window.localStorage;
    } else {
	myStorage = null;
    }

    var storeNotesTab = function(name) {
        if (myStorage != null) {
            myStorage.setItem('NoteSelected',name);
        }
    }

    var getNotesTab = function() {
        if (myStorage === null) {
            return 'about';
        }
        value = myStorage.getItem('NoteSelected');
        if (value=='undefined') {
            return 'about';
        } else {
	    return value;
	}
    }

    $('.notes h4').click(function(e) {
         var $this = $(this);
	 storeNotesTab($this[0].id);
	 if (currentOpenNote != null) {
	     currentOpenNote.data('section').hide(0);
             currentOpenNote.removeClass('selected');
	     if (currentOpenNote.html() == $this.html()) {
		 currentOpenNote = null;
		 return;
	     }
         }
	 currentOpenNote=$this;
	 $this.addClass('selected');
	 currentOpenNote.data('section').show(0);
      }
    );
    var tab = getNotesTab();
    $('.notes h4#' +tab).click();
    focusSpades();
  }
);

<|endoftext|>


<commit_before>define(['underscore', 'newton'], function(_, Newton) {

    var Simulation = {};

    Simulation.create = function(spec) {
        var that = {},
            particles,
            distance,
            startAngleA,
            startAngleB;

        that.start = function() {
            var margin = 100,
                points = createPoints({
                    start: {
                        x: margin,
                        y: spec.height * 0.25
                    },
                    end: {
                        x: spec.width - margin,
                        y: spec.height * 0.75
                    },
                    count: spec.segments
                });

            var sim = createNewtonSimulation(points);
            sim.start();
        };

        var update = function(time, simulator, totalTime) {
            var step = totalTime * 0.001,
                scale = 1;

            rotateHandle(
                particles[1],
                particles[0],
                startAngleA + (Math.sin(step) * scale)
            );
            rotateHandle(
                particles[particles.length - 2],
                particles[particles.length - 1],
                startAngleB + (Math.sin(step) * scale)
            );
        };

        var rotateHandle = function(handleParticle, pivotParticle, angle) {
            var x = pivotParticle.position.x - distance * Math.cos(angle),
                y = pivotParticle.position.y - distance * Math.sin(angle);

            handleParticle.pin(x, y);
        };

        var createPoints = function(spec) {
            var points = [],
                count = spec.count,
                xDistance = spec.end.x - spec.start.x,
                yDistance = spec.end.y - spec.start.y,
                totalDistance = Math.sqrt( Math.pow(xDistance, 2) + Math.pow(yDistance, 2) ),
                fraction = 0;

            distance = totalDistance / spec.count;

            while (count--) {
                fraction = count / (spec.count - 1);
                points.push({
                    x: spec.start.x + (xDistance * fraction),
                    y: spec.start.y + (yDistance * fraction)
                });
            }
            return points;
        };

        var createNewtonSimulation = function(points) {
            var renderer = Newton.Renderer(spec.canvas),
                sim = Newton.Simulator(update, renderer.callback),
                world = Newton.Body();

            particles = [];

            sim.add(world);

            _(points).each(function(point, i) {
                var particle = Newton.Particle(point.x, point.y);
                particles.push(particle);
                world.addParticle(particle);
                if (i < 2 || i > points.length - 3) {
                    particle.pin();
                }
                if (i > 0) {
                    world.DistanceConstraint(particle, particles[i - 1], 1, distance);
                }
                if (i > 1) {
                    world.AngleConstraint(particle, particles[i - 1], particles[i - 2], 1);
                }
            });

            startAngleA = getAngleBetweenPoints(points[0], points[1]);
            startAngleB = getAngleBetweenPoints(points[points.length - 1], points[points.length - 2]);

            return sim;
        };

        var getAngleBetweenPoints = function(pointA, pointB) {
            var xDiff = pointA.x - pointB.x;
            var yDiff = pointA.y - pointB.y;
            return Math.atan2(yDiff, xDiff);
        };

        return that;
    };

    return Simulation;
});<commit_msg>Use crossed boxes instead of angle constraints as they're more stable<commit_after>define(['underscore', 'newton'], function(_, Newton) {

    var Simulation = {};

    Simulation.create = function(spec) {
        var that = {},
            layout,
            particles,
            startAngleA,
            startAngleB;

        that.start = function() {
            var margin = 100;

            layout = createLayout({
                start: {
                    x: margin,
                    y: spec.height * 0.25
                },
                end: {
                    x: spec.width - margin,
                    y: spec.height * 0.75
                },
                count: spec.segments
            });

            var sim = createNewtonSimulation();
            sim.start();
        };

        var update = function(time, simulator, totalTime) {
            var step = totalTime * 0.001,
                scale = 1,
                angleA = layout.angle + (Math.sin(step) * scale),
                angleB = layout.angle + (Math.cos(step) * scale),
                startIndex = 0,
                endIndex = spec.segments - 1;

            rotateHandle(particles[startIndex + 1], layout.points[startIndex], angleA, layout.distance);
            rotateHandle(particles[startIndex], layout.points[startIndex], angleA, 0);

            rotateHandle(particles[endIndex - 1], layout.points[endIndex], angleB, layout.distance * -1);
            rotateHandle(particles[endIndex], layout.points[endIndex], angleB, 0);
        };

        var rotateHandle = function(handle, centerPoint, angle, distance) {
            var handlePoint = getCoordsForAngle(angle, centerPoint, distance),
                perpendicular = angle + Math.PI / 2,
                topCoords = getCoordsForAngle(perpendicular, handlePoint, layout.thickness * -0.5),
                bottomCoords = getCoordsForAngle(perpendicular, handlePoint, layout.thickness * 0.5);

            handle.top.pin(topCoords.x, topCoords.y);
            handle.bottom.pin(bottomCoords.x, bottomCoords.y);
        };

        var getCoordsForAngle = function(angle, center, distance) {
            return {
                x: center.x - distance * Math.cos(angle),
                y: center.y - distance * Math.sin(angle)
            }
        };

        var createLayout = function(spec) {
            var points = [],
                count = spec.count,
                xDistance = spec.end.x - spec.start.x,
                yDistance = spec.end.y - spec.start.y,
                totalDistance = Math.sqrt( Math.pow(xDistance, 2) + Math.pow(yDistance, 2) ),
                fraction = 0;

            while (count--) {
                fraction = count / (spec.count - 1);
                points.push({
                    x: spec.start.x + (xDistance * fraction),
                    y: spec.start.y + (yDistance * fraction)
                });
            }

            return {
                points: points,
                angle: getAngleBetweenPoints(points[0], points[spec.count - 1]),
                distance: totalDistance / spec.count,
                thickness: 10
            };
        };

        var createNewtonSimulation = function() {
            var renderer = Newton.Renderer(spec.canvas),
                sim = Newton.Simulator(update, renderer.callback),
                world = Newton.Body(),
                perpendicular = layout.angle + Math.PI / 2,
                distance = layout.distance * 1.2;

            particles = [];

            sim.add(world);

            _(layout.points).each(function(point, i) {
                var topCoords       = getCoordsForAngle(perpendicular, point, layout.thickness * -0.5),
                    bottomCoords    = getCoordsForAngle(perpendicular, point, layout.thickness * 0.5),
                    particle = {
                        top:    Newton.Particle(topCoords.x, topCoords.y),
                        bottom: Newton.Particle(bottomCoords.x, bottomCoords.y)
                    };

                particles.push(particle);

                world.addParticle(particle.top);
                world.addParticle(particle.bottom);

                world.DistanceConstraint(particle.top, particle.bottom, 1, layout.thickness);

                if (i < 2 || i > layout.points.length - 3) {
                    particle.top.pin();
                    particle.bottom.pin();
                }

                if (i > 0) {
                    world.DistanceConstraint(particle.top,      particles[i - 1].top,       1, distance);
                    world.DistanceConstraint(particle.bottom,   particles[i - 1].bottom,    1, distance);
                    world.DistanceConstraint(particle.bottom,   particles[i - 1].top,       1, distance);
                    world.DistanceConstraint(particle.top,      particles[i - 1].bottom,    1, distance);
                }
            });

            return sim;
        };

        var getAngleBetweenPoints = function(pointA, pointB) {
            var xDiff = pointA.x - pointB.x;
            var yDiff = pointA.y - pointB.y;
            return Math.atan2(yDiff, xDiff);
        };

        return that;
    };

    return Simulation;
});<|endoftext|>


<commit_before>'use strict';

const { iso8601 } = require ('ccxt/js/base/functions/time')
const { extend, deepExtend } = require ('ccxt/js/base/functions/generic.js')
    , {
        Asks,
        Bids,
        CountedAsks,
        CountedBids,
        IndexedAsks,
        IndexedBids,
        IncrementalAsks,
        IncrementalBids,
        IncrementalIndexedAsks,
        IncrementalIndexedBids,
    } = require ('./OrderBookSide')

// ----------------------------------------------------------------------------
// overwrites absolute volumes at price levels

class OrderBook {

    constructor (snapshot = {}, depth = undefined) {

        Object.defineProperty (this, 'cache', {
            __proto__: null, // make it invisible
            value: [],
            writable: true,
        })

        depth = depth || Number.MAX_SAFE_INTEGER

        const defaults = {
            'bids': [],
            'asks': [],
            'timestamp': undefined,
            'datetime': undefined,
            'nonce': undefined,
            'symbol': undefined,
        }

        // merge to this
        const entries = Object.entries (extend (defaults, snapshot))
        for (let i = 0; i < entries.length; i++) {
            const [property, value] = entries[i]
            this[property] = value
        }

        // wrap plain arrays with Bids/Asks classes if necessary
        if (this.asks.constructor.name === 'Array') {
            this.asks = new Asks (this.asks, depth)
        }
        if (this.bids.constructor.name === 'Array') {
            this.bids = new Bids (this.bids, depth)
        }
        if (this.timestamp) {
            this.datetime = iso8601 (this.timestamp)
        }
    }

    limit (n = undefined) {
        this.asks.limit (n)
        this.bids.limit (n)
        return this
    }

    update (snapshot) {
        if ((snapshot.nonce !== undefined) &&
            (this.nonce !== undefined) &&
            (snapshot.nonce <= this.nonce)) {
            return this
        }
        this.nonce = snapshot.nonce
        this.timestamp = snapshot.timestamp
        this.datetime = iso8601 (this.timestamp)
        return this.reset (snapshot)
    }

    reset (snapshot = {}) {
        this.asks.index.clear ()
        if (snapshot.asks) {
            for (let i = 0; i < snapshot.asks.length; i++) {
                this.asks.storeArray (snapshot.asks[i])
            }
        }
        this.bids.index.clear ()
        if (snapshot.bids) {
            for (let i = 0; i < snapshot.bids.length; i++) {
                this.bids.storeArray (snapshot.bids[i])
            }
        }
        this.nonce = snapshot.nonce
        this.timestamp = snapshot.timestamp
        this.datetime = iso8601 (this.timestamp)
        return this
    }
}

// ----------------------------------------------------------------------------
// overwrites absolute volumes at price levels
// or deletes price levels based on order counts (3rd value in a bidask delta)

class CountedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new CountedAsks (snapshot.asks || [], depth),
            'bids': new CountedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// indexed by order ids (3rd value in a bidask delta)

class IndexedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IndexedAsks (snapshot.asks || [], depth),
            'bids': new IndexedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// adjusts the volumes by positive or negative relative changes or differences

class IncrementalOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IncrementalAsks (snapshot.asks || [], depth),
            'bids': new IncrementalBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// incremental and indexed (2 in 1)

class IncrementalIndexedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IncrementalIndexedAsks (snapshot.asks || [], depth),
            'bids': new IncrementalIndexedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------

module.exports = {
    OrderBook,
    CountedOrderBook,
    IndexedOrderBook,
    IncrementalOrderBook,
    IncrementalIndexedOrderBook,
}
<commit_msg>disable max classes per file for OrderBook.js<commit_after>/* eslint-disable max-classes-per-file */

'use strict';

const { iso8601 } = require ('ccxt/js/base/functions/time')
const { extend, deepExtend } = require ('ccxt/js/base/functions/generic.js')
    , {
        Asks,
        Bids,
        CountedAsks,
        CountedBids,
        IndexedAsks,
        IndexedBids,
        IncrementalAsks,
        IncrementalBids,
        IncrementalIndexedAsks,
        IncrementalIndexedBids,
    } = require ('./OrderBookSide')

// ----------------------------------------------------------------------------
// overwrites absolute volumes at price levels

class OrderBook {

    constructor (snapshot = {}, depth = undefined) {

        Object.defineProperty (this, 'cache', {
            __proto__: null, // make it invisible
            value: [],
            writable: true,
        })

        depth = depth || Number.MAX_SAFE_INTEGER

        const defaults = {
            'bids': [],
            'asks': [],
            'timestamp': undefined,
            'datetime': undefined,
            'nonce': undefined,
            'symbol': undefined,
        }

        // merge to this
        const entries = Object.entries (extend (defaults, snapshot))
        for (let i = 0; i < entries.length; i++) {
            const [property, value] = entries[i]
            this[property] = value
        }

        // wrap plain arrays with Bids/Asks classes if necessary
        if (this.asks.constructor.name === 'Array') {
            this.asks = new Asks (this.asks, depth)
        }
        if (this.bids.constructor.name === 'Array') {
            this.bids = new Bids (this.bids, depth)
        }
        if (this.timestamp) {
            this.datetime = iso8601 (this.timestamp)
        }
    }

    limit (n = undefined) {
        this.asks.limit (n)
        this.bids.limit (n)
        return this
    }

    update (snapshot) {
        if ((snapshot.nonce !== undefined) &&
            (this.nonce !== undefined) &&
            (snapshot.nonce <= this.nonce)) {
            return this
        }
        this.nonce = snapshot.nonce
        this.timestamp = snapshot.timestamp
        this.datetime = iso8601 (this.timestamp)
        return this.reset (snapshot)
    }

    reset (snapshot = {}) {
        this.asks.index.clear ()
        if (snapshot.asks) {
            for (let i = 0; i < snapshot.asks.length; i++) {
                this.asks.storeArray (snapshot.asks[i])
            }
        }
        this.bids.index.clear ()
        if (snapshot.bids) {
            for (let i = 0; i < snapshot.bids.length; i++) {
                this.bids.storeArray (snapshot.bids[i])
            }
        }
        this.nonce = snapshot.nonce
        this.timestamp = snapshot.timestamp
        this.datetime = iso8601 (this.timestamp)
        return this
    }
}

// ----------------------------------------------------------------------------
// overwrites absolute volumes at price levels
// or deletes price levels based on order counts (3rd value in a bidask delta)

class CountedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new CountedAsks (snapshot.asks || [], depth),
            'bids': new CountedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// indexed by order ids (3rd value in a bidask delta)

class IndexedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IndexedAsks (snapshot.asks || [], depth),
            'bids': new IndexedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// adjusts the volumes by positive or negative relative changes or differences

class IncrementalOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IncrementalAsks (snapshot.asks || [], depth),
            'bids': new IncrementalBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------
// incremental and indexed (2 in 1)

class IncrementalIndexedOrderBook extends OrderBook {
    constructor (snapshot = {}, depth = undefined) {
        super (extend (snapshot, {
            'asks': new IncrementalIndexedAsks (snapshot.asks || [], depth),
            'bids': new IncrementalIndexedBids (snapshot.bids || [], depth),
        }))
    }
}

// ----------------------------------------------------------------------------

module.exports = {
    OrderBook,
    CountedOrderBook,
    IndexedOrderBook,
    IncrementalOrderBook,
    IncrementalIndexedOrderBook,
}
<|endoftext|>


<commit_before>const db = require('APP/db')
const Character = db.model('characters')

const enemies = require('./enemies.json')
const GamePlayers = {}
const GameEnemies = {}
const GameItems = {}
const collisionArrays = {}
const isUpdating = {}

const EasystarConstructor = require('easystarjs')

const findClosestPlayer = require('./utils').findClosestPlayer

const mapWidth = 60
const mapHeight = 60

const enemyMovement = (io, state) => {
  Object.keys(GameEnemies[state]).forEach(enemyName => {
    const enemy = GameEnemies[state][enemyName]
    const closestPlayer = findClosestPlayer(GamePlayers[state], enemy)
    if (closestPlayer) {
      collisionArrays[state].findPath(
        Math.floor(enemy.x / mapWidth),
        Math.floor(enemy.y / mapHeight),
        Math.floor(closestPlayer.x / mapWidth),
        Math.floor(closestPlayer.y / mapHeight),
        path => {
          if (path && path[1]) {
            const newX = path[1].x * mapWidth
            const newY = path[1].y * mapHeight
            const distance = 1
            enemy.x += newX - enemy.x > 0 ? distance : -distance
            enemy.y += newY - enemy.y > 0 ? distance : -distance
            const newPos = { x: enemy.x, y: enemy.y }
            io.sockets.to(state).emit('updateEnemy', newPos, enemyName)
          }
        })
      collisionArrays[state].calculate()
    }
  })
}

const spawnEnemy = (io, state) => {
  enemies[state].forEach((enemy) => {
    if (!GameEnemies[state][enemy.name]) {
      GameEnemies[state][enemy.name] = Object.assign({}, enemy)
      io.sockets.to(state).emit('addEnemy', enemy)
    }
  })
}

const runIntervals = (io, state) => {
  setInterval(() => enemyMovement(io, state), 33)
  setInterval(() => spawnEnemy(io, state), 10000)
}

const socketFunction = io => {
  io.on('connection', socket => {
    console.log('got a connection', socket.id)
    let room = 'world'
    socket.join(room)

    socket.on('disconnect', () => {
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }
      console.log(socket.id, 'disconnected')
    })

    socket.on('updatePlayer', player => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id] = Object.assign({}, GamePlayers[room][socket.id], { x: player.playerPos.x, y: player.playerPos.y, lootCount: player.lootCount })
        socket.broadcast.to(room).emit('updatePlayer', socket.id, player)
      }
    })

    socket.on('fireProjectile', (xCoord, yCoord) => {
      socket.broadcast.to(room).emit('fireProjectile', socket.id, xCoord, yCoord)
    })

    socket.on('killEnemy', name => {
      if (GameEnemies[room]) {
        delete GameEnemies[room][name]
        socket.broadcast.to(room).emit('removeEnemy', name)
      }
    })

    socket.on('createItem', item => {
      GameItems[room][item.name] = Object.assign({}, item)
      socket.broadcast.to(room).emit('addItem', item)
    })

    socket.on('killItem', name => {
      if (GameItems[room]) {
        delete GameItems[room][name]
        socket.broadcast.to(room).emit('removeItem', name)
      }
    })

    socket.on('setupState', (player, collisionMap, newRoom) => {
      // remove player from previous map (room)
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }

      // join new map
      socket.leave(room)
      room = newRoom
      socket.join(room)
      if (!GamePlayers[room]) GamePlayers[room] = {}
      if (!GameEnemies[room]) GameEnemies[room] = {}

      // get all players and enemies on the map
      socket.emit('getPlayers', GamePlayers[room])
      socket.emit('getEnemies', GameEnemies[room])

      // add player to map
      GamePlayers[room][socket.id] = player
      socket.broadcast.to(room).emit('addPlayer', socket.id, player)

      if (!collisionArrays[room]) {
        collisionArrays[room] = new EasystarConstructor.js()
        collisionArrays[room].setGrid(collisionMap)
        collisionArrays[room].setAcceptableTiles([0])
        collisionArrays[room].enableDiagonals()
      }

      if (!isUpdating[room]) {
        isUpdating[room] = true
        runIntervals(io, room)
      }
    })

    socket.on('savePlayer', player => {
      Character.update(player, {
        where: {
          id: player.id
        },
      })
    })
  })
}

module.exports = socketFunction
<commit_msg>fix merge conflict correction<commit_after>const db = require('APP/db')
const Character = db.model('characters')

const enemies = require('./enemies.json')
const GamePlayers = {}
const GameEnemies = {}
const GameItems = {}
const collisionArrays = {}
const isUpdating = {}

const EasystarConstructor = require('easystarjs')

const findClosestPlayer = require('./utils').findClosestPlayer

const mapWidth = 60
const mapHeight = 60

const enemyMovement = (io, state) => {
  Object.keys(GameEnemies[state]).forEach(enemyName => {
    const enemy = GameEnemies[state][enemyName]
    const closestPlayer = findClosestPlayer(GamePlayers[state], enemy)
    if (closestPlayer) {
      collisionArrays[state].findPath(
        Math.floor(enemy.x / mapWidth),
        Math.floor(enemy.y / mapHeight),
        Math.floor(closestPlayer.x / mapWidth),
        Math.floor(closestPlayer.y / mapHeight),
        path => {
          if (path && path[1]) {
            const newX = path[1].x * mapWidth
            const newY = path[1].y * mapHeight
            const distance = 1
            enemy.x += newX - enemy.x > 0 ? distance : -distance
            enemy.y += newY - enemy.y > 0 ? distance : -distance
            const newPos = { x: enemy.x, y: enemy.y }
            io.sockets.to(state).emit('updateEnemy', newPos, enemyName)
          }
        })
      collisionArrays[state].calculate()
    }
  })
}

const spawnEnemy = (io, state) => {
  enemies[state].forEach((enemy) => {
    if (!GameEnemies[state][enemy.name]) {
      GameEnemies[state][enemy.name] = Object.assign({}, enemy)
      io.sockets.to(state).emit('addEnemy', enemy)
    }
  })
}

const runIntervals = (io, state) => {
  setInterval(() => enemyMovement(io, state), 33)
  setInterval(() => spawnEnemy(io, state), 10000)
}

const socketFunction = io => {
  io.on('connection', socket => {
    console.log('got a connection', socket.id)
    let room = 'world'
    socket.join(room)

    socket.on('disconnect', () => {
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }
      console.log(socket.id, 'disconnected')
    })

    socket.on('updatePlayer', player => {
      if (GamePlayers[room]) {
        GamePlayers[room][socket.id] = Object.assign({}, GamePlayers[room][socket.id], { x: player.playerPos.x, y: player.playerPos.y, lootCount: player.lootCount })
        socket.broadcast.to(room).emit('updatePlayer', socket.id, player)
      }
    })

    socket.on('fireProjectile', (xCoord, yCoord) => {
      socket.broadcast.to(room).emit('fireProjectile', socket.id, xCoord, yCoord)
    })

    socket.on('killEnemy', name => {
      if (GameEnemies[room]) {
        delete GameEnemies[room][name]
        socket.broadcast.to(room).emit('removeEnemy', name)
      }
    })

    socket.on('createItem', item => {
      GameItems[room][item.name] = Object.assign({}, item)
      socket.broadcast.to(room).emit('addItem', item)
    })

    socket.on('killItem', name => {
      if (GameItems[room]) {
        delete GameItems[room][name]
        socket.broadcast.to(room).emit('removeItem', name)
      }
    })

    socket.on('setupState', (player, collisionMap, newRoom) => {
      // remove player from previous map (room)
      if (GamePlayers[room]) {
        delete GamePlayers[room][socket.id]
        socket.broadcast.to(room).emit('removePlayer', socket.id)
      }

      // join new map
      socket.leave(room)
      room = newRoom
      socket.join(room)
      if (!GamePlayers[room]) GamePlayers[room] = {}
      if (!GameEnemies[room]) GameEnemies[room] = {}
      if (!GameItems[room]) GameItems[room] = {}

      // get all players and enemies on the map
      socket.emit('getPlayers', GamePlayers[room])
      socket.emit('getEnemies', GameEnemies[room])
      socket.emit('getItems', GameItems[room])

      // add player to map
      GamePlayers[room][socket.id] = player
      socket.broadcast.to(room).emit('addPlayer', socket.id, player)

      if (!collisionArrays[room]) {
        collisionArrays[room] = new EasystarConstructor.js()
        collisionArrays[room].setGrid(collisionMap)
        collisionArrays[room].setAcceptableTiles([0])
        collisionArrays[room].enableDiagonals()
      }

      if (!isUpdating[room]) {
        isUpdating[room] = true
        runIntervals(io, room)
      }
    })

    socket.on('savePlayer', player => {
      Character.update(player, {
        where: {
          id: player.id
        },
      })
    })
  })
}

module.exports = socketFunction
<|endoftext|>