<commit_before>/**
 *   Drag & Drop Web Workspace
 *   Copyright (C) 2015 eCaresoft Inc
 *   Ernesto Angel Celis de la Fuente <developer@celisdelafuente.net>
 *
 *   This file is part of Iridescence Smart Connector
 *
 *   Iridescence Smart Connector is free software: you can redistribute it
 *   under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or (at
 *   your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
  Triggered when a shape starts moving
*/
var dragger = function() {
  // TODO Fix for paths
  switch(this.type) {
    case "rect":
      this.ox = this.attr("x");
      this.oy = this.attr("y");
      break;
    case "circle":
    case "ellipse":
      this.ox = this.attr("cx");
      this.oy = this.attr("cy");
      break;
  }
  this.animate({"fill-opacity": .2}, 500);
}

/**
  Triggered when a shape is moving
  */
var move = function(dx, dy) {
  var coordinates;
  if (this.type == "rect") {
    coordinates = {x: this.ox + dx, y: this.oy + dy};
  } else {
    coordinates = { cx: this.ox + dx, cy: this.oy + dy};
  }
  this.attr(coordinates);
  // TODO
  for(var i = connections.length; i--;) {
    paper.connection(connections[i]);
  }
  paper.safari();
}

/**
  Triggered when a shape stops moving
  */
var up = function() {
  this.animate({"fill-opacity": 0}, 500);
}

/**
 * Triggers when an element from Toolbar is dragged into workspace
 * @method toolUp
 * */
var release = function() {
  this.attr("x", toolbarX + 5);
  this.attr("y", toolbarY + 5);
  addToDiagram(this);
}

/**
 * Triggered when a shape is clicked, populates the
 * properties panel
 * @method modify
 * */
var modify = function() {
  var property = this.data("props");
  switch(this.type) {
    case "rect":
      if (connect.length < 2) {   // If the connection queue's length < 2
        if(connect[0] != this) {  // and If shape isn't already in queue
          connect.push(this);     // add shape to queue
        }
      }
      $('#step-name').val(property.name);
      $('#step-url').val(property.url);
      $('#step-id').val(this.id);
      $('#properties a[href="#connector"]').tab('show');
      break;
    case "path":
      $('#properties a[href="#connection"]').tab('show');
      break;
  }
}

var setData = function(shape) {
  var d = new DataModel();
  shape.data("props", d);
}

/**
 * Add a new element from Toolbar to Workspace
 * @method addToDiagram
 * @param {Object} shape Raphael Element object
 * */
var addToDiagram = function (shape) {
  var color = Raphael.getColor(); // Get next color in spectrum
  if(shape.type === "path") {
    if(connect.length == 2) {     // Create a connection between adapters
      var newConnection = paper.connection(connect[0], connect[1], "#000");
      newConnection.line.attr({
          "title": id = connect[0].id + 'to' + connect[1].id,
          "stroke-width": 3});
      newConnection.line.click(modify);
      connections.push(newConnection);
      workspace.push(newConnection.line);
      connect = [];               // Empty queue
    } else {
      return;                     // 2 shapes in queue are required
    }                             // to make a connection
  } else {
    var newShape = shape.clone();   // Hello Dolly!
    setData(newShape);              // Give Dolly a Soul
    newShape.attr({fill: color,
                  stroke: color,
                  "fill-opacity": 0,
                  "stroke-width": 3,
                  "width": 50,
                  "height": 30,
                  "x": 50 + Math.floor(Math.random()*160),
                  "y": 70 + Math.floor(Math.random()*160)});
    newShape.drag(move, dragger, up).click(modify);
    workspace.push(newShape);   // Append new shape to workspace
    if(workspace.length == 1) {   // If workspace empty we start from scratch
      connect.push(startShape);
      connect.push(newShape);
      var firstConnection = paper.connection(connect[0], connect[1], "#000");
      firstConnection.line.attr({
          "title": id = connect[0].id + 'to' + connect[1].id,
          "stroke-width": 3});
      firstConnection.line.click(modify);
      connections.push(firstConnection); // connect to the begining
      workspace.push(firstConnection.line);
    }
  }
}

var util = new Util();
// Global settings
var connections = [];               // Connections between shapes
var connect = [];                   // Temporary queue for connections
var workspace_metadata = function() {};
workspace_metadata.prototype.type;
workspace_metadata.prototype.guid;
workspace_metadata.prototype.name;
workspace_metadata.prototype.comments;
var workspace_meta = new workspace_metadata();

var allInputs = $(":input");                // Properties list
var toolbarX = 4,
  toolbarY = 4,
  toolbarWidth = 40,
  toolBarHeigth = 300,
  paperWidth = 768,
  paperHeigth = 500;
var paper = Raphael("work-canvas",
                    paperWidth, paperHeigth);  // Creates canvas 320×200@10,50
var workspace = paper.set();            // Create a default workspace
var work_guid = util.guid();
var toolbar = paper.rect(toolbarX, toolbarY,
                         toolbarWidth,
                         toolBarHeigth); // Placeholder for the tools
// We'll derive other shapes from this one
var basicShape = paper
  .rect(toolbarX + 5, toolbarY + 5, 30, 20)
  .attr({"fill": "#CCC",
        "fill-opacity": 0,
        "stroke-width": 3,
        cursor: "move"});
// Same as basicShape its a basic connector, derive other from it
var connectShape = paper
  .path("M9 35L40 60")
  .attr({"stroke-width": 3,
        cursor: "move"});
// TODO Moar shapes

// Start and End shapes, there should be one of each by default
// in every workspace
var startShape = paper
  .circle(toolbarX + 80, toolbarY + 75, 15)
  .attr({"fill": "#7AC200",
        "fill-opacity": 100,
        "stroke-width": 3,
        "stroke": "#298500",
        cursor: "move"})
  .data("props", {"type":"start"});

var endShape = paper
  .circle(paperWidth - 80, paperHeigth - 75, 15)
  .attr({"fill": "#D21C00",
        "fill-opacity": 100,
        "stroke-width": 3,
        "stroke": "#990000",
        cursor: "move"})
  .data("props", {"type":"end"});

/**
 * Remove shape from workspace
 * @method remove
 * @param {Integer} id of the Raphael element
 * */
var remove = function(id) {
  // TODO Fix this, should be donw within w.remove
  var shape = paper.getById(id);
  workspace.exclude(s);
  shape.remove();
}

/**
 * Clone a shape by id
 * @method cloneBlk
 * @param {Integer} id of the Raphael element
 * */
var clone = function(id) {
  addToDiagram(paper.getById(id));
}

/**
 * Update the shape properties data 'props' with values from
 * the properties panel
 * @method updateShape
 * @param {Integer} id of Raphael element
 * */
var update = function(id) {
  // TODO Fix it, values get borked in the panel
  var s = paper.getById(id);
  s.data("props").id = id;
  s.data("props").type = $('#step-type').val();
  s.data("props").name = $('#step-name').val();
  s.data("props").url = $('#step-url').val();
  s.attr({'title': s.data("props").name,
          'text':s.data("props").name});
}

/**
 * Save workspace to YAML in the server
 * @method save
 * */
var save = function() {
  //TODO
  var payload = [];
  workspace.forEach(function(s) {
    payload.push(s.data("props"));
  });
  $.post("/api/", {"__anti-forgery-token": $('#__anti-forgery-token').val(),
         "workspace":JSON.stringify(payload)});
}

var updateWorkspace = function() {
  workspace_meta.type = $('#work-type').val();
  workspace_meta.guid= $('#work-guid').val()
  workspace_meta.name = $('#work-name').val()
  workspace_meta.comments = $('#work-comments').val()

}

$('#work-guid').val(work_guid);
$('#work-guid-label').html("Id: " + work_guid);
// Attach listeners to Toolbar elements
basicShape.drag(move, dragger, release);
connectShape.click(function(){addToDiagram(this)});
startShape.drag(move, dragger, function(){});
endShape.drag(move, dragger, function(){});
// Bind listeners to Properties controls
// TODO Do this in one iteration of all
$('#work-type-lst li a').on("click change", function(){
  var type = $(this).text().toUpperCase().replace(' ','').replace('.','');
  $('#btn-work-type').html(type + '');
  $('#work-type').val(type);
});
$('#workspace :input').on("click change keyup", function() {
  updateWorkspace();
});
$('#step-type-lst li a').on("click change", function(){
  var type = $(this).text().toUpperCase().replace(' ','');
  $('#btn-step-type').html(type + '');
  $('#step-type').val(type);
  update($('#step-id').val());
});
$('#connector :input').on("click change keyup", function(){
  update($('#step-id').val());
});
$('#remove-btn').click(function(){remove($('#step-id').val())});
$('#clone-btn').click(function(){clone($('#step-id').val())});
$('#save-btn').click(function(){save()});

<commit_msg>WIP GUI Destination<commit_after>/**
 *   Drag & Drop Web Workspace
 *   Copyright (C) 2015 eCaresoft Inc
 *   Ernesto Angel Celis de la Fuente <developer@celisdelafuente.net>
 *
 *   This file is part of Iridescence Smart Connector
 *
 *   Iridescence Smart Connector is free software: you can redistribute it
 *   under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or (at
 *   your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Workspace Metadata
 */
var workspace_metadata = function() {};
workspace_metadata.prototype.type;
workspace_metadata.prototype.guid;
workspace_metadata.prototype.name;
workspace_metadata.prototype.comments;

/**
  Triggered when a shape starts moving
*/
var dragger = function() {
  // TODO Fix for paths
  switch(this.type) {
    case "rect":
      this.ox = this.attr("x");
      this.oy = this.attr("y");
      break;
    case "circle":
    case "ellipse":
      this.ox = this.attr("cx");
      this.oy = this.attr("cy");
      break;
  }
  this.animate({"fill-opacity": .2}, 500);
}

/**
  Triggered when a shape is moving
  */
var move = function(dx, dy) {
  var coordinates;
  if (this.type == "rect") {
    coordinates = {x: this.ox + dx, y: this.oy + dy};
  } else {
    coordinates = { cx: this.ox + dx, cy: this.oy + dy};
  }
  this.attr(coordinates);
  // TODO
  for(var i = connections.length; i--;) {
    paper.connection(connections[i]);
  }
  paper.safari();
}

/**
  Triggered when a shape stops moving
  */
var up = function() {
  this.animate({"fill-opacity": 0}, 500);
}

/**
 * Triggers when an element from Toolbar is dragged into workspace
 * @method toolUp
 * */
var release = function() {
  this.attr("x", toolbarX + 5);
  this.attr("y", toolbarY + 5);
  addToDiagram(this);
}

/**
 * Triggered when a shape is clicked, populates the
 * properties panel
 * @method modify
 * */
var modify = function() {
  var property = this.data("props");
  switch(this.type) {
    case "rect":
      if (connect.length < 2) {   // If the connection queue's length < 2
        if(connect[0] != this) {  // and If shape isn't already in queue
          connect.push(this);     // add shape to queue
        }
      }
      $('#step-name').val(property.name);
      $('#step-url').val(property.url);
      $('#step-id').val(this.id);
      $('#properties a[href="#connector"]').tab('show');
      break;
    case "path":
      $('#properties a[href="#connection"]').tab('show');
      break;
  }
}

var setData = function(shape) {
  var d = new DataModel();
  shape.data("props", d);
}

/**
 * Add a new element from Toolbar to Workspace
 * @method addToDiagram
 * @param {Object} shape Raphael Element object
 * */
var addToDiagram = function (shape) {
  var color = Raphael.getColor(); // Get next color in spectrum
  if(shape.type === "path") {
    if(connect.length == 2) {     // Create a connection between adapters
      var newConnection = paper.connection(connect[0], connect[1], "#000");
      newConnection.line.attr({
          "title": id = connect[0].id + 'to' + connect[1].id,
          "stroke-width": 3});
      newConnection.line.click(modify);
      connections.push(newConnection);
      workspace.push(newConnection.line);
      connect = [];               // Empty queue
    } else {
      return;                     // 2 shapes in queue are required
    }                             // to make a connection
  } else {
    var newShape = shape.clone();   // Hello Dolly!
    setData(newShape);              // Give Dolly a Soul
    newShape.attr({fill: color,
                  stroke: color,
                  "fill-opacity": 0,
                  "stroke-width": 3,
                  "width": 50,
                  "height": 30,
                  "x": 50 + Math.floor(Math.random()*160),
                  "y": 70 + Math.floor(Math.random()*160)});
    newShape.drag(move, dragger, up).click(modify);
    workspace.push(newShape);   // Append new shape to workspace
    if(workspace.length == 1) {   // If workspace empty we start from scratch
      connect.push(startShape);
      connect.push(newShape);
      var firstConnection = paper.connection(connect[0], connect[1], "#000");
      firstConnection.line.attr({
          "title": id = connect[0].id + 'to' + connect[1].id,
          "stroke-width": 3});
      firstConnection.line.click(modify);
      connections.push(firstConnection); // connect to the begining
      workspace.push(firstConnection.line);
    }
  }
}

var util = new Util();
// Global settings
var connections = [];               // Connections between shapes
var connect = [];                   // Temporary queue for connections
var workspace_meta = new workspace_metadata();

var allInputs = $(":input");                // Properties list
var toolbarX = 4,
  toolbarY = 4,
  toolbarWidth = 40,
  toolBarHeigth = 300,
  paperWidth = 768,
  paperHeigth = 500;
var paper = Raphael("work-canvas",
                    paperWidth, paperHeigth);  // Creates canvas 320×200@10,50
var workspace = paper.set();            // Create a default workspace
var work_guid = util.guid();            // Generate Workspace GUID
var toolbar = paper.rect(toolbarX, toolbarY,
                         toolbarWidth,
                         toolBarHeigth); // Placeholder for the tools
// We'll create shapes based it
var basicShape = paper
  .rect(toolbarX + 5, toolbarY + 5, 30, 20)
  .attr({"fill": "#CCC",
        "fill-opacity": 0,
        "stroke-width": 3,
        cursor: "move"});
// Same as basicShape its a basic connector, derive other from it
var connectShape = paper
  .path("M9 35L40 60")
  .attr({"stroke-width": 3,
        cursor: "move"});
// TODO Moar shapes

// Start and End shapes, there should be one of each by default
// in every workspace
var startShape = paper
  .circle(toolbarX + 80, toolbarY + 75, 15)
  .attr({"fill": "#7AC200",
        "fill-opacity": 100,
        "stroke-width": 3,
        "stroke": "#298500",
        cursor: "move"})
  .data("props", {"type":"start"});

var endShape = paper
  .circle(paperWidth - 80, paperHeigth - 75, 15)
  .attr({"fill": "#D21C00",
        "fill-opacity": 100,
        "stroke-width": 3,
        "stroke": "#990000",
        cursor: "move"})
  .data("props", {"type":"end"});

/**
 * Remove shape from workspace
 * @method remove
 * @param {Integer} id of the Raphael element
 * */
var remove = function(id) {
  // TODO Fix this, should be donw within w.remove
  var shape = paper.getById(id);
  workspace.exclude(shape);
  shape.remove();
}

/**
 * Clone a shape by id
 * @method cloneBlk
 * @param {Integer} id of the Raphael element
 * */
var clone = function(id) {
  addToDiagram(paper.getById(id));
}

/**
 * Update the shape properties data 'props' with values from
 * the properties panel
 * @method updateShape
 * @param {Integer} id of Raphael element
 * */
var update = function(id) {
  // TODO Fix it, values get borked in the panel
  var s = paper.getById(id);
  s.data("props").id = id;
  s.data("props").type = $('#step-type').val();
  s.data("props").name = $('#step-name').val();
  s.data("props").url = $('#step-url').val();
  s.attr({'title': s.data("props").name,
          'text':s.data("props").name});
}

/**
 * Save workspace to YAML in the server
 * @method save
 * */
var save = function() {
  //TODO
  var payload = [];
  workspace.forEach(function(s) {
    payload.push(s.data("props"));
  });
  $.post("/api/", {"__anti-forgery-token": $('#__anti-forgery-token').val(),
         "workspace":{"data": JSON.stringify(payload),
                    "meta": JSON.stringify(workspace_meta)}});
}

/**
 * Update workspace properties
 * @method
 */
var updateWorkspace = function() {
  workspace_meta.type = $('#work-type').val();
  workspace_meta.guid= $('#work-guid').val()
  workspace_meta.name = $('#work-name').val()
  workspace_meta.comments = $('#work-comments').val()

}

// Initialize some properties for a new workspace
// TODO Check if the values aren't overwriten when refreshing webpage
$('#work-guid').val(work_guid);
$('#work-guid-label').html("Id: " + work_guid);
// Attach listeners to Toolbar elements
basicShape.drag(move, dragger, release);
connectShape.click(function(){addToDiagram(this)});
startShape.drag(move, dragger, function(){});
endShape.drag(move, dragger, function(){});
// Bind listeners to Properties controls
// TODO Do this in one iteration of all
// Workspace
//
$('#work-type-lst li a').on("click change", function(){
  var type = $(this).text().toUpperCase().replace(' ','').replace('.','');
  $('#btn-work-type').html(type + '');
  $('#work-type').val(type);
});
$('#workspace :input').on("click change keyup", function() {
  updateWorkspace();
});
//
// Adapters
//
$('#step-type-lst li a').on("click change", function(){
  var type = $(this).text().toUpperCase().replace(' ','');
  $('#btn-step-type').html(type + '');
  $('#step-type').val(type);
  update($('#step-id').val());
});
//
// Connectors
//
$('#connector :input').on("click change keyup", function(){
  update($('#step-id').val());
});
//
// Form controls
//
// TODO Remove from workspace is badly broken
$('#remove-btn').click(function(){remove($('#step-id').val())});
$('#clone-btn').click(function(){clone($('#step-id').val())});
$('#save-btn').click(function(){save()});

<|endoftext|>


<commit_before>'use strict';

angular
    .module('cometApp')
    .config(config);

    config.$inject = ['$stateProvider', '$urlRouterProvider'];

    function config ($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '/src/home/home.html',
                controller: 'HomeController',
                controllerAs: 'vm'
            })
            .state('user-create', {
                url: '/user/create',
                templateUrl: '/src/user/user-create.html',
                controller: 'UserController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-login', {
                url: '/account/login',
                templateUrl: '/src/account/account-login.html',
                controller: 'AccountLoginController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-confirm', {
                url: '/account/confirm?token',
                templateUrl: '/src/account/account-confirm.html',
                controller: 'AccountConfirmController',
                controllerAs: 'vm'
            })
            .state('account-forgot', {
                url: '/account/forgot',
                templateUrl: '/src/account/account-forgot.html',
                controller: 'AccountRecoverController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-recover', {
                url: '/account/recover?token&email',
                templateUrl: '/src/account/account-recover.html',
                controller: 'AccountRecoverController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('dashboard', {
                url: '/dashboard',
                templateUrl: '/src/dashboard/dashboard-index.html',
                controller: 'DashboardController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (!authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('dashboard.profile', {
                url: '/profile',
                templateUrl: '/src/user/user-profile.html',
                controller: 'UserProfileController',
                controllerAs: 'vm'
            });

        $urlRouterProvider.otherwise('/');
    }
<commit_msg>fix ruta inexistente a 'dashboard'<commit_after>'use strict';

angular
    .module('cometApp')
    .config(config);

    config.$inject = ['$stateProvider', '$urlRouterProvider'];

    function config ($stateProvider, $urlRouterProvider) {

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '/src/home/home.html',
                controller: 'HomeController',
                controllerAs: 'vm'
            })
            .state('user-create', {
                url: '/user/create',
                templateUrl: '/src/user/user-create.html',
                controller: 'UserController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-login', {
                url: '/account/login',
                templateUrl: '/src/account/account-login.html',
                controller: 'AccountLoginController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-confirm', {
                url: '/account/confirm?token',
                templateUrl: '/src/account/account-confirm.html',
                controller: 'AccountConfirmController',
                controllerAs: 'vm'
            })
            .state('account-forgot', {
                url: '/account/forgot',
                templateUrl: '/src/account/account-forgot.html',
                controller: 'AccountRecoverController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('account-recover', {
                url: '/account/recover?token&email',
                templateUrl: '/src/account/account-recover.html',
                controller: 'AccountRecoverController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('dashboard-index', {
                url: '/dashboard',
                templateUrl: '/src/dashboard/dashboard-index.html',
                controller: 'DashboardController',
                controllerAs: 'vm',
                onEnter: ['$state', 'authService', function ($state, authService) {
                    if (!authService.isLoggedIn()) {
                        $state.go('home');
                    }
                }]
            })
            .state('dashboard.profile', {
                url: '/profile',
                templateUrl: '/src/user/user-profile.html',
                controller: 'UserProfileController',
                controllerAs: 'vm'
            });

        $urlRouterProvider.otherwise('/');
    }
<|endoftext|>


<commit_before>/*
 * === ABOUT US ===
 * @name:		Orbitron
 * @website:	http://www.team-orbitron.com
 * === ABOUT PROJECT ===
 * @author:		Orbitron
 * @project:	Achievements
 * @version:	v1.0.6
 * @website:	https://raw.githubusercontent.com/OfficialOrbitron/ModPE/master/Scripts/Achievements.js
 *
 * Testet with:
 * MCPE: v0.9.5
 * BlockLauncher: v1.7.9
 *
 */

// Project info
var project		= "Achievements";
var sname		= "ACH";
var version		= "1.0.6";
var author		= "Orbitron";

// Values
var achievement	= [
	{
		"id": 1,
		"reached": false,
		"message": "Monster Hunter!"
	},
	{
		"id": 2,
		"reached": false,
		"message": "Cow Tipper"
	},
	{
		"id": 3,
		"reached": false,
		"message": "Sniper Duel"
	},
	{
		"id": 4,
		"reached": false,
		"message": "Getting Wood"
	},
	{
		"id": 5,
		"reached": false,
		"message": "DIAMONDS!"
	},
	{
		"id": 6,
		"reached": false,
		"message": "Benchmarking"
	},
	{
		"id": 7,
		"reached": false,
		"message": "Hot Topic"
	},
	{
		"id": 8,
		"reached": false,
		"message": "Time to Mine!"
	},
	{
		"id": 9,
		"reached": false,
		"message": "Acquire Hardware"
	},
	{
		"id": 10,
		"reached": false,
		"message": "Time to Farm!"
	},
	{
		"id": 11,
		"reached": false,
		"message": "Bake Bread"
	},
	{
		"id": 12,
		"reached": false,
		"message": "The Lie"
	},
	{
		"id": 13,
		"reached": false,
		"message": "Getting an Upgrade"
	},
	{
		"id": 14,
		"reached": false,
		"message": "Time to Strike!"
	},
	{
		"id": 15,
		"reached": false,
		"message": "Librarian"
	}
];

// Main functions
function useItem(x, y, z, itemId, blockId, side)
{
	if(achievement[5]["reached"] === true && itemId == 58)
	{
		addonShowAchievement(5);
	}
	if(achievement[6]["reached"] === true && itemId == 61)
	{
		addonShowAchievement(6);
	}
	if(achievement[7]["reached"] === true && itemId == 270)
	{
		addonShowAchievement(7);
	}
	if(achievement[8]["reached"] === true && itemId == 265)
	{
		addonShowAchievement(8);
	}
	if(achievement[9]["reached"] === true && itemId == 290)
	{
		addonShowAchievement(9);
	}
	if(achievement[10]["reached"] === true && itemId == 297)
	{
		addonShowAchievement(10);
	}
	if(achievement[11]["reached"] === true && itemId == 354)
	{
		addonShowAchievement(11);
	}
	if(achievement[12]["reached"] === true)
	{
		if (itemId == 274 || itemId == 257 || itemId == 285 || itemId == 278)
		{
			addonShowAchievement(12);
		}
	}
	if(achievement[13]["reached"] === true && itemId == 268)
	{
		addonShowAchievement(13);
	}
	if(achievement[14]["reached"] === true && itemId == 47)
	{
		addonShowAchievement(14);
	}
}
function attackHook(attacker, victim)
{
	if(achievement[0]["reached"] === true)
	{
		if(Entity.getEntityTypeId(victim) == 32 || Entity.getEntityTypeId(victim) == 33 || Entity.getEntityTypeId(victim) == 34 || Entity.getEntityTypeId(victim) == 35 || Entity.getEntityTypeId(victim) == 36)
		{
			addonShowAchievement(0);
		}
	}
	if(achievement[1]["reached"] === true && Entity.getEntityTypeId(victim) == 11)
	{
		addonShowAchievement(1);
	}
	if(achievement[2]["reached"] === true && Entity.getEntityTypeId(victim) == 34 && getCarriedItem() == 261)
	{
		addonShowAchievement(2);
	}
}
function procCmd(command)
{
	var cmd = command.toLowerCase().split(" ");
	switch(cmd[0])
	{
		case "ach":
		case "achievements":

			switch(cmd[1])
			{
				case "save":

					for(var i = 0; i < achievement.length; i++)
					{
						ModPE.saveData("a" + i, achievement[i]["reached"]);
					}
					addonColourMessage("Saved achievements!");
					break;

				case "load":

					for(var i = 0; i < achievement.length; i++)
					{
						achievement[i]["reached"] = ModPE.readData("a" + i);
					}
					addonColourMessage("Loaded achievements!");
					break;

				case "reset":

					for(var i = 0; i < achievement.length; i++)
					{
						achievement[i]["reached"] = false;
						ModPE.saveData("a" + i, achievement[i]);
					}
					addonColourMessage("Resetted achievements!");
					break;

				default:

					addonErrorMessage("Command " + p[1] + " does not exist!");
					break;
			}

		default:

			break;
	}
}
function destroyBlock(x, y, z, side)
{
	if (achievement[3]["reached"] === true && getTile(x, y, z) == 17)
	{
		addonShowAchievement(3);
	}
	if (achievement[4]["reached"] === true && getTile(x, y, z) == 56 && getCarriedItem() == 257)
	{
		addonShowAchievement(4);
	}
}
function newLevel()
{
	for(var i = 0; i < achievement.length; i++)
	{
		achievement[i]["reached"] = ModPE.readData("a" + i);
	}
	clientMessage(ChatColor.GRAY + "[INFO] " + ChatColor.WHITE + project + " loaded");
}
function leaveGame()
{
	for(var i = 0; i < achievement.length; i++)
	{
		ModPE.saveData("a" + i, achievement[i]["reached"]);
	}
}

// Additional functions
function addonColourMessage(string)
{
	clientMessage(ChatColor.GRAY + "["+ ChatColor.RED + sname + ChatColor.GRAY +"] " + ChatColor.WHITE + string);
}
function addonErrorMessage(string)
{
	clientMessage(ChatColor.GRAY + "["+ ChatColor.RED + sname + ChatColor.GRAY +"] " + ChatColor.RED + string);
}
function addonShowAchievement(ID)
{
	achievement[ID] = true;
	clientMessage("Achievement get! " + achievement[ID]["message"]);
}<commit_msg>Fixed reaching of achievements<commit_after>/*
 * === ABOUT US ===
 * @name:		Orbitron
 * @website:	http://www.team-orbitron.com
 * === ABOUT PROJECT ===
 * @author:		Orbitron
 * @project:	Achievements
 * @version:	v1.0.6
 * @website:	https://raw.githubusercontent.com/OfficialOrbitron/ModPE/master/Scripts/Achievements.js
 *
 * Testet with:
 * MCPE: v0.9.5
 * BlockLauncher: v1.7.9
 *
 */

// Project info
var project		= "Achievements";
var sname		= "ACH";
var version		= "1.0.6";
var author		= "Orbitron";

// Values
var achievement	= [
	{
		"id": 1,
		"reached": false,
		"message": "Monster Hunter!"
	},
	{
		"id": 2,
		"reached": false,
		"message": "Cow Tipper"
	},
	{
		"id": 3,
		"reached": false,
		"message": "Sniper Duel"
	},
	{
		"id": 4,
		"reached": false,
		"message": "Getting Wood"
	},
	{
		"id": 5,
		"reached": false,
		"message": "DIAMONDS!"
	},
	{
		"id": 6,
		"reached": false,
		"message": "Benchmarking"
	},
	{
		"id": 7,
		"reached": false,
		"message": "Hot Topic"
	},
	{
		"id": 8,
		"reached": false,
		"message": "Time to Mine!"
	},
	{
		"id": 9,
		"reached": false,
		"message": "Acquire Hardware"
	},
	{
		"id": 10,
		"reached": false,
		"message": "Time to Farm!"
	},
	{
		"id": 11,
		"reached": false,
		"message": "Bake Bread"
	},
	{
		"id": 12,
		"reached": false,
		"message": "The Lie"
	},
	{
		"id": 13,
		"reached": false,
		"message": "Getting an Upgrade"
	},
	{
		"id": 14,
		"reached": false,
		"message": "Time to Strike!"
	},
	{
		"id": 15,
		"reached": false,
		"message": "Librarian"
	}
];

// Main functions
function useItem(x, y, z, itemId, blockId, side)
{
	if(achievement[5]["reached"] === true && itemId == 58)
	{
		addonShowAchievement(5);
	}
	if(achievement[6]["reached"] === true && itemId == 61)
	{
		addonShowAchievement(6);
	}
	if(achievement[7]["reached"] === true && itemId == 270)
	{
		addonShowAchievement(7);
	}
	if(achievement[8]["reached"] === true && itemId == 265)
	{
		addonShowAchievement(8);
	}
	if(achievement[9]["reached"] === true && itemId == 290)
	{
		addonShowAchievement(9);
	}
	if(achievement[10]["reached"] === true && itemId == 297)
	{
		addonShowAchievement(10);
	}
	if(achievement[11]["reached"] === true && itemId == 354)
	{
		addonShowAchievement(11);
	}
	if(achievement[12]["reached"] === true)
	{
		if (itemId == 274 || itemId == 257 || itemId == 285 || itemId == 278)
		{
			addonShowAchievement(12);
		}
	}
	if(achievement[13]["reached"] === true && itemId == 268)
	{
		addonShowAchievement(13);
	}
	if(achievement[14]["reached"] === true && itemId == 47)
	{
		addonShowAchievement(14);
	}
}
function attackHook(attacker, victim)
{
	if(achievement[0]["reached"] === true)
	{
		if(Entity.getEntityTypeId(victim) == 32 || Entity.getEntityTypeId(victim) == 33 || Entity.getEntityTypeId(victim) == 34 || Entity.getEntityTypeId(victim) == 35 || Entity.getEntityTypeId(victim) == 36)
		{
			addonShowAchievement(0);
		}
	}
	if(achievement[1]["reached"] === true && Entity.getEntityTypeId(victim) == 11)
	{
		addonShowAchievement(1);
	}
	if(achievement[2]["reached"] === true && Entity.getEntityTypeId(victim) == 34 && getCarriedItem() == 261)
	{
		addonShowAchievement(2);
	}
}
function procCmd(command)
{
	var cmd = command.toLowerCase().split(" ");
	switch(cmd[0])
	{
		case "ach":
		case "achievements":

			switch(cmd[1])
			{
				case "save":

					for(var i = 0; i < achievement.length; i++)
					{
						ModPE.saveData("a" + i, achievement[i]["reached"]);
					}
					addonColourMessage("Saved achievements!");
					break;

				case "load":

					for(var i = 0; i < achievement.length; i++)
					{
						achievement[i]["reached"] = ModPE.readData("a" + i);
					}
					addonColourMessage("Loaded achievements!");
					break;

				case "reset":

					for(var i = 0; i < achievement.length; i++)
					{
						achievement[i]["reached"] = false;
						ModPE.saveData("a" + i, achievement[i]);
					}
					addonColourMessage("Resetted achievements!");
					break;

				default:

					addonErrorMessage("Command " + p[1] + " does not exist!");
					break;
			}

		default:

			break;
	}
}
function destroyBlock(x, y, z, side)
{
	if (achievement[3]["reached"] === true && getTile(x, y, z) == 17)
	{
		addonShowAchievement(3);
	}
	if (achievement[4]["reached"] === true && getTile(x, y, z) == 56 && getCarriedItem() == 257)
	{
		addonShowAchievement(4);
	}
}
function newLevel()
{
	for(var i = 0; i < achievement.length; i++)
	{
		achievement[i]["reached"] = ModPE.readData("a" + i);
	}
	clientMessage(ChatColor.GRAY + "[INFO] " + ChatColor.WHITE + project + " loaded");
}
function leaveGame()
{
	for(var i = 0; i < achievement.length; i++)
	{
		ModPE.saveData("a" + i, achievement[i]["reached"]);
	}
}

// Additional functions
function addonColourMessage(string)
{
	clientMessage(ChatColor.GRAY + "["+ ChatColor.RED + sname + ChatColor.GRAY +"] " + ChatColor.WHITE + string);
}
function addonErrorMessage(string)
{
	clientMessage(ChatColor.GRAY + "["+ ChatColor.RED + sname + ChatColor.GRAY +"] " + ChatColor.RED + string);
}
function addonShowAchievement(ID)
{
	achievement[ID]["reached"] = true;
	clientMessage("Achievement get! " + achievement[ID]["message"]);
}<|endoftext|>


<commit_before>/**
 * Don't break on browsers without console.log()
 */
try {
    console.assert(1);
} catch(e) {
    /* jshint -W020 */
    console = {
        log: function () {
            "use strict";
        },
        assert: function () {
            "use strict";
        }
    };
    /* jshint +W020 */
}
<commit_msg>Change the way existance of console is detected<commit_after>/**
 * Don't break on browsers without console.log()
 */
if (typeof console === "undefined") {
    /* jshint -W020 */
    console = {
        log: function () {
            "use strict";
        },
        assert: function () {
            "use strict";
        }
    };
    /* jshint +W020 */
}
<|endoftext|>


<commit_before>function leave_room(){
    socket.emit('left', {}, function() {
        socket.disconnect();
        // go back to the login page
        window.location.href = "/";
    });
}

function send_msg(msg){
    msg = msg.trim();
    if(msg != ''){
        $('#text').val('');
        msg = Aes.Ctr.encrypt(msg, Cookies.get('password'), 256)
        socket.emit('text', {'msg': msg});
    }
}

function filter_msg(msg){
    msg = msg.trim();
    msg = filter_code(msg);
    msg = filter_href(msg);
    return msg;
}

function filter_code(msg){
    if(msg.substring(0,5)=='/code'){
        msg = '
' + msg.substring(5) + '
';
    }
    return msg;
}

function filter_href(msg){
    geturl = new RegExp(
        "(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))",
        "g");
    if(msg.match(geturl) && msg.match(geturl).length){
        msg.match(geturl).forEach(function(_url){
            msg = msg.replace(_url, ''+_url+'')
            ext = _url.slice(-4)
            if(ext=='jpeg' || ext=='.jpg' || ext=='.gif' || ext=='.png'){
                msg = msg + '
';
            }
        });
    }
    return msg;
}

function spawnNotification(theBody,theIcon,theTitle) {
    if( ! window.onfocus ){
        var options = {
          body: theBody,
          icon: theIcon
        }
        var n = new Notification(theTitle,options);
        setTimeout(n.close.bind(n), 5000);
    }
}

function store_message(data){
    data_string = (JSON.stringify(data));
    storage_key = 'room_' + data.room_key;
    chat_room_data = JSON.parse(localStorage.getItem(storage_key));
    if(chat_room_data==null){
        chat_room_data = [];
    }
    chat_room_data.push(data_string);
    localStorage.setItem(storage_key, JSON.stringify(chat_room_data));
}

function build_local_data(room_key){
    storage_key = 'room_' + room_key;
    chat_room_data = JSON.parse(localStorage.getItem(storage_key));
    if(chat_room_data == null){
        empty_array = [];
        localStorage.setItem(storage_key, JSON.stringify(empty_array));
        return;
    }
    for(chat of chat_room_data){
        c = JSON.parse(chat);
        draw_msg(c);
    }
}

function draw_msg(msg_obj){
    unencrypted_msg = Aes.Ctr.decrypt(msg_obj.msg, Cookies.get('password'), 256);
    filtered_msg = filter_msg( unencrypted_msg );
    $(msg_obj.tpl).insertBefore('#chat li:last');
    new_msg_li = $('#chat li:nth-last-child(2)');
    new_msg_li.find('.msg_content').html(filtered_msg);
    new_msg_user = new_msg_li.attr('data-user');

    msg_pretty_time = pretty_time_now(msg_obj.sent)
    new_msg_li.find('.msg_date').text(msg_pretty_time);
    if(Cookies.get('user_name')==new_msg_user){
        new_msg_li.addClass('msg_me');
    }
    $('#chat').scrollTop($('#chat')[0].scrollHeight);
    if($('#chat li').length <= 1){
        return
    }

    // check if the last message was the same person and recent
    previous_message_li = $('#chat li:nth-last-child(3)');
    previous_message_type = previous_message_li.attr('data-type');
    append_to_last = false;
    if(
         previous_message_li.attr('data-user') == new_msg_user
        &&
        previous_message_type == 'msg')
        {
        new_msg_li.find('.user_image_container').find('img').hide();
        previous_message_time = new Date(previous_message_li.attr('data-date'));
        diff = Math.round(Math.abs((new Date() - previous_message_time) / 1000));
        if(diff < 120){
            append_to_last = true;
        }
    }

    if( previous_message_type == 'msg'){
        if(append_to_last == true){
            new_msg_li.find('h3').hide();
            new_msg_li.find('.msg_date').hide();
            new_msg_li.addClass('no_break_above');
            previous_message_li.addClass('no_break_below');
        }
    }
}

function pretty_time_now(msg_time){
    var now = new Date();
    diff = Math.round(Math.abs( now - msg_time) / 1000);

    msg_pretty_time = false;
    if(diff < 20){
        msg_pretty_time = 'seconds ago';
    }else if(diff < 60){
        msg_pretty_time = 'less then a minute ago'
    }else if(diff <= 5400){
        minutes = Math.round(diff / 60);
        if(minutes == 1){
            msg_pretty_time = '1 minute ago';
        } else {
            msg_pretty_time = minutes + ' mintues ago';
        }
    }else if(diff > 5401){
        hours = Math.round(diff / 3600)
        msg_pretty_time = 'about '+hours+' hours ago';
    } else {
        msg_pretty_time = 'just now';
    }
    return msg_pretty_time;
}

function settings_update(){
    $('.setting-update').click(function(){
        setting_name = $(this).attr('name');
        if(setting_name=='clear_local'){
            localStorage.clear();
        }
    });
}

function lock_console(){
    $('#settings_btn').fadeOut();
    $('#chat_window').fadeOut();
    $('#lock_status').removeClass('fa-unlock-alt').addClass('fa-lock');
    $('#repassword_container').fadeIn(1500);
    $("#repassword").focus();
    $( "#chat li" ).each(function(index) {
        if(! $(this).hasClass('typing')){
            $(this).remove();
        }
    });
    Cookies.set('password', '');
    Cookies.set('terminal', 'locked');
}

function unlock_console(password){
    Cookies.set('password', password);
    Cookies.set('terminal', 'open');
    build_local_data(Cookies.get('room_key'));
    $('#lock_status').removeClass('fa-lock').addClass('fa-unlock-alt');
    $('#repassword_container').fadeOut(1500);
    $('#settings_btn').fadeIn();
    $('#chat_window').fadeIn();
    $("#textbox").focus();
    $('#chat').scrollTop($('#chat')[0].scrollHeight);
}

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime >= 2) { // 120 seconds
        lock_console();
    }
}

var socket;
var idleTime = 0;

var CHATSEC = CHATSEC || (function(){

    return {
        init : function(Args) {
            _args = Args;

            $('#room_name').html(':: ' + Cookies.set('room_name'));
            $('title').html('Chatsec::  ' + Cookies.set('room_name'));

            // Notification.requestPermission().then(function(result) {
            //     console.log(result);
            // });

        },
        launch : function(){
            if(Cookies.get('password')==''){
                window.location = '/';
            }

            $(document).ready(function(){
                build_local_data(Cookies.get('room_key'));
                $('.typing').hide();
                $("#textbox").focus();

                // Manual/Idle Lockout
                $('#lock_btn').click(function(){
                    lock_console();
                });
                var idleInterval = setInterval(timerIncrement, 60000); // 60 seconds
                //Zero the idle timer on mouse movement.
                $(this).mousemove(function (e) {
                    idleTime = 0;
                });
                $(this).keypress(function (e) {
                    idleTime = 0;
                });
                $('.cs_login').keypress(function(e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        unlock_console($(this).val());
                        $(this).val('');
                        timeoutTime = 0;
                        // set_login_creds($(this));
                    }
                });

                // Sockets
                socket = io.connect(window.location.protocol + '//' + document.domain + ':' + location.port + '/chat');
                socket.on('connect', function() {
                    socket.emit('joined', {});
                });

                socket.on('status', function(data) {
                    $(data.tpl).insertBefore('#chat li:last');
                    $('#chat').scrollTop($('#chat')[0].scrollHeight);
                });

                // Reciving user currently typing
                socket.on('typing', function(data) {
                    if(Cookies.get('user_name') != data.user_name ){
                        $('.typing').find('.typing_avatar').attr(
                            'src',
                            '/static/imgs/avatars/black/' + data.avatar
                        );
                        $('.typing').find('h3').text(data.user_name);
                        $('.typing').show().delay(750).fadeOut();
                        $('#chat').scrollTop($('#chat')[0].scrollHeight);
                    }
                });

                // Recieving a message
                socket.on('message', function(data) {
                    draw_msg(data);

                    if(Cookies.get('user_name') != data.user_name ){
                        var audio = new Audio('/static/audio/new_msg.mp3');
                        audio.play();
                        // spawnNotification(
                        //     filtered_msg,
                        //     'http://www.google.com/',
                        //     'ChatSec - ' + data.user_name );
                    }
                    store_message(data);
                });

                // Sending a message
                $('#textbox').keypress(function(e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        message = $('#textbox').val();
                        send_msg(message);
                        $('#textbox').val('');
                    } else {
                        socket.emit('typing', {'msg': 'chatsec-user-typing'});
                    }
                });

                $('#send').click(function(e){
                    send_msg($('#textbox').val());
                });

                // @todo: make t his actually work or kill it
                $(window).on('beforeunload', function(){
                    socket.emit('left', {}, function() {
                        socket.disconnect();
                    });
                });

                // Timer Scripts
                window.setInterval(function(){
                    // Update msg time
                    $("#chat li").each(function( index ) {
                        var sent_time = new Date( $(this).attr('data-date') );
                        msg_pretty_time = pretty_time_now(sent_time)
                        if(msg_pretty_time){
                            $(this).find('.msg_date').text(msg_pretty_time);
                        }
                    });

                    // Highlight code blocks
                    $('pre').each(function(i, block) {
                        // hljs.highlightBlock(block);
                    });
                }, 1000);
            });
        }
    };
}());<commit_msg>Working on notifications, not really a fan so far..<commit_after>function leave_room(){
    socket.emit('left', {}, function() {
        socket.disconnect();
        // go back to the login page
        window.location.href = "/";
    });
}

function send_msg(msg){
    msg = msg.trim();
    if(msg != ''){
        $('#text').val('');
        msg = Aes.Ctr.encrypt(msg, Cookies.get('password'), 256)
        socket.emit('text', {'msg': msg});
    }
}

function filter_msg(msg){
    msg = msg.trim();
    msg = filter_code(msg);
    msg = filter_href(msg);
    return msg;
}

function filter_code(msg){
    if(msg.substring(0,5)=='/code'){
        msg = '
' + msg.substring(5) + '
';
    }
    return msg;
}

function filter_href(msg){
    geturl = new RegExp(
        "(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))",
        "g");
    if(msg.match(geturl) && msg.match(geturl).length){
        msg.match(geturl).forEach(function(_url){
            msg = msg.replace(_url, ''+_url+'')
            ext = _url.slice(-4)
            if(ext=='jpeg' || ext=='.jpg' || ext=='.gif' || ext=='.png'){
                msg = msg + '
';
            }
        });
    }
    return msg;
}

function spawn_notification(msg_obj) {
    if(window.Notification && Notification.permission !== "denied") {
        Notification.requestPermission(function(status) {  // status is "granted", if accepted by user
            if(Cookies.get('terminal')=='unlocked'){
                title = 'ChatSec - ' + msg_obj.user_name;
                msg = Aes.Ctr.decrypt(msg_obj.msg, Cookies.get('password'), 256);
            } else {
                title ='Chatsec';
                msg = 'New message recieved.';
            }
            var n = new Notification('Title', {
                body: msg,
                icon: 'static/imgs/avatars/black/' + msg_obj.avatar
            });
            setTimeout(n.close.bind(n), 5000);
        });
    }
}

function store_message(data){
    data_string = (JSON.stringify(data));
    storage_key = 'room_' + data.room_key;
    chat_room_data = JSON.parse(localStorage.getItem(storage_key));
    if(chat_room_data==null){
        chat_room_data = [];
    }
    chat_room_data.push(data_string);
    localStorage.setItem(storage_key, JSON.stringify(chat_room_data));
}

function build_local_data(room_key){
    storage_key = 'room_' + room_key;
    chat_room_data = JSON.parse(localStorage.getItem(storage_key));
    if(chat_room_data == null){
        empty_array = [];
        localStorage.setItem(storage_key, JSON.stringify(empty_array));
        return;
    }
    for(chat of chat_room_data){
        c = JSON.parse(chat);
        draw_msg(c);
    }
}

function draw_msg(msg_obj){
    unencrypted_msg = Aes.Ctr.decrypt(msg_obj.msg, Cookies.get('password'), 256);
    filtered_msg = filter_msg( unencrypted_msg );
    $(msg_obj.tpl).insertBefore('#chat li:last');
    new_msg_li = $('#chat li:nth-last-child(2)');
    new_msg_li.find('.msg_content').html(filtered_msg);
    new_msg_user = new_msg_li.attr('data-user');

    msg_pretty_time = pretty_time_now(msg_obj.sent)
    new_msg_li.find('.msg_date').text(msg_pretty_time);
    if(Cookies.get('user_name')==new_msg_user){
        new_msg_li.addClass('msg_me');
    }
    $('#chat').scrollTop($('#chat')[0].scrollHeight);
    if($('#chat li').length <= 1){
        return
    }

    // check if the last message was the same person and recent
    previous_message_li = $('#chat li:nth-last-child(3)');
    previous_message_type = previous_message_li.attr('data-type');
    append_to_last = false;
    if(
         previous_message_li.attr('data-user') == new_msg_user
        &&
        previous_message_type == 'msg')
        {
        new_msg_li.find('.user_image_container').find('img').hide();
        previous_message_time = new Date(previous_message_li.attr('data-date'));
        diff = Math.round(Math.abs((new Date() - previous_message_time) / 1000));
        if(diff < 120){
            append_to_last = true;
        }
    }

    if( previous_message_type == 'msg'){
        if(append_to_last == true){
            new_msg_li.find('h3').hide();
            new_msg_li.find('.msg_date').hide();
            new_msg_li.addClass('no_break_above');
            previous_message_li.addClass('no_break_below');
        }
    }
}

function pretty_time_now(msg_time){
    var now = new Date();
    diff = Math.round(Math.abs( now - msg_time) / 1000);

    msg_pretty_time = false;
    if(diff < 20){
        msg_pretty_time = 'seconds ago';
    }else if(diff < 60){
        msg_pretty_time = 'less then a minute ago'
    }else if(diff <= 5400){
        minutes = Math.round(diff / 60);
        if(minutes == 1){
            msg_pretty_time = '1 minute ago';
        } else {
            msg_pretty_time = minutes + ' mintues ago';
        }
    }else if(diff > 5401){
        hours = Math.round(diff / 3600)
        msg_pretty_time = 'about '+hours+' hours ago';
    } else {
        msg_pretty_time = 'just now';
    }
    return msg_pretty_time;
}

function settings_update(){
    $('.setting-update').click(function(){
        setting_name = $(this).attr('name');
        if(setting_name=='clear_local'){
            localStorage.clear();
        }
    });
}

function lock_console(){
    $('#settings_btn').fadeOut();
    $('#chat_window').fadeOut();
    $('#lock_status').removeClass('fa-unlock-alt').addClass('fa-lock');
    $('#repassword_container').fadeIn(1500);
    $("#repassword").focus();
    $( "#chat li" ).each(function(index) {
        if(! $(this).hasClass('typing')){
            $(this).remove();
        }
    });
    Cookies.set('password', '');
    Cookies.set('terminal', 'locked');
}

function unlock_console(password){
    Cookies.set('password', password);
    Cookies.set('terminal', 'open');
    build_local_data(Cookies.get('room_key'));
    $('#lock_status').removeClass('fa-lock').addClass('fa-unlock-alt');
    $('#repassword_container').fadeOut(1500);
    $('#settings_btn').fadeIn();
    $('#chat_window').fadeIn();
    $("#textbox").focus();
    $('#chat').scrollTop($('#chat')[0].scrollHeight);
}

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime >= 2) { // 120 seconds
        lock_console();
    }
}

var socket;
var idleTime = 0;

var CHATSEC = CHATSEC || (function(){

    return {
        init : function(Args) {
            _args = Args;

            $('#room_name').html(':: ' + Cookies.set('room_name'));
            $('title').html('Chatsec::  ' + Cookies.set('room_name'));

            window.Notification.requestPermission().then(function(result) {
                Cookies.set('notifications', true);
                console.log(result);
            });

        },
        launch : function(){
            if(Cookies.get('password')==''){
                window.location = '/';
            }

            $(document).ready(function(){
                build_local_data(Cookies.get('room_key'));
                $('.typing').hide();
                $("#textbox").focus();

                // Manual/Idle Lockout
                $('#lock_btn').click(function(){
                    lock_console();
                });
                var idleInterval = setInterval(timerIncrement, 60000); // 60 seconds
                //Zero the idle timer on mouse movement.
                $(this).mousemove(function (e) {
                    idleTime = 0;
                });
                $(this).keypress(function (e) {
                    idleTime = 0;
                });
                $('.cs_login').keypress(function(e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        unlock_console($(this).val());
                        $(this).val('');
                        timeoutTime = 0;
                        // set_login_creds($(this));
                    }
                });

                // Sockets
                socket = io.connect(window.location.protocol + '//' + document.domain + ':' + location.port + '/chat');
                socket.on('connect', function() {
                    socket.emit('joined', {});
                });

                socket.on('status', function(data) {
                    $(data.tpl).insertBefore('#chat li:last');
                    $('#chat').scrollTop($('#chat')[0].scrollHeight);
                });

                // Reciving user currently typing
                socket.on('typing', function(data) {
                    if(Cookies.get('user_name') != data.user_name ){
                        $('.typing').find('.typing_avatar').attr(
                            'src',
                            '/static/imgs/avatars/black/' + data.avatar
                        );
                        $('.typing').find('h3').text(data.user_name);
                        $('.typing').show().delay(750).fadeOut();
                        $('#chat').scrollTop($('#chat')[0].scrollHeight);
                    }
                });

                // Recieving a message
                socket.on('message', function(data) {
                    draw_msg(data);

                    if(Cookies.get('user_name') != data.user_name ){
                        var audio = new Audio('/static/audio/new_msg.mp3');
                        audio.play();
                        spawn_notification(data);
                    }
                    store_message(data);
                });

                // Sending a message
                $('#textbox').keypress(function(e) {
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        message = $('#textbox').val();
                        send_msg(message);
                        $('#textbox').val('');
                    } else {
                        socket.emit('typing', {'msg': 'chatsec-user-typing'});
                    }
                });

                $('#send').click(function(e){
                    send_msg($('#textbox').val());
                });

                // @todo: make t his actually work or kill it
                $(window).on('beforeunload', function(){
                    socket.emit('left', {}, function() {
                        socket.disconnect();
                    });
                });

                // Timer Scripts
                window.setInterval(function(){
                    // Update msg time
                    $("#chat li").each(function( index ) {
                        var sent_time = new Date( $(this).attr('data-date') );
                        msg_pretty_time = pretty_time_now(sent_time)
                        if(msg_pretty_time){
                            $(this).find('.msg_date').text(msg_pretty_time);
                        }
                    });

                    // Highlight code blocks
                    $('pre').each(function(i, block) {
                        // hljs.highlightBlock(block);
                    });
                }, 1000);
            });
        }
    };
}());<|endoftext|>


<commit_before>import { expect } from "chai"
import moment from "moment"
import MergePositions from "../pages/mergePositions.page"

const EXAMPLE_POSITIONS = {
  validLeft: {
    search: "merge one",
    fullName: "Merge One",
    organization: "MoD",
    type: "PRINCIPAL",
    code: "MOD-M1-HQ-00001",
    status: "ACTIVE",
    person: "CIV BEMERGED, Myposwill",
    associatedPositions: [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor C" }
    ],
    previousPeople: [
      {
        name: "CIV BEMERGED, Myposwill",
        date: `${moment().format("DD MMMM YYYY")} -  `
      }
    ],
    location: "Unspecified",
    notes: ["Merge one position note"]
  },
  validRight: {
    search: "merge two",
    fullName: "Merge Two",
    organization: "MoD",
    type: "PRINCIPAL",
    code: "MOD-M2-HQ-00001",
    status: "ACTIVE",
    person: "Unspecified",
    associatedPositions: [
      { person: "Unfilled", position: "EF 1.1 Advisor C" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ],
    previousPeople: [],
    location: "Unspecified",
    posUuid: "e87f0f60-ad13-4c1c-96f7-672c595b81c7",
    notes: ["Merge two position note"]
  },
  occupiedRight: {
    search: "cost adder",
    fullName: "Cost Adder - MoD"
  }
}

describe("Merge positions page", () => {
  it("Should display fields values of the left position", () => {
    // Open merge positions page.
    MergePositions.open()
    MergePositions.title.waitForExist()
    MergePositions.title.waitForDisplayed()

    // Search and select a position from left position field.
    MergePositions.leftPositionField.setValue(
      EXAMPLE_POSITIONS.validLeft.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()
    // Check if the fields displayed properly after selecting a position from left side.
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "left",
      "Name"
    )
    expect(MergePositions.getColumnContent("left", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    expect(
      MergePositions.getColumnContent("left", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validLeft.organization)
    expect(MergePositions.getColumnContent("left", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.type
    )
    expect(MergePositions.getColumnContent("left", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.code
    )
    expect(MergePositions.getColumnContent("left", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.status
    )
    expect(MergePositions.getColumnContent("left", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.person
    )
    expect(MergePositions.getAssociatedPositions("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
  })

  it("Should not allow to select the same positions", () => {
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.validLeft.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()

    MergePositions.samePositionsToast.waitForDisplayed()
  })

  it("Should not allow to select two occupied positions", () => {
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.occupiedRight.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.occupiedRight.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()

    MergePositions.occupiedPositionsToast.waitForDisplayed()
  })

  it("Should display fields values of the right position", () => {
    // Search and select a position from right position field.
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.validRight.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()
    // Check if the fields displayed properly after selecting a position from left side.
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validRight.fullName,
      "right",
      "Name"
    )
    expect(MergePositions.getColumnContent("right", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    expect(
      MergePositions.getColumnContent("right", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validRight.organization)
    expect(MergePositions.getColumnContent("right", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.type
    )
    expect(MergePositions.getColumnContent("right", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.code
    )
    expect(MergePositions.getColumnContent("right", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.status
    )
    expect(MergePositions.getColumnContent("right", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.person
    )
    expect(MergePositions.getAssociatedPositions("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.previousPeople
    )
  })

  it("Should be able to select all fields from left position", () => {
    MergePositions.getUseAllButton("left").click()

    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    expect(
      MergePositions.getColumnContent("mid", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validLeft.organization)
    expect(MergePositions.getColumnContent("mid", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.type
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.code
    )
    expect(MergePositions.getColumnContent("mid", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.status
    )
    expect(MergePositions.getColumnContent("mid", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.person
    )
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
    expect(MergePositions.getColumnContent("mid", "Location").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.location
    )
  })

  it("Should be able to select all fields from right position", () => {
    MergePositions.getUseAllButton("right").click()

    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validRight.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    expect(
      MergePositions.getColumnContent("mid", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validRight.organization)
    expect(MergePositions.getColumnContent("mid", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.type
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.code
    )
    expect(MergePositions.getColumnContent("mid", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.status
    )
    expect(MergePositions.getColumnContent("mid", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.person
    )
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validRight.previousPeople
    )
    expect(MergePositions.getColumnContent("mid", "Location").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.location
    )
  })

  it("Sould be able to select from both left and right side.", () => {
    MergePositions.getSelectButton("left", "Name").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )

    MergePositions.getSelectButton("left", "Code").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.code,
      "mid",
      "Code"
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.equal(
      EXAMPLE_POSITIONS.validLeft.code
    )

    MergePositions.getSelectButton("left", "Associated Positions").click()
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )

    MergePositions.getSelectButton("left", "Previous People").click()
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
  })

  it("Should display correct values on the left column", () => {
    MergePositions.getUseAllButton("left").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    MergePositions.editAssociatedPositionsButton.click()
    MergePositions.editAssociatedPositionsModal.waitForDisplayed()
    expect(MergePositions.getAssociatedPositionsInModal("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
  })
  it("Should display correct values on the right column", () => {
    expect(MergePositions.getAssociatedPositionsInModal("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
  })
  it("Should display left column values on the middle column", () => {
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      MergePositions.getAssociatedPositionsInModal("left")
    )
  })
  it("Should be able to remove items from the middle column", () => {
    const index = 0
    const afterFirstRemove = [
      { person: "Unfilled", position: "EF 1.1 Advisor C" }
    ]
    const afterSecondRemove = []
    MergePositions.getAssociatedPositionActionButton(
      "mid",
      index
    ).waitForDisplayed()
    MergePositions.getAssociatedPositionActionButton(
      "mid",
      index
    ).scrollIntoView()
    MergePositions.getAssociatedPositionActionButton("mid", index).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterFirstRemove
    )
    MergePositions.getAssociatedPositionActionButton("mid", index).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterSecondRemove
    )
  })
  it("Should be able to select items from right and left and save", () => {
    const leftItemIndex = 0
    const rightItemIndex = 1
    const afterPicked = [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ]
    MergePositions.getAssociatedPositionActionButton(
      "left",
      leftItemIndex
    ).click()
    MergePositions.getAssociatedPositionActionButton(
      "right",
      rightItemIndex
    ).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterPicked
    )
    MergePositions.saveAssociatedPositionsButton.click()
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(afterPicked)
  })

  it("Should be able to merge both positions when winner is left position", () => {
    MergePositions.mergePositionsButton.click()
    MergePositions.waitForSuccessAlert()
  })

  it("Should merge positions when winner's associated positions are a combination from both positions", () => {
    const winnerApsAfterMerge = [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ]
    expect(MergePositions.winnerAssociatedPositions).to.eql(winnerApsAfterMerge)
  })

  it("Should merge notes of the both positions", () => {
    MergePositions.showNotesButton.click()
    // Wait for offcanvas to open
    browser.pause(100)
    expect(
      MergePositions.areNotesExist([
        ...EXAMPLE_POSITIONS.validLeft.notes,
        ...EXAMPLE_POSITIONS.validRight.notes
      ])
    ).to.eq(true)
  })

  it("Should be able to delete the loser position", () => {
    MergePositions.openPage(
      `/positions/${EXAMPLE_POSITIONS.validRight.posUuid}`
    )
    MergePositions.errorTitle.waitForExist()
    expect(MergePositions.errorTitle.getText()).to.equal(
      `Position #${EXAMPLE_POSITIONS.validRight.posUuid} not found.`
    )
  })
})
<commit_msg>NCI-Agency/anet#3525: Remove empty lines<commit_after>import { expect } from "chai"
import moment from "moment"
import MergePositions from "../pages/mergePositions.page"

const EXAMPLE_POSITIONS = {
  validLeft: {
    search: "merge one",
    fullName: "Merge One",
    organization: "MoD",
    type: "PRINCIPAL",
    code: "MOD-M1-HQ-00001",
    status: "ACTIVE",
    person: "CIV BEMERGED, Myposwill",
    associatedPositions: [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor C" }
    ],
    previousPeople: [
      {
        name: "CIV BEMERGED, Myposwill",
        date: `${moment().format("DD MMMM YYYY")} -  `
      }
    ],
    location: "Unspecified",
    notes: ["Merge one position note"]
  },
  validRight: {
    search: "merge two",
    fullName: "Merge Two",
    organization: "MoD",
    type: "PRINCIPAL",
    code: "MOD-M2-HQ-00001",
    status: "ACTIVE",
    person: "Unspecified",
    associatedPositions: [
      { person: "Unfilled", position: "EF 1.1 Advisor C" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ],
    previousPeople: [],
    location: "Unspecified",
    posUuid: "e87f0f60-ad13-4c1c-96f7-672c595b81c7",
    notes: ["Merge two position note"]
  },
  occupiedRight: {
    search: "cost adder",
    fullName: "Cost Adder - MoD"
  }
}

describe("Merge positions page", () => {
  it("Should display fields values of the left position", () => {
    // Open merge positions page.
    MergePositions.open()
    MergePositions.title.waitForExist()
    MergePositions.title.waitForDisplayed()

    // Search and select a position from left position field.
    MergePositions.leftPositionField.setValue(
      EXAMPLE_POSITIONS.validLeft.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()
    // Check if the fields displayed properly after selecting a position from left side.
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "left",
      "Name"
    )
    expect(MergePositions.getColumnContent("left", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    expect(
      MergePositions.getColumnContent("left", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validLeft.organization)
    expect(MergePositions.getColumnContent("left", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.type
    )
    expect(MergePositions.getColumnContent("left", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.code
    )
    expect(MergePositions.getColumnContent("left", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.status
    )
    expect(MergePositions.getColumnContent("left", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.person
    )
    expect(MergePositions.getAssociatedPositions("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
  })
  it("Should not allow to select the same positions", () => {
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.validLeft.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()

    MergePositions.samePositionsToast.waitForDisplayed()
  })
  it("Should not allow to select two occupied positions", () => {
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.occupiedRight.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.occupiedRight.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()

    MergePositions.occupiedPositionsToast.waitForDisplayed()
  })
  it("Should display fields values of the right position", () => {
    // Search and select a position from right position field.
    MergePositions.rightPositionField.setValue(
      EXAMPLE_POSITIONS.validRight.search
    )
    MergePositions.waitForAdvancedSelectLoading(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    MergePositions.firstItemFromAdvancedSelect.click()
    // Check if the fields displayed properly after selecting a position from left side.
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validRight.fullName,
      "right",
      "Name"
    )
    expect(MergePositions.getColumnContent("right", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    expect(
      MergePositions.getColumnContent("right", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validRight.organization)
    expect(MergePositions.getColumnContent("right", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.type
    )
    expect(MergePositions.getColumnContent("right", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.code
    )
    expect(MergePositions.getColumnContent("right", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.status
    )
    expect(MergePositions.getColumnContent("right", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.person
    )
    expect(MergePositions.getAssociatedPositions("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.previousPeople
    )
  })
  it("Should be able to select all fields from left position", () => {
    MergePositions.getUseAllButton("left").click()

    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )
    expect(
      MergePositions.getColumnContent("mid", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validLeft.organization)
    expect(MergePositions.getColumnContent("mid", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.type
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.code
    )
    expect(MergePositions.getColumnContent("mid", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.status
    )
    expect(MergePositions.getColumnContent("mid", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.person
    )
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
    expect(MergePositions.getColumnContent("mid", "Location").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.location
    )
  })
  it("Should be able to select all fields from right position", () => {
    MergePositions.getUseAllButton("right").click()

    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validRight.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.fullName
    )
    expect(
      MergePositions.getColumnContent("mid", "Organization").getText()
    ).to.eq(EXAMPLE_POSITIONS.validRight.organization)
    expect(MergePositions.getColumnContent("mid", "Type").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.type
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.code
    )
    expect(MergePositions.getColumnContent("mid", "Status").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.status
    )
    expect(MergePositions.getColumnContent("mid", "Person").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.person
    )
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validRight.previousPeople
    )
    expect(MergePositions.getColumnContent("mid", "Location").getText()).to.eq(
      EXAMPLE_POSITIONS.validRight.location
    )
  })
  it("Sould be able to select from both left and right side.", () => {
    MergePositions.getSelectButton("left", "Name").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    expect(MergePositions.getColumnContent("mid", "Name").getText()).to.eq(
      EXAMPLE_POSITIONS.validLeft.fullName
    )

    MergePositions.getSelectButton("left", "Code").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.code,
      "mid",
      "Code"
    )
    expect(MergePositions.getColumnContent("mid", "Code").getText()).to.equal(
      EXAMPLE_POSITIONS.validLeft.code
    )

    MergePositions.getSelectButton("left", "Associated Positions").click()
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )

    MergePositions.getSelectButton("left", "Previous People").click()
    expect(MergePositions.getPreviousPeople("mid")).to.eql(
      EXAMPLE_POSITIONS.validLeft.previousPeople
    )
  })
  it("Should display correct values on the left column", () => {
    MergePositions.getUseAllButton("left").click()
    MergePositions.waitForColumnToChange(
      EXAMPLE_POSITIONS.validLeft.fullName,
      "mid",
      "Name"
    )
    MergePositions.editAssociatedPositionsButton.click()
    MergePositions.editAssociatedPositionsModal.waitForDisplayed()
    expect(MergePositions.getAssociatedPositionsInModal("left")).to.eql(
      EXAMPLE_POSITIONS.validLeft.associatedPositions
    )
  })
  it("Should display correct values on the right column", () => {
    expect(MergePositions.getAssociatedPositionsInModal("right")).to.eql(
      EXAMPLE_POSITIONS.validRight.associatedPositions
    )
  })
  it("Should display left column values on the middle column", () => {
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      MergePositions.getAssociatedPositionsInModal("left")
    )
  })
  it("Should be able to remove items from the middle column", () => {
    const index = 0
    const afterFirstRemove = [
      { person: "Unfilled", position: "EF 1.1 Advisor C" }
    ]
    const afterSecondRemove = []
    MergePositions.getAssociatedPositionActionButton(
      "mid",
      index
    ).waitForDisplayed()
    MergePositions.getAssociatedPositionActionButton(
      "mid",
      index
    ).scrollIntoView()
    MergePositions.getAssociatedPositionActionButton("mid", index).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterFirstRemove
    )
    MergePositions.getAssociatedPositionActionButton("mid", index).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterSecondRemove
    )
  })
  it("Should be able to select items from right and left and save", () => {
    const leftItemIndex = 0
    const rightItemIndex = 1
    const afterPicked = [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ]
    MergePositions.getAssociatedPositionActionButton(
      "left",
      leftItemIndex
    ).click()
    MergePositions.getAssociatedPositionActionButton(
      "right",
      rightItemIndex
    ).click()
    expect(MergePositions.getAssociatedPositionsInModal("mid")).to.eql(
      afterPicked
    )
    MergePositions.saveAssociatedPositionsButton.click()
    expect(MergePositions.getAssociatedPositions("mid")).to.eql(afterPicked)
  })
  it("Should be able to merge both positions when winner is left position", () => {
    MergePositions.mergePositionsButton.click()
    MergePositions.waitForSuccessAlert()
  })
  it("Should merge positions when winner's associated positions are a combination from both positions", () => {
    const winnerApsAfterMerge = [
      { person: "Unfilled", position: "EF 1.1 Advisor B" },
      { person: "Unfilled", position: "EF 1.1 Advisor D" }
    ]
    expect(MergePositions.winnerAssociatedPositions).to.eql(winnerApsAfterMerge)
  })
  it("Should merge notes of the both positions", () => {
    MergePositions.showNotesButton.click()
    // Wait for offcanvas to open
    browser.pause(100)
    expect(
      MergePositions.areNotesExist([
        ...EXAMPLE_POSITIONS.validLeft.notes,
        ...EXAMPLE_POSITIONS.validRight.notes
      ])
    ).to.eq(true)
  })
  it("Should be able to delete the loser position", () => {
    MergePositions.openPage(
      `/positions/${EXAMPLE_POSITIONS.validRight.posUuid}`
    )
    MergePositions.errorTitle.waitForExist()
    expect(MergePositions.errorTitle.getText()).to.equal(
      `Position #${EXAMPLE_POSITIONS.validRight.posUuid} not found.`
    )
  })
})
<|endoftext|>


<commit_before>// JavaScript Olympics

// I paired with Marie-France Han on this challenge.

// This challenge took me [#] hours.

// Release 0 - Warm Up (File/Repo Prep)

// Release 1 - Bulk Up

var sarahHughes = { name: "Sarah Hughes", event: "Ladies' Singles" };
var michelleKwan = { name: "Michelle Kwan", event: "Ladies' Singles" };
var yevgeniPlushenko = { name: "Yevgeni Plushenko", event: "Men's Singles" };
var paulWylie = { name: "Paul Wylie", event: "Men's Singles" };

var athletes = new Array(
  sarahHughes,
  michelleKwan,
  yevgeniPlushenko,
  paulWylie
);

function win(athletes) {
  for( var i = 0; i < athletes.length; i++) {
    athletes[i].win = "won";
    console.log(athletes[i].name + " " + athletes[i].win + " the " + athletes[i].event + "!");
  }
}

/*
console.log(athletes);
console.log("================================================")
win(athletes);
console.log("================================================")
console.log(athletes);
*/

// Jumble your words

function reverseStr(string) {
  var array = string.split("");
  return array = array.reverse().join("");
}

/* Driver code
var str = "Banana";
console.log(reverseStr(str));

var jumbleStr = "!sdrow ruoy elbmuJ"
console.log(reverseStr(jumbleStr));
*/

// 2,4,6,8

function appreciate(array) {
  var output = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i]% 2 === 0) {
      output.push(array[i]);
    }
  }
  return output;
}

/* Driver code:
console.log(appreciate([4,7,8,9,3,2.13,46,54]));
*/

// "We built this city"

var Athlete = function(name, age, sport, quote) {
  this.name = name;
  this.age = age;
  this.sport = sport;
  this.quote = quote;
}

// Driver Code
var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!");
console.log(michaelPhelps.constructor === Athlete);
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote);

var alexanderPopov = new Athlete("Alexander Popov", 30, "swimming", "I'm the torpedo!");
console.log(alexanderPopov.constructor === Athlete);
console.log(alexanderPopov.name + " " + alexanderPopov.sport + " " + alexanderPopov.quote);

// Reflection<commit_msg>7.6 Olympics: Finalize format, add reflection<commit_after>// Pair Challenge 7.6: JavaScript Olympics
// by Jeff George, 10/25/2015
// for DBC Phase 0

// I paired with Marie-France Han on this challenge.
// We worked together for about 2 hours, and I spent another hour following up.

/* Release 0 - Warm Up (File/Repo Prep) **************************************/

/* Release 1 - Bulk Up *******************************************************/

var sarahHughes = { name: "Sarah Hughes", event: "Ladies' Singles" };
var michelleKwan = { name: "Michelle Kwan", event: "Ladies' Singles" };
var yevgeniPlushenko = { name: "Yevgeni Plushenko", event: "Men's Singles" };
var paulWylie = { name: "Paul Wylie", event: "Men's Singles" };

var athletes = new Array(
  sarahHughes,
  michelleKwan,
  yevgeniPlushenko,
  paulWylie
);

function win(athletes) {
  for( var i = 0; i < athletes.length; i++) {
    athletes[i].win = function() {
      console.log(this.name + " won the " + this.event + "!");
    }
  }
}

console.log("\nRelease 1 ________________________________________________________");
console.log(athletes);
console.log("------------------------------------------------------------------");
win(athletes);
console.log(athletes);
console.log("------------------------------------------------------------------");
athletes[0].win();
console.log("==================================================================");

/* Release 2 - Jumble your words *********************************************/

function reverseStr(string) {
  var array = string.split("");
  return array = array.reverse().join("");
}

/* Driver code */
console.log("\nRelease 2 ________________________________________________________");
var str = "Banana";
console.log(reverseStr(str));
console.log("------------------------------------------------------------------");
var jumbleStr = "!sdrow ruoy elbmuJ"
console.log(reverseStr(jumbleStr));
console.log("==================================================================");

/* Release 3 - 2,4,6,8 *******************************************************/

function appreciate(array) {
  var output = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i]% 2 === 0) {
      output.push(array[i]);
    }
  }
  return output;
}

/* Driver code: */
console.log("\nRelease 3 ________________________________________________________");
console.log(appreciate([4,7,8,9,3,2.13,46,54]));
console.log("==================================================================");

/* Release 4 - "We built this city" ******************************************/

var Athlete = function(name, age, sport, quote) {
  this.name = name;
  this.age = age;
  this.sport = sport;
  this.quote = quote;
}

/* Driver code: */
console.log("\nRelease 4 ________________________________________________________");
var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal, I swear!");
console.log(michaelPhelps.constructor === Athlete);
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote);
console.log("------------------------------------------------------------------");
var alexanderPopov = new Athlete("Alexander Popov", 30, "swimming", "I'm the Torpedo!");
console.log(alexanderPopov.constructor === Athlete);
console.log(alexanderPopov.name + " " + alexanderPopov.sport + " " + alexanderPopov.quote);
console.log("==================================================================");

/******************************** Reflection **********************************\

What JavaScript knowledge did you solidify in this challenge?

In general, this challenge improved my understanding of defining functions in
JavaScript, especially constructor functions.

What are constructor functions?

Constructor functions are special functions that can be used to conveniently
create instances of a given type of object. Once you've created a constructor
function, you can create instances of that object type with the simple "var/new"
syntax, in which the values of the properties for the new object are passed into
the constructor function as arguments.

How are constructors different from Ruby classes (in your research)?

Constructors in JS are written as functions, while classes are objects of the
class Class. This appears make a major difference in terms of inheritance--in
Ruby, classes and their instances can inherit methods from their
super-classes; in JavaScript, the concepts of class and super-class don't seem
to exist. If you want a JavaScript constructor to pass functionality to its
instances, I believe you have to code it into the constructor explicitly.

\*******************************************************************************/<|endoftext|>