<commit_before>var _ = require('lodash');
var constants = require('../public/shared/gj_constants');

var GameObject = require('./game_object');
var Bloodsplosion = require('./bloodsplosion');
var Axe = require('./axe');
var Lazer = require('./lazer');

var SPAWN_COUNTDOWN = 30;
var INVULNERABLE_COUNTDOWN = 30;

var Player = function(id, color) {

    Player.superclass.call(this, id);

    this.type = 'player';
    this.color = color;
    this.x = 400;
    this.y = 320;
    this.w = 16;
    this.h = 24;

    this.kills = 0;
    this.deaths = 0;
    this.facex = 1;

    this.dead = false;
    this.jumped = false;

    this.spawnCountdown = SPAWN_COUNTDOWN;
    this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;

    this._keysDown = {};
    this._prevKeysDown = {};
    this._mousePos = { x: null, y: null };
    this._mouseDown = false;
    this._mouseWasDown = false;
    this._standing = 0; // When greater than zero, the player is on the ground.  Counts down every frame. Reset every time a ground collision is detected.
    this._roofing = 0; // same as standing but for roof
    this._droppingKick = false;
    this._justDied = false;

    this._cachedMap = null;
    this._fireDelay = 400;
    this._lastFireTime = null;
};

Player.superclass = GameObject;

_.extend(
    Player.prototype,
    GameObject.prototype,
    {
        update: function(state) {
            this._cachedMap = state.maps[state.era];

            this.jumped = false;

            if (this._justDied) {
                var emitter = new Bloodsplosion(this.x, this.y - this.h / 2);
                state.addObject(emitter);
                this._justDied = false;
                this.dead = true;
                this.vx = this.vy = 0;
                this.spawnCountdown = SPAWN_COUNTDOWN;
                this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;
                return;
            }

            if (this.spawnCountdown > 0) {
                if (--this.spawnCountdown <= 0) {
                    this.dead = false;
                    this.moveToSpawnPoint();
                } else return;
            }

            if (this.invulnerableCountdown > 0) {
                --this.invulnerableCountdown;
            }

            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.facex = -1;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.facex = 1;
            }

            if (this._standing > 0) this._standing--;
            if (this._roofing > 0) this._roofing--;

            switch (state.era) {
                case constants.eras.JUNGLE:
                    this.moveSelf_jungle(state);
                    break;
                case constants.eras.TUNDRA:
                    this.moveSelf_tundra(state);
                    break;
                case constants.eras.FUTURE:
                    this.moveSelf_future(state);
                    break;
            }

            if (this._mouseDown) {
                if (!this._lastFireTime || (new Date().getTime() - this._lastFireTime) > this._fireDelay) {
                    this._lastFireTime = new Date().getTime();
                    this.fireWeapon(state);
                }
            }

            // Integrate velocity in to position and collide with the map.
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null));
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null));

            this._prevKeysDown = _.clone(this._keysDown);
        },

        collideWithObject: function(other) {
            if (this._droppingKick && other.takeDamage) {
                if (this.y > other.y || !other._droppingKick) {
//                    other.takeDamage(this,this._cachedState);
                }
            }
        },

        _moveX: function (turnx, accx, decayx, maxx) {
            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.vx += this.vx > 0 ? -turnx : -accx;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.vx += this.vx < 0 ? turnx : accx;
            } else {
                this.vx *= decayx;
            }
            if (this.vx > maxx) {
                this.vx = maxx;
            } else if (this.vx < -maxx) {
                this.vx = -maxx;
            }
        },

        moveSelf_future: function(state) {
            var JET_UP = 1.2;
            var JET_SAVE = 1.6;

            if (this._standing) {
                this._moveX(2, 0.5, 0.8, 4);// Ground
            } else {
                this._moveX(0.5, 0.3, 1, 6);// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                this._standing = 0;
                this.vy -= this.vy >= 0 ? JET_SAVE : JET_UP;
                this.vy -= 0.3;
                this.jumped = true;
            }
            this.vy += 0.8;

            if (this._roofing > 0) {
                this.vy = 4;
            }

            if (this.vy > 12) {
                this.vy = 12;
            }
            else if (this.vy < -6) {
                this.vy = -6;
            }
        },

        moveSelf_basic: function(state) {
            if (this._standing) {
                this._moveX(2, 0.5, 0.8, 6);// Ground
            } else {
                this._moveX(1, 0.3, 0.9, 6);// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                if (this._standing > 0) {
                    this._standing = 0;
                    this.vy = -10;
                    this.jumped = true;
                }
                if (this.vy < 0) {
                    this.vy -= 0.5;
                    this.y -= 0.3;
                }
            }

            this.vy += 1.0;

            if (this.vy > 12) {
                this.vy = 12;
            }
        },

        _startKick: function() {
            var theta = Math.atan2(this._mousePos.y - (this.y - this.h/2), this._mousePos.x - this.x);
            if (theta > 0) {
                if      (theta <   Math.PI/4) theta =   Math.PI/4;
                else if (theta > 3*Math.PI/4) theta = 3*Math.PI/4;
            } else {
                if (theta > -Math.PI/2) theta =   Math.PI/4;
                else                    theta = 3*Math.PI/4;
            }
            this.vx = 15 * Math.cos (theta);
            this.vy = 15 * Math.sin (theta);
        },

        moveSelf_jungle: function(state) {
            if (this._standing) {
                this._droppingKick = false;
            } else if (!this._mouseWasDown && this._mouseDown && !this._droppingKick) {
                this._droppingKick = true;
                this._startKick();
            }

            if (!this._droppingKick) {
                this.moveSelf_basic(state);
            }
        },

        moveSelf_tundra: function(state) {
            this.moveSelf_basic(state);
        },

        fireWeapon: function(state) {
            var projectile;

            switch (state.era) {
                case constants.eras.TUNDRA:
                    projectile = Axe;
                    break;
                case constants.eras.FUTURE:
                    projectile = Lazer;
                    break;
            }

            if (projectile) {
                projectile = new projectile(this, { x: this._mousePos.x, y: this._mousePos.y });

                state.addObject(projectile);
            }
        },

        moveToSpawnPoint: function() {
            var map = this._cachedMap;
            var spawnPoint = _.sample(map._spawnPoints);
            this.x = constants.TILE_SIZE * spawnPoint[0];
            this.y = constants.TILE_SIZE * spawnPoint[1];
        },

        takeDamage: function(other) {
            if (this._justDied || this.dead) return;
            if (other && other._owner) {
                other._owner.kills++;
            }
            this.deaths++;
            this._justDied = true;
        },

        handleInput: function(input) {
            switch (input.type) {
                case 'keydown':
                    this._keysDown[input.key] = true;
                    break;
                case 'keyup':
                    delete this._keysDown[input.key];
                    break;
                case 'mousemove':
                    this._mousePos.x = input.x;
                    this._mousePos.y = input.y;
                    break;
                case 'mousedown':
                    this._mouseWasDown = this._mouseDown;
                    this._mouseDown = true;
                    break;
                case 'mouseup':
                    this._mouseDown = false;
                    break;
            }
        },

        collideWithMap: function(map, damaged) {
            map._sampledFatalTile = false;

            if (map.sampleAtPixel(this.x - this.w / 2, this.y - this.h / 2)
                || map.sampleAtPixel(this.x - this.w / 2, this.y - 2 - (this.vy > 0 ? this.vy : 0))
                || map.sampleAtPixel(this.x - this.w / 2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w / 2, this.y - this.h / 2)
                || map.sampleAtPixel(this.x + this.w / 2, this.y - 2 - (this.vy > 0 ? this.vy : 0))
                || map.sampleAtPixel(this.x + this.w / 2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = -Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w / 2 - 2, this.y, this.vy > 0)
                || map.sampleAtPixel(this.x - this.w / 2 + 2, this.y, this.vy > 0)) {
                this.y = constants.TILE_SIZE * Math.floor(this.y / constants.TILE_SIZE);
                this.vy = 0;
                this._standing = 2;
            }
            if (map.sampleAtPixel(this.x + this.w / 2 - 2, this.y - this.h)
                || map.sampleAtPixel(this.x - this.w / 2 + 2, this.y - this.h)) {
                this.y = constants.TILE_SIZE * Math.ceil(this.y / constants.TILE_SIZE);
                if (this.vy < 0) this.vy = 0;
                this._roofing = 2;
            }

            // TODO make sure taking damage here doesnt allow double death
            if (map._sampledFatalTile && damaged && !this.invulnerableCountdown) damaged();
        }
    }
);

module.exports = Player;
<commit_msg>Reimplemented dropkicks<commit_after>var _ = require('lodash');
var constants = require('../public/shared/gj_constants');

var GameObject = require('./game_object');
var Bloodsplosion = require('./bloodsplosion');
var Axe = require('./axe');
var Lazer = require('./lazer');

var SPAWN_COUNTDOWN = 30;
var INVULNERABLE_COUNTDOWN = 30;

var Player = function(id, color) {

    Player.superclass.call(this, id);

    this.type = 'player';
    this.color = color;
    this.x = 400;
    this.y = 320;
    this.w = 16;
    this.h = 24;

    this.kills = 0;
    this.deaths = 0;
    this.facex = 1;

    this.dead = false;
    this.jumped = false;

    this.spawnCountdown = SPAWN_COUNTDOWN;
    this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;

    this._keysDown = {};
    this._prevKeysDown = {};
    this._mousePos = { x: null, y: null };
    this._mouseDown = false;
    this._mouseWasDown = false;
    this._standing = 0; // When greater than zero, the player is on the ground.  Counts down every frame. Reset every time a ground collision is detected.
    this._roofing = 0; // same as standing but for roof
    this._droppingKick = false;
    this._justDied = false;

    this._cachedMap = null;
    this._fireDelay = 400;
    this._lastFireTime = null;
};

Player.superclass = GameObject;

_.extend(
    Player.prototype,
    GameObject.prototype,
    {
        update: function(state) {
            this._cachedMap = state.maps[state.era];

            this.jumped = false;

            if (this._justDied) {
                var emitter = new Bloodsplosion(this.x, this.y - this.h / 2);
                state.addObject(emitter);
                this._justDied = false;
                this.dead = true;
                this.vx = this.vy = 0;
                this.spawnCountdown = SPAWN_COUNTDOWN;
                this.invulnerableCountdown = INVULNERABLE_COUNTDOWN;
                return;
            }

            if (this.spawnCountdown > 0) {
                if (--this.spawnCountdown <= 0) {
                    this.dead = false;
                    this.moveToSpawnPoint();
                } else return;
            }

            if (this.invulnerableCountdown > 0) {
                --this.invulnerableCountdown;
            }

            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.facex = -1;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.facex = 1;
            }

            if (this._standing > 0) this._standing--;
            if (this._roofing > 0) this._roofing--;

            switch (state.era) {
                case constants.eras.JUNGLE:
                    this.moveSelf_jungle(state);
                    break;
                case constants.eras.TUNDRA:
                    this.moveSelf_tundra(state);
                    break;
                case constants.eras.FUTURE:
                    this.moveSelf_future(state);
                    break;
            }

            if (this._mouseDown) {
                if (!this._lastFireTime || (new Date().getTime() - this._lastFireTime) > this._fireDelay) {
                    this._lastFireTime = new Date().getTime();
                    this.fireWeapon(state);
                }
            }

            // Integrate velocity in to position and collide with the map.
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null));
            this.x += this.vx/2;
            this.y += this.vy/2;
            this.collideWithMap(state.maps[state.era], this.takeDamage.bind(this,null));

            this._prevKeysDown = _.clone(this._keysDown);
        },

        collideWithObject: function(other) {
            if (this._droppingKick && other.takeDamage) {
                if (this.y > other.y || !other._droppingKick) {
                    other.takeDamage(this);
                }
            }
        },

        _moveX: function (turnx, accx, decayx, maxx) {
            if (this._keysDown[constants.keys.MOVE_LEFT]) {
                this.vx += this.vx > 0 ? -turnx : -accx;
            } else if (this._keysDown[constants.keys.MOVE_RIGHT]) {
                this.vx += this.vx < 0 ? turnx : accx;
            } else {
                this.vx *= decayx;
            }
            if (this.vx > maxx) {
                this.vx = maxx;
            } else if (this.vx < -maxx) {
                this.vx = -maxx;
            }
        },

        moveSelf_future: function(state) {
            var JET_UP = 1.2;
            var JET_SAVE = 1.6;

            if (this._standing) {
                this._moveX(2, 0.5, 0.8, 4);// Ground
            } else {
                this._moveX(0.5, 0.3, 1, 6);// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                this._standing = 0;
                this.vy -= this.vy >= 0 ? JET_SAVE : JET_UP;
                this.vy -= 0.3;
                this.jumped = true;
            }
            this.vy += 0.8;

            if (this._roofing > 0) {
                this.vy = 4;
            }

            if (this.vy > 12) {
                this.vy = 12;
            }
            else if (this.vy < -6) {
                this.vy = -6;
            }
        },

        moveSelf_basic: function(state) {
            if (this._standing) {
                this._moveX(2, 0.5, 0.8, 6);// Ground
            } else {
                this._moveX(1, 0.3, 0.9, 6);// Air
            }

            if (this._keysDown[constants.keys.JUMP]) {
                if (this._standing > 0) {
                    this._standing = 0;
                    this.vy = -10;
                    this.jumped = true;
                }
                if (this.vy < 0) {
                    this.vy -= 0.5;
                    this.y -= 0.3;
                }
            }

            this.vy += 1.0;

            if (this.vy > 12) {
                this.vy = 12;
            }
        },

        _startKick: function() {
            var theta = Math.atan2(this._mousePos.y - (this.y - this.h/2), this._mousePos.x - this.x);
            if (theta > 0) {
                if      (theta <   Math.PI/4) theta =   Math.PI/4;
                else if (theta > 3*Math.PI/4) theta = 3*Math.PI/4;
            } else {
                if (theta > -Math.PI/2) theta =   Math.PI/4;
                else                    theta = 3*Math.PI/4;
            }
            this.vx = 15 * Math.cos (theta);
            this.vy = 15 * Math.sin (theta);
        },

        moveSelf_jungle: function(state) {
            if (this._standing) {
                this._droppingKick = false;
            } else if (!this._mouseWasDown && this._mouseDown && !this._droppingKick) {
                this._droppingKick = true;
                this._startKick();
            }

            if (!this._droppingKick) {
                this.moveSelf_basic(state);
            }
        },

        moveSelf_tundra: function(state) {
            this.moveSelf_basic(state);
        },

        fireWeapon: function(state) {
            var projectile;

            switch (state.era) {
                case constants.eras.TUNDRA:
                    projectile = Axe;
                    break;
                case constants.eras.FUTURE:
                    projectile = Lazer;
                    break;
            }

            if (projectile) {
                projectile = new projectile(this, { x: this._mousePos.x, y: this._mousePos.y });

                state.addObject(projectile);
            }
        },

        moveToSpawnPoint: function() {
            var map = this._cachedMap;
            var spawnPoint = _.sample(map._spawnPoints);
            this.x = constants.TILE_SIZE * spawnPoint[0];
            this.y = constants.TILE_SIZE * spawnPoint[1];
        },

        takeDamage: function(other) {
            if (this._justDied || this.dead) return;
            if (other && other._owner) {
                other._owner.kills++;
            }
            this.deaths++;
            this._justDied = true;
        },

        handleInput: function(input) {
            switch (input.type) {
                case 'keydown':
                    this._keysDown[input.key] = true;
                    break;
                case 'keyup':
                    delete this._keysDown[input.key];
                    break;
                case 'mousemove':
                    this._mousePos.x = input.x;
                    this._mousePos.y = input.y;
                    break;
                case 'mousedown':
                    this._mouseWasDown = this._mouseDown;
                    this._mouseDown = true;
                    break;
                case 'mouseup':
                    this._mouseDown = false;
                    break;
            }
        },

        collideWithMap: function(map, damaged) {
            map._sampledFatalTile = false;

            if (map.sampleAtPixel(this.x - this.w / 2, this.y - this.h / 2)
                || map.sampleAtPixel(this.x - this.w / 2, this.y - 2 - (this.vy > 0 ? this.vy : 0))
                || map.sampleAtPixel(this.x - this.w / 2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w / 2, this.y - this.h / 2)
                || map.sampleAtPixel(this.x + this.w / 2, this.y - 2 - (this.vy > 0 ? this.vy : 0))
                || map.sampleAtPixel(this.x + this.w / 2, this.y - this.h + 2)) {
                this.x = constants.TILE_SIZE / 2 + constants.TILE_SIZE * Math.floor(this.x / constants.TILE_SIZE);
                if (this._droppingKick) {
                    this._droppingKick = false;
                    this.vx = -Math.abs(this.vx)/2;
                } else {
                    this.vx = 0;
                }
            }
            if (map.sampleAtPixel(this.x + this.w / 2 - 2, this.y, this.vy > 0)
                || map.sampleAtPixel(this.x - this.w / 2 + 2, this.y, this.vy > 0)) {
                this.y = constants.TILE_SIZE * Math.floor(this.y / constants.TILE_SIZE);
                this.vy = 0;
                this._standing = 2;
            }
            if (map.sampleAtPixel(this.x + this.w / 2 - 2, this.y - this.h)
                || map.sampleAtPixel(this.x - this.w / 2 + 2, this.y - this.h)) {
                this.y = constants.TILE_SIZE * Math.ceil(this.y / constants.TILE_SIZE);
                if (this.vy < 0) this.vy = 0;
                this._roofing = 2;
            }

            // TODO make sure taking damage here doesnt allow double death
            if (map._sampledFatalTile && damaged && !this.invulnerableCountdown) damaged();
        }
    }
);

module.exports = Player;
<|endoftext|>


<commit_before>(function(module){

  var retrieveData = [];
  var objData = {};
  objData.all = [];
  objData.request = function(){
    console.log('click');
    $('#btn_search').on('click',function(){
      if (localStorage.searchResult) {
        retrieveData.push(JSON.parse(localStorage.getItem('searchResult')));
        retrieveData.push($('#searchText').val());
        localStorage.setItem('searchResult', JSON.stringify(retrieveData));
      }else {
        localStorage.setItem('searchResult', JSON.stringify($('#searchText').val()));
      }
    });
  }
  module.objData = objData;
})(window);
<commit_msg>local storage , fix array<commit_after>(function(module){

  var retrieveData = [];
  var getData;
  var objData = {};
  objData.all = [];
  objData.request = function(){
    console.log('click');
    $('#btn_search').on('click',function(){
      if (localStorage.searchResult) {
        retrieveData.push(JSON.parse(localStorage.getItem('searchResult')));
        retrieveData.push($('#searchText').val());
        localStorage.setItem('searchResult', JSON.stringify(retrieveData));
      }else {
        localStorage.setItem('searchResult', JSON.stringify($('#searchText').val()));
      }
    });
  }
  module.objData = objData;
})(window);
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2014 Felipe Ribeiro
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Quicksort recursively sorts parts of the array in
 * O(n.lg n)
 */
var quicksort = function(array, lo, hi) {

  if (lo === undefined) lo = 0;
  if (hi === undefined) hi = array.length - 1;

  if (lo < hi) {
    var p = partition(array, lo, hi);
    quicksort(array, lo, p - 1);
    quicksort(array, p + 1, hi);
  }

  return array;
};

/**
 * Chooses a pivot and makes every element that is
 * lower than the pivot move to its left, and every
 * greater element moves to its right
 *
 * @return Number the positon of the pivot
 */
var partition = function(a, lo, hi) {
  // pick a random element, swap with the rightmost and
  // use it as pivot
  swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi);
  var pivot = hi;

  // dividerPosition keeps track of the position
  // where the pivot should be inserted
  var dividerPosition = lo;

  for (var i = lo; i < hi; i++) {
    if (a[i] < a[pivot]) {
      swap(a, i, dividerPosition);
      dividerPosition++;
    }
  }
  swap(a, dividerPosition, pivot);
  return dividerPosition;
};

/**
 * Swaps two elements in the array
 */
var swap = function(array, x, y) {
  var tmp = array[y];
  array[y] = array[x];
  array[x] = tmp;
};

module.exports = quicksort;
<commit_msg>Quicksort<commit_after>/**
 * Copyright (C) 2014 Felipe Ribeiro
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * Quicksort recursively sorts parts of the array in
 * O(n.lg n)
 */
var quicksort = function(array, lo, hi) {

  // Sets the lo and hi values when they're not provided
  // (i.e. the initial call)
  if (lo === undefined) lo = 0;
  if (hi === undefined) hi = array.length - 1;

  if (lo < hi) {
    var p = partition(array, lo, hi);
    quicksort(array, lo, p - 1);
    quicksort(array, p + 1, hi);
  }

  return array;
};

/**
 * Chooses a pivot and makes every element that is
 * lower than the pivot move to its left, and every
 * greater element moves to its right
 *
 * @return Number the positon of the pivot
 */
var partition = function(a, lo, hi) {
  // pick a random element, swap with the rightmost and
  // use it as pivot
  swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi);
  var pivot = hi;

  // dividerPosition keeps track of the position
  // where the pivot should be inserted
  var dividerPosition = lo;

  for (var i = lo; i < hi; i++) {
    if (a[i] < a[pivot]) {
      swap(a, i, dividerPosition);
      dividerPosition++;
    }
  }
  swap(a, dividerPosition, pivot);
  return dividerPosition;
};

/**
 * Swaps two elements in the array
 */
var swap = function(array, x, y) {
  var tmp = array[y];
  array[y] = array[x];
  array[x] = tmp;
};

module.exports = quicksort;
<|endoftext|>


<commit_before>// console.log($("#bells").find(".active").attr("id"));

function Timer(time, name) {
	this.time = time;
	this.name = name;
}

Timer.prototype = {
	started: false,
	timesRun: 0,
	done: false,

	setTime: function(time) {
		this.time = time;
	},

	getTime: function() {
		return this.time;
	},

	getText: function() {
		var minutes = Math.floor(this.time/60).toString();
		var seconds = (this.time - (minutes * 60)).toString();
		if (minutes < 10) {
			minutes = "0" + minutes;
		}
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
		return minutes + ":" + seconds;
	},

	updateText: function() {
		var time = this.getText();

		$("#" + this.name + "-time").find(".time").text(time);
		$("#" + this.name).find(".time").text(time);
	},

	minuteUp: function() {
		this.time = this.time + 60;
	},

	minuteDown: function() {
		if (this.time > 59) {
			this.time = this.time - 60;
		}
	},

	secondDown: function() {
		if (this.time > 0) {
			this.time = this.time - 1;
		}
	},

	secondUp: function() {
		this.time = this.time + 1;
	}
}

function meditationTimer(time, name) {
	Timer.call(this, time, name);
	this.delay = 0;
	var self = this;

	this.start = function() {
		var bell = $(getActiveBell());
		if (!this.started) {
			this.startTime = this.time;
		}
		if ((!bell.get(0).ended) && (bell.get(0).currentTime != 0)) {
			bell.get(0).play();
		}
		this.timeout = setTimeout(this.countdown, this.delay*1000);
	}

	this.countdown = function() {
		if (!self.started) {
			makeVisible(self.name);
			makeActive(self.name);
			$(getActiveBell()).get(0).play();
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		clearTimeout(this.timeout);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		$(getActiveBell()).get(0).pause();
		$(getActiveBell()).get(0).currentTime = 0;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
		clearTimeout(self.timeout);
		$(getActiveBell()).get(0).pause();
	};

	this.end = function() {
		intTimer.stop();
		delTimer.stop();
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		$(getActiveBell).get(0).currentTime = 0;
		$(getActiveBell()).get(0).play();
		hide('stop-button');
		hide('pause-button');
		show('start-button');
		showArrows();
	};

	this.resume = function() {
		this.start();
	};

	this.setDelay = function(delay) {
		this.delay = delay;
	}

}

function delayTimer(time, name) {
	Timer.call(this, time, name);
	var self = this;
	this.done = false;

	this.start = function() {
		if (!this.done) {
			makeVisible(this.name);
			makeActive(this.name);
			if (!this.started) {
				this.startTime = this.time;
			}
			this.countdown();
			$(getActiveBellShort()).get(0).pause();
			$(getActiveBellShort()).get(0).currentTime = 0;
		}
	}

	this.countdown = function() {
		if (!self.started) {
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.done = true;
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.done = true;
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		this.done = false;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
	};
}

function intervalTimer(time, name) {
	Timer.call(this, time, name);
	var self = this;
	this.delay = 0;
	this.done = false;

	this.start = function() {
		if (this.time === 0) {
			this.done = true;
			this.startTime = 0;
		}
		if (!this.done) {
			if (!this.started) {
				this.startTime = this.time;
			}
			this.timeout = setTimeout(this.countdown, this.delay*1000);
		}
	};

	this.countdown = function() {
		if (!self.started) {
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		clearTimeout(this.timeout);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.done = false;
		this.timesRun = 0;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
		clearTimeout(self.timeout);
	};

	this.end = function() {
		$(getActiveBellShort()).get(0).play();
		this.done = true;
	};

	this.resume = function() {
		this.start();
	};

	this.setDelay = function(delay) {
		this.delay = delay;
	}

}

meditationTimer.prototype = Object.create(Timer.prototype);
meditationTimer.prototype.constructor = meditationTimer;
delayTimer.prototype = Object.create(Timer.prototype);
delayTimer.prototype.constructor = delayTimer;
intervalTimer.prototype = Object.create(Timer.prototype);
intervalTimer.prototype.constructor = intervalTimer;

var medTimer = new meditationTimer(600, 'meditation');
var delTimer = new delayTimer(10, 'delay');
var intTimer = new intervalTimer(0, 'interval');

// $('#delay-time').find('.time').text(delTimer.getText());
// $('#meditation-time').find('.time').text(medTimer.getText());
// $('#interval-time').find('.time').text(intTimer.getText());
// $('#delay').find('.small-time').text(delTimer.getText());
// $('#meditation').find('.small-time').text(medTimer.getText());
// $('#interval').find('.small-time').text(intTimer.getText());

function makeActive(id) {
	$('#' + id).addClass('active').siblings().removeClass('active');
}

function makeVisible(id) {
	var visibleTimer = '#' + $('#timers').find('.visible').attr('id');
	$(visibleTimer).removeClass('visible').addClass('invisible');
	$('#' + id + '-time').removeClass('invisible').addClass('visible');
}

function highlight() {
	//$(this).css('background-color', '#375661');
	$(this).addClass('highlighted');
}

function unhighlight() {
	//$(this).css('background-color', '#23444E');
	$(this).removeClass('highlighted');
}

function hide(id) {
	$('#' + id).addClass('hidden');
}

function show(id) {
	$('#' + id).removeClass('hidden');
}

function soundBell(id) {
	var activeId = '#'+ $('#' + id).parent().children('.playing').attr('id');
	$(activeId + '-audio').get(0).pause();
	$(activeId + '-audio').get(0).currentTime = 0;
	$(activeId).removeClass('playing');
	$('#' + id).addClass('playing');
	$('#' + id + '-audio').get(0).play();
}

function activateArrow(id) {
	var timer = getActiveTimer();
	switch(id) {
		case 'minute-up':
			timer.minuteUp();
			break;
		case 'minute-down':
			timer.minuteDown();
			break;
		case 'second-up':
			timer.secondUp();
			break;
		case 'second-down':
			timer.secondDown();
			break;
	}
	timer.updateText();
}

function getActiveTimer() {
	var active = $('.visible').attr('id');
	if (active == 'meditation-time') {
		var timer = medTimer;
	}
	else if (active == 'delay-time') {
		var timer = delTimer;
	}
	else if (active =='interval-time') {
		var timer = intTimer;
	}
	return timer;
}

function getActiveBell() {
	var bell = $("#bells").find(".active").attr("id");
	return ("#" + bell + "-long-audio");
}

function getActiveBellShort() {
	var bell = $("#bells").find(".active").attr("id");
	return ("#" + bell + "-audio");
}

function hideArrows() {
	$("#arrows-up").removeClass("visible-arrow");
	$("#arrows-down").removeClass("visible-arrow");
	$("#arrows-up").addClass("invisible-arrow");
	$("#arrows-down").addClass("invisible-arrow");
}

function showArrows() {
	$("#arrows-up").addClass("visible-arrow");
	$("#arrows-down").addClass("visible-arrow");
	$("#arrows-up").removeClass("invisible-arrow");
	$("#arrows-down").removeClass("invisible-arrow");
}

function resume() {
	hide('resume-button');
	show('pause-button');
	delTimer.start();
	medTimer.start();
	intTimer.start();
}

function start() {
	hide('start-button');
	show('stop-button');
	show('pause-button');
	medTimer.setDelay(delTimer.time);
	intTimer.setDelay(delTimer.time);
	hideArrows();
	delTimer.start();
	medTimer.start();
	intTimer.start();
}

function stop() {
	delTimer.stop();
	medTimer.stop();
	intTimer.stop();
	hide('stop-button');
	hide('pause-button');
	show('start-button');
	showArrows();
	makeActive('meditation');
	makeVisible('meditation');
}

function pause() {
	delTimer.pause();
	medTimer.pause();
	intTimer.pause();
	medTimer.setDelay(delTimer.time);
	intTimer.setDelay(delTimer.time);
	hide('pause-button');
	show('resume-button');
}

function init() {
	$('#timer-buttons').on('click', '.button', function() {makeActive(this.id);});
	$('#timer-buttons').on('click', '.button', function() {makeVisible(this.id);});
	$('#timer-buttons').on('mouseenter', '.button', highlight);
	$('#timer-buttons').on('mouseleave', '.button', unhighlight);
	$('#bells').on('mouseenter', '.button', highlight);
	$('#bells').on('mouseleave', '.button', unhighlight);
	$('#bells').on('click', '.button', function() {soundBell(this.id);});
	$('#bells').on('click', '.button', function() {makeActive(this.id);});
	$('#start-stop-buttons').on('mouseenter', '.button', highlight);
	$('#start-stop-buttons').on('mouseleave', '.button', unhighlight);
	$('#timer').on('click', '.arrow', function() {activateArrow(this.id);});
	$('#start-button').on('click', start);
	$('#stop-button').on('click', stop);
	$('#pause-button').on('click', pause);
	$('#resume-button').on('click', resume);
	$(function() {
		$("#info-dialog").dialog({
			autoOpen: false,
			show: 'fade',
			hide: 'drop',
			modal: true,
			width: 450,
			minWidth: 700,
			maxHeight: 1200
		});
		$("#info").on("click", function() {
			$("#info-dialog").dialog("open");
		});
	});

	$(function() {
		$("#contact-dialog").dialog({
			autoOpen: false,
			show: 'fade',
			hide: 'drop',
			modal: true,
			width: 'auto'
	});
	$("#contact").on("click", function() {
		$("#contact-dialog").dialog("open");
		});
	});
}

$(document).ready(function() {
	init();
});<commit_msg>Added start/stop to 3-bell audio when start button is clicked; hope to fix issues with iOS Safari audio<commit_after>// console.log($("#bells").find(".active").attr("id"));

function Timer(time, name) {
	this.time = time;
	this.name = name;
}

Timer.prototype = {
	started: false,
	timesRun: 0,
	done: false,

	setTime: function(time) {
		this.time = time;
	},

	getTime: function() {
		return this.time;
	},

	getText: function() {
		var minutes = Math.floor(this.time/60).toString();
		var seconds = (this.time - (minutes * 60)).toString();
		if (minutes < 10) {
			minutes = "0" + minutes;
		}
		if (seconds < 10) {
			seconds = "0" + seconds;
		}
		return minutes + ":" + seconds;
	},

	updateText: function() {
		var time = this.getText();

		$("#" + this.name + "-time").find(".time").text(time);
		$("#" + this.name).find(".time").text(time);
	},

	minuteUp: function() {
		this.time = this.time + 60;
	},

	minuteDown: function() {
		if (this.time > 59) {
			this.time = this.time - 60;
		}
	},

	secondDown: function() {
		if (this.time > 0) {
			this.time = this.time - 1;
		}
	},

	secondUp: function() {
		this.time = this.time + 1;
	}
}

function meditationTimer(time, name) {
	Timer.call(this, time, name);
	this.delay = 0;
	var self = this;

	this.start = function() {
		var bell = $(getActiveBell());
		if (!this.started) {
			this.startTime = this.time;
		}
		if ((!bell.get(0).ended) && (bell.get(0).currentTime != 0)) {
			bell.get(0).play();
		}
		this.timeout = setTimeout(this.countdown, this.delay*1000);
	}

	this.countdown = function() {
		if (!self.started) {
			makeVisible(self.name);
			makeActive(self.name);
			$(getActiveBell()).get(0).play();
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		clearTimeout(this.timeout);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		$(getActiveBell()).get(0).pause();
		$(getActiveBell()).get(0).currentTime = 0;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
		clearTimeout(self.timeout);
		$(getActiveBell()).get(0).pause();
	};

	this.end = function() {
		intTimer.stop();
		delTimer.stop();
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		$(getActiveBell).get(0).currentTime = 0;
		$(getActiveBell()).get(0).play();
		hide('stop-button');
		hide('pause-button');
		show('start-button');
		showArrows();
	};

	this.resume = function() {
		this.start();
	};

	this.setDelay = function(delay) {
		this.delay = delay;
	}

}

function delayTimer(time, name) {
	Timer.call(this, time, name);
	var self = this;
	this.done = false;

	this.start = function() {
		if (!this.done) {
			makeVisible(this.name);
			makeActive(this.name);
			if (!this.started) {
				this.startTime = this.time;
			}
			this.countdown();
			$(getActiveBellShort()).get(0).pause();
			$(getActiveBellShort()).get(0).currentTime = 0;
		}
	}

	this.countdown = function() {
		if (!self.started) {
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.done = true;
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.done = true;
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.timesRun = 0;
		this.done = false;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
	};
}

function intervalTimer(time, name) {
	Timer.call(this, time, name);
	var self = this;
	this.delay = 0;
	this.done = false;

	this.start = function() {
		if (this.time === 0) {
			this.done = true;
			this.startTime = 0;
		}
		if (!this.done) {
			if (!this.started) {
				this.startTime = this.time;
			}
			this.timeout = setTimeout(this.countdown, this.delay*1000);
		}
	};

	this.countdown = function() {
		if (!self.started) {
			self.started = true;
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
		else {
			self.intervalID = setInterval(function() {
				self.timesRun++;
				self.secondDown();
				self.updateText();
				if (self.timesRun >= self.startTime) {
					clearInterval(self.intervalID);
					self.end();
				}
			}, 1000);
		}
	};

	this.stop = function() {
		clearInterval(this.intervalID);
		clearTimeout(this.timeout);
		this.setTime(this.startTime);
		this.updateText();
		this.started = false;
		this.done = false;
		this.timesRun = 0;
	};

	this.pause = function() {
		clearInterval(self.intervalID);
		clearTimeout(self.timeout);
	};

	this.end = function() {
		$(getActiveBellShort()).get(0).play();
		this.done = true;
	};

	this.resume = function() {
		this.start();
	};

	this.setDelay = function(delay) {
		this.delay = delay;
	}

}

meditationTimer.prototype = Object.create(Timer.prototype);
meditationTimer.prototype.constructor = meditationTimer;
delayTimer.prototype = Object.create(Timer.prototype);
delayTimer.prototype.constructor = delayTimer;
intervalTimer.prototype = Object.create(Timer.prototype);
intervalTimer.prototype.constructor = intervalTimer;

var medTimer = new meditationTimer(600, 'meditation');
var delTimer = new delayTimer(10, 'delay');
var intTimer = new intervalTimer(0, 'interval');

// $('#delay-time').find('.time').text(delTimer.getText());
// $('#meditation-time').find('.time').text(medTimer.getText());
// $('#interval-time').find('.time').text(intTimer.getText());
// $('#delay').find('.small-time').text(delTimer.getText());
// $('#meditation').find('.small-time').text(medTimer.getText());
// $('#interval').find('.small-time').text(intTimer.getText());

function makeActive(id) {
	$('#' + id).addClass('active').siblings().removeClass('active');
}

function makeVisible(id) {
	var visibleTimer = '#' + $('#timers').find('.visible').attr('id');
	$(visibleTimer).removeClass('visible').addClass('invisible');
	$('#' + id + '-time').removeClass('invisible').addClass('visible');
}

function highlight() {
	//$(this).css('background-color', '#375661');
	$(this).addClass('highlighted');
}

function unhighlight() {
	//$(this).css('background-color', '#23444E');
	$(this).removeClass('highlighted');
}

function hide(id) {
	$('#' + id).addClass('hidden');
}

function show(id) {
	$('#' + id).removeClass('hidden');
}

function soundBell(id) {
	var activeId = '#'+ $('#' + id).parent().children('.playing').attr('id');
	$(activeId + '-audio').get(0).pause();
	$(activeId + '-audio').get(0).currentTime = 0;
	$(activeId).removeClass('playing');
	$('#' + id).addClass('playing');
	$('#' + id + '-audio').get(0).play();
}

function activateArrow(id) {
	var timer = getActiveTimer();
	switch(id) {
		case 'minute-up':
			timer.minuteUp();
			break;
		case 'minute-down':
			timer.minuteDown();
			break;
		case 'second-up':
			timer.secondUp();
			break;
		case 'second-down':
			timer.secondDown();
			break;
	}
	timer.updateText();
}

function getActiveTimer() {
	var active = $('.visible').attr('id');
	if (active == 'meditation-time') {
		var timer = medTimer;
	}
	else if (active == 'delay-time') {
		var timer = delTimer;
	}
	else if (active =='interval-time') {
		var timer = intTimer;
	}
	return timer;
}

function getActiveBell() {
	var bell = $("#bells").find(".active").attr("id");
	return ("#" + bell + "-long-audio");
}

function getActiveBellShort() {
	var bell = $("#bells").find(".active").attr("id");
	return ("#" + bell + "-audio");
}

function hideArrows() {
	$("#arrows-up").removeClass("visible-arrow");
	$("#arrows-down").removeClass("visible-arrow");
	$("#arrows-up").addClass("invisible-arrow");
	$("#arrows-down").addClass("invisible-arrow");
}

function showArrows() {
	$("#arrows-up").addClass("visible-arrow");
	$("#arrows-down").addClass("visible-arrow");
	$("#arrows-up").removeClass("invisible-arrow");
	$("#arrows-down").removeClass("invisible-arrow");
}

function resume() {
	hide('resume-button');
	show('pause-button');
	delTimer.start();
	medTimer.start();
	intTimer.start();
}

function start() {
	hide('start-button');
	show('stop-button');
	show('pause-button');
	getActiveBell().get(0).play();
	getActiveBell.get(0).pause();
	getActiveBell.get(0).currentTime = 0;
	medTimer.setDelay(delTimer.time);
	intTimer.setDelay(delTimer.time);
	hideArrows();
	delTimer.start();
	medTimer.start();
	intTimer.start();
}

function stop() {
	delTimer.stop();
	medTimer.stop();
	intTimer.stop();
	hide('stop-button');
	hide('pause-button');
	show('start-button');
	showArrows();
	makeActive('meditation');
	makeVisible('meditation');
}

function pause() {
	delTimer.pause();
	medTimer.pause();
	intTimer.pause();
	medTimer.setDelay(delTimer.time);
	intTimer.setDelay(delTimer.time);
	hide('pause-button');
	show('resume-button');
}

function init() {
	$('#timer-buttons').on('click', '.button', function() {makeActive(this.id);});
	$('#timer-buttons').on('click', '.button', function() {makeVisible(this.id);});
	$('#timer-buttons').on('mouseenter', '.button', highlight);
	$('#timer-buttons').on('mouseleave', '.button', unhighlight);
	$('#bells').on('mouseenter', '.button', highlight);
	$('#bells').on('mouseleave', '.button', unhighlight);
	$('#bells').on('click', '.button', function() {soundBell(this.id);});
	$('#bells').on('click', '.button', function() {makeActive(this.id);});
	$('#start-stop-buttons').on('mouseenter', '.button', highlight);
	$('#start-stop-buttons').on('mouseleave', '.button', unhighlight);
	$('#timer').on('click', '.arrow', function() {activateArrow(this.id);});
	$('#start-button').on('click', start);
	$('#stop-button').on('click', stop);
	$('#pause-button').on('click', pause);
	$('#resume-button').on('click', resume);
	$(function() {
		$("#info-dialog").dialog({
			autoOpen: false,
			show: 'fade',
			hide: 'drop',
			modal: true,
			width: 450,
			minWidth: 700,
			maxHeight: 1200
		});
		$("#info").on("click", function() {
			$("#info-dialog").dialog("open");
		});
	});

	$(function() {
		$("#contact-dialog").dialog({
			autoOpen: false,
			show: 'fade',
			hide: 'drop',
			modal: true,
			width: 'auto'
	});
	$("#contact").on("click", function() {
		$("#contact-dialog").dialog("open");
		});
	});
}

$(document).ready(function() {
	init();
});<|endoftext|>


<commit_before>app.controller('TripCtrl', ['$scope', '$state', 'LxNotificationService', 'LxDialogService', 'LxDatePickerService',
    'gettextCatalog', 'authService', 'tripService', 'trip', function (
    $scope, $state, LxNotificationService, LxDialogService, LxDatePickerService, gettextCatalog, authService, tripService, trip) {

    if (authService.isLoggedIn() && tripService.all.length ===0) {
        tripService.getAll();
    }

    $scope.trips = tripService.all;
    $scope.trip = trip;

    $scope.editedTrip = new tripService.Trip();
    $scope.editedTrip.resetTo($scope.trip);
    $scope.editedTrip.isEditing = false;
    $scope.tempDestination = new tripService.Destination();
    setTimeout(function() { LxDatePickerService.disableAll() }, 1000);
    // In display mode, will display the current trip

    $scope.enterEditMode = function() {
        LxDatePickerService.enableAll();
        $scope.editedTrip.isEditing = true;
    };

    $scope.cancelEdit = function() {
        $scope.editedTrip.resetTo($scope.trip);
        $state.go('trip', {id: $scope.trip._id})
        LxDatePickerService.disableAll();
        $scope.editedTrip.isEditing = false;
    };

    $scope.confirmEdit = function() {
        tripService.update($scope.editedTrip);
        $scope.trip.resetTo($scope.editedTrip);
        LxDatePickerService.disableAll();
        $scope.editedTrip.isEditing = false;
    };

    $scope.confirmDelete = function() {
        LxNotificationService.confirm(gettextCatalog.getString('Delete Trip'),
            gettextCatalog.getString('Are you sure you want to delete the trip') + ' "' +
            trip.title + '"', {
                cancel:gettextCatalog.getString('Cancel'),
                ok:gettextCatalog.getString('Confirm')
            }, function(answer) {
                if (answer) {
                    tripService.remove($scope.trip);
                    $state.go('home');
                }
            });
    };

    $scope.showAddDestinationDialog = function (ev) {
        LxDialogService.open('add-trip-dialog');
        $scope.tempDestination.resetTo(new tripService.Destination());
        LxDatePickerService.handleClicks('add-trip-dialog');
    };

    $scope.closeAddDestinationDialog = function() {
        LxDatePickerService.endHandleClicks('add-trip-dialog');

    };

    $scope.addDestination = function(destination) {
        var dest = new tripService.Destination();
        dest.resetTo($scope.tempDestination);
        $scope.editedTrip.addDestination(dest);
        $scope.tempDestination.resetTo(new tripService.Destination());
        LxDialogService.close('add-trip-dialog');
    };

    $scope.removeDestination = function(destination) {
        $scope.editedTrip.removeDestination(destination);
    };

    $scope.map = {center: {latitude: 40.1451, longitude: -99.6680 }, zoom: 4, polys:[]};

    addPoly = function (destination) {
        var location = destination.location;
        var path = [location.latitude, location.longitude];
        $scope.map.polys.push(path);
    };

    updateMapBounds = function (bounds) {
        var bounds = new google.maps.LatLngBounds();
        _.each(trip.destinations, function(destination){
            var location = destination.location;
            bounds.extend(new google.maps.LatLng(location.latitude, location.longitude));
        });
        $scope.map.bounds = {
            northeast: {
                latitude: bounds.getNorthEast().lat(),
                longitude: bounds.getNorthEast().lng()
            },
            southwest: {
                latitude: bounds.getSouthWest().lat(),
                longitude: bounds.getSouthWest().lng()
            }
        }
    };

    $scope.loadDestinationsInMap = function(){
        console.log('esta pasando por loadDestination');
        if(!trip.destinations || trip.destinations.length === 0) { return; }

        _.each(trip.destinations, function(destination){
            addPoly(destination);
        });

        updateMapBounds();
    };

    $scope.loadDestinationsInMap();

}]);
<commit_msg>adding confirm dialog to delete a destination<commit_after>app.controller('TripCtrl', ['$scope', '$state', 'LxNotificationService', 'LxDialogService', 'LxDatePickerService',
    'gettextCatalog', 'authService', 'tripService', 'trip', function (
    $scope, $state, LxNotificationService, LxDialogService, LxDatePickerService, gettextCatalog, authService, tripService, trip) {

    if (authService.isLoggedIn() && tripService.all.length ===0) {
        tripService.getAll();
    }

    $scope.trips = tripService.all;
    $scope.trip = trip;

    $scope.editedTrip = new tripService.Trip();
    $scope.editedTrip.resetTo($scope.trip);
    $scope.editedTrip.isEditing = false;
    $scope.tempDestination = new tripService.Destination();
    setTimeout(function() { LxDatePickerService.disableAll() }, 1000);
    // In display mode, will display the current trip

    $scope.enterEditMode = function() {
        LxDatePickerService.enableAll();
        $scope.editedTrip.isEditing = true;
    };

    $scope.cancelEdit = function() {
        $scope.editedTrip.resetTo($scope.trip);
        $state.go('trip', {id: $scope.trip._id})
        LxDatePickerService.disableAll();
        $scope.editedTrip.isEditing = false;
    };

    $scope.confirmEdit = function() {
        tripService.update($scope.editedTrip);
        $scope.trip.resetTo($scope.editedTrip);
        LxDatePickerService.disableAll();
        $scope.editedTrip.isEditing = false;
    };

    $scope.confirmDelete = function() {
        LxNotificationService.confirm(gettextCatalog.getString('Delete Trip'),
            gettextCatalog.getString('Are you sure you want to delete the trip') + ' "' +
            trip.title + '"', {
                cancel:gettextCatalog.getString('Cancel'),
                ok:gettextCatalog.getString('Confirm')
            }, function(answer) {
                if (answer) {
                    tripService.remove($scope.trip);
                    $state.go('home');
                }
            });
    };

    $scope.showAddDestinationDialog = function (ev) {
        LxDialogService.open('add-trip-dialog');
        $scope.tempDestination.resetTo(new tripService.Destination());
        LxDatePickerService.handleClicks('add-trip-dialog');
    };

    $scope.closeAddDestinationDialog = function() {
        LxDatePickerService.endHandleClicks('add-trip-dialog');

    };

    $scope.addDestination = function(destination) {
        var dest = new tripService.Destination();
        dest.resetTo($scope.tempDestination);
        $scope.editedTrip.addDestination(dest);
        $scope.tempDestination.resetTo(new tripService.Destination());
        LxDialogService.close('add-trip-dialog');
    };

    $scope.removeDestination = function(destination) {
        LxNotificationService.confirm(gettextCatalog.getString('Delete Destination'),
            gettextCatalog.getString('Are you sure you want to delete the destination') + ' "' +
            destination.city + '"', {
                cancel:gettextCatalog.getString('Cancel'),
                ok:gettextCatalog.getString('Confirm')
            }, function(answer) {
                if (answer) {
                    $scope.editedTrip.removeDestination(destination);
                }
            });
    };

    $scope.map = {center: {latitude: 40.1451, longitude: -99.6680 }, zoom: 4, polys:[]};

    addPoly = function (destination) {
        var location = destination.location;
        var path = [location.latitude, location.longitude];
        $scope.map.polys.push(path);
    };

    updateMapBounds = function (bounds) {
        var bounds = new google.maps.LatLngBounds();
        _.each(trip.destinations, function(destination){
            var location = destination.location;
            bounds.extend(new google.maps.LatLng(location.latitude, location.longitude));
        });
        $scope.map.bounds = {
            northeast: {
                latitude: bounds.getNorthEast().lat(),
                longitude: bounds.getNorthEast().lng()
            },
            southwest: {
                latitude: bounds.getSouthWest().lat(),
                longitude: bounds.getSouthWest().lng()
            }
        }
    };

    $scope.loadDestinationsInMap = function(){
        console.log('esta pasando por loadDestination');
        if(!trip.destinations || trip.destinations.length === 0) { return; }

        _.each(trip.destinations, function(destination){
            addPoly(destination);
        });

        updateMapBounds();
    };

    $scope.loadDestinationsInMap();

}]);
<|endoftext|>


<commit_before>function searchFavorites(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		return feedback;
	} /*else {
		_.each(resultList, function(x) {
			if (x.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			} else if (x.tags.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);

			} else if (x.notes.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}*/
			/*else if (x.location.display_address.join(' ').toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}*/
		//});
	//}
	return feedback;
}

//filters are distance, rating, category
function filterFavorites(criterion, filter, results) {

	var feedback = [];
	if (filter == "rating") {
		feedback = _.filter(results, function(x) {
			return x.rating >= criterion;
		});
	} else if (filter == "distance") {
		var destinations = [];
		feedback = _.each(results, function(x) {
			var lat = parseFloat(x.coordinate.latitude);
			var lng = parseFloat(x.coordinate.longitude);
			var latlng = new google.maps.LatLng(lat, lng);
			destinations[x.name] = latlng;

		});
		var geo = new Geolocation;
		var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		var mapping = calculateDistances(locObj, Object.values(destinations));
		for (var i=0; i< mapping.values.length; i++){
			if ((mapping.values[i])[distance] <= criterion){
				feedback(destinations[i]);
			}
		}
		return findDistance(x) <= criterion;
		//within 'criterion' miles
	} else if (filter == "category" || filter == "categories") {
		getFavoriteCategories();
		 _.each(results, function(x) {
			for(thisList in businessAndCategories){
				if((typeof thisList[x] != "undefined") && thisList[x].contains(criterion)){
					feedback.push(x);
				}
			}
		});
	}
	/*return*/browseFavorites(feedback);
}

function sortFavorites(criterion, order, results){
	var feedback = [];
	if (criterion == "rating") {
		feedback = _.sortBy(results, function(x) {
			return x.rating;
		});
	} else if (criterion == "distance") {
		// var destinations = [];
		// feedback = _.each(results, function(x) {
		//	var lat = parseFloat(x.coordinate.latitude);
		//	var lng = parseFloat(x.coordinate.longitude);
		//	var latlng = new google.maps.LatLng(lat, lng);
		//	destinations[x.name] = latlng;

		// });
		// var geo = new Geolocation;
		// var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		// var mapping = calculateDistances(locObj, Object.values(destinations));
		// for (var i=0; i< mapping.values.length; i++){
		//	if ((mapping.values[i])[distance] <= criterion){
		//		feedback(destinations[i]);
		//	}
		// }
		// return findDistance(x);
		//within 'criterion' miles
	}

	if(order == "DESCENDING"){
		feedback.reverse();
	}

	browseFavorites(feedback);
}

function sortResults(criterion, order, results){
	var feedback = [];
	if (criterion == "rating") {
		feedback = _.sortBy(results, function(x) {
			return x.rating;
		});
	} else if (criterion == "distance") {
		// var destinations = [];
		// feedback = _.each(results, function(x) {
		//	var lat = parseFloat(x.coordinate.latitude);
		//	var lng = parseFloat(x.coordinate.longitude);
		//	var latlng = new google.maps.LatLng(lat, lng);
		//	destinations[x.name] = latlng;

		// });
		// var geo = new Geolocation;
		// var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		// var mapping = calculateDistances(locObj, Object.values(destinations));
		// for (var i=0; i< mapping.values.length; i++){
		//	if ((mapping.values[i])[distance] <= criterion){
		//		feedback(destinations[i]);
		//	}
		// }
		// return findDistance(x);
		//within 'criterion' miles
	}

	if(order == "DESCENDING"){
		feedback.reverse();
	}

	addQuery(feedback);
}

var businessAndCategories = [];
function getFavoriteCategories() {
	businessAndCategories = [];
	var feedback = {};
	var busName = "";
	var resultList = JSON.parse(localStorage.getItem("results"));
	//returns the list of lists (of categories);
	_.each(resultList, function(x) {
		feedback[x.name] = [];
		_.each(x.categories, function(y) {
			feedback[x.name].push(y[1]);
		});
	});
	var answer = {};
	var cats = {};
	_.each(feedback, function(innerCat, ky) {
		getBroadCategories(ky, answer, innerCat, allcategories);

	});

	return cats;
}

//this function needs testing
//innerCat has Traditional(American), Gluten-Free | Mexican, Catering
function getBroadCategories(busName, answers, innerCat, globalCategories) {
	for (var singleCat in innerCat) {
		answers[singleCat] = [];
		var hierarchy = [];
		var broadforthissub = findStrings(busName, innerCat[singleCat], hierarchy, globalCategories, globalCategories);
		answers[singleCat].push(broadforthissub);
	}
	return answers;
}

function findStrings(busName, singleCat, catsForThisCat, globalCategories, staticGlobal) {
	if ( typeof globalCategories == 'object') {
		for (var ky in globalCategories) {
			catsForThisCat.push(ky);

			if (typeof findStrings(busName, singleCat, catsForThisCat, globalCategories[ky], staticGlobal) == "object"){

			}else{
				while(Object.keys(staticGlobal).indexOf(catsForThisCat.pop()) != -1){
				}
			}

		}
		} else if ( typeof globalCategories == 'string') {

			if (globalCategories.toLowerCase().indexOf(singleCat.toLowerCase()) > -1) {
				saveThisHierachy(busName, singleCat, catsForThisCat);
				return catsForThisCat;
				//return the list which contains the hierachy of categories for this business
				//first element in the list is the inner most category and the last element is the broad category
			} else {
				return "NF";
			}
		}

}

function saveThisHierachy(bus, subcategory, tree){
	var bus_tree = {};
	tree.push(subcategory);
	bus_tree[bus] = tree;
	businessAndCategories.push(JSON.stringify(bus_tree));
}
function getFavoritesWithinCategory(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));

	_.each(resultList, function(x) {
		if (x.categories == query) {
			feedback.push(x);
		}
	});
	return feedback;
}

function addBusinessToFavorite(business) {
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		resultList = [];

	}
	resultList.push(business);
	localStorage.setItem("results", JSON.stringify(resultList));
}

function deleteBusinessFromStorage(business) {
    var resultList = JSON.parse(localStorage.getItem("results"));
    var temp = removeA(resultList, business);
    localStorage.setItem("results", JSON.stringify(temp));
    getBookmarks(lastTerm[0]);
}

function removeA(array, item) {
	 for(var i in array){
    if(array[i].id == item.id) {
            array.splice(i,1);
            break;
            }
    }
	return array;
}

function metersToMiles(meters){
    return meters * 0.000621371192;
}

function saveBookmark(business, tags, notes) {
	if (tags == undefined) {
		tags = " ";
	}
	if (notes == undefined) {
		notes = " ";
	}
	business.tags = tags;
	business.notes = notes;
	business.distance = metersToMiles(business.distance);
	var d = new Date();
	var day = d.getDate();
	var month = d.getMonth() + 1;
	var time = d.getTime();
	var year = d.getFullYear();
	business.dateAdded = time + " " + month + "/" + day + "/" + year;
	addBusinessToFavorite(business);
}<commit_msg>Uncomment search favorites code<commit_after>function searchFavorites(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		return feedback;
	} else {
		_.each(resultList, function(x) {
			if (x.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			} else if (x.tags.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);

			} else if (x.notes.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}
			else if (x.location.display_address.join(' ').toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}
		});
	}
	return feedback;
}

//filters are distance, rating, category
function filterFavorites(criterion, filter, results) {

	var feedback = [];
	if (filter == "rating") {
		feedback = _.filter(results, function(x) {
			return x.rating >= criterion;
		});
	} else if (filter == "distance") {
		var destinations = [];
		feedback = _.each(results, function(x) {
			var lat = parseFloat(x.coordinate.latitude);
			var lng = parseFloat(x.coordinate.longitude);
			var latlng = new google.maps.LatLng(lat, lng);
			destinations[x.name] = latlng;

		});
		var geo = new Geolocation;
		var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		var mapping = calculateDistances(locObj, Object.values(destinations));
		for (var i=0; i< mapping.values.length; i++){
			if ((mapping.values[i])[distance] <= criterion){
				feedback(destinations[i]);
			}
		}
		return findDistance(x) <= criterion;
		//within 'criterion' miles
	} else if (filter == "category" || filter == "categories") {
		getFavoriteCategories();
		 _.each(results, function(x) {
			for(thisList in businessAndCategories){
				if((typeof thisList[x] != "undefined") && thisList[x].contains(criterion)){
					feedback.push(x);
				}
			}
		});
	}
	/*return*/browseFavorites(feedback);
}

function sortFavorites(criterion, order, results){
	var feedback = [];
	if (criterion == "rating") {
		feedback = _.sortBy(results, function(x) {
			return x.rating;
		});
	} else if (criterion == "distance") {
		// var destinations = [];
		// feedback = _.each(results, function(x) {
		//	var lat = parseFloat(x.coordinate.latitude);
		//	var lng = parseFloat(x.coordinate.longitude);
		//	var latlng = new google.maps.LatLng(lat, lng);
		//	destinations[x.name] = latlng;

		// });
		// var geo = new Geolocation;
		// var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		// var mapping = calculateDistances(locObj, Object.values(destinations));
		// for (var i=0; i< mapping.values.length; i++){
		//	if ((mapping.values[i])[distance] <= criterion){
		//		feedback(destinations[i]);
		//	}
		// }
		// return findDistance(x);
		//within 'criterion' miles
	}

	if(order == "DESCENDING"){
		feedback.reverse();
	}

	browseFavorites(feedback);
}

function sortResults(criterion, order, results){
	var feedback = [];
	if (criterion == "rating") {
		feedback = _.sortBy(results, function(x) {
			return x.rating;
		});
	} else if (criterion == "distance") {
		// var destinations = [];
		// feedback = _.each(results, function(x) {
		//	var lat = parseFloat(x.coordinate.latitude);
		//	var lng = parseFloat(x.coordinate.longitude);
		//	var latlng = new google.maps.LatLng(lat, lng);
		//	destinations[x.name] = latlng;

		// });
		// var geo = new Geolocation;
		// var locObj = new google.maps.LatLng(geo.getCurrentLocation.latitude, geo.getCurrentLocation.longitude);
		// var mapping = calculateDistances(locObj, Object.values(destinations));
		// for (var i=0; i< mapping.values.length; i++){
		//	if ((mapping.values[i])[distance] <= criterion){
		//		feedback(destinations[i]);
		//	}
		// }
		// return findDistance(x);
		//within 'criterion' miles
	}

	if(order == "DESCENDING"){
		feedback.reverse();
	}

	addQuery(feedback);
}

var businessAndCategories = [];
function getFavoriteCategories() {
	businessAndCategories = [];
	var feedback = {};
	var busName = "";
	var resultList = JSON.parse(localStorage.getItem("results"));
	//returns the list of lists (of categories);
	_.each(resultList, function(x) {
		feedback[x.name] = [];
		_.each(x.categories, function(y) {
			feedback[x.name].push(y[1]);
		});
	});
	var answer = {};
	var cats = {};
	_.each(feedback, function(innerCat, ky) {
		getBroadCategories(ky, answer, innerCat, allcategories);

	});

	return cats;
}

//this function needs testing
//innerCat has Traditional(American), Gluten-Free | Mexican, Catering
function getBroadCategories(busName, answers, innerCat, globalCategories) {
	for (var singleCat in innerCat) {
		answers[singleCat] = [];
		var hierarchy = [];
		var broadforthissub = findStrings(busName, innerCat[singleCat], hierarchy, globalCategories, globalCategories);
		answers[singleCat].push(broadforthissub);
	}
	return answers;
}

function findStrings(busName, singleCat, catsForThisCat, globalCategories, staticGlobal) {
	if ( typeof globalCategories == 'object') {
		for (var ky in globalCategories) {
			catsForThisCat.push(ky);

			if (typeof findStrings(busName, singleCat, catsForThisCat, globalCategories[ky], staticGlobal) == "object"){

			}else{
				while(Object.keys(staticGlobal).indexOf(catsForThisCat.pop()) != -1){
				}
			}

		}
		} else if ( typeof globalCategories == 'string') {

			if (globalCategories.toLowerCase().indexOf(singleCat.toLowerCase()) > -1) {
				saveThisHierachy(busName, singleCat, catsForThisCat);
				return catsForThisCat;
				//return the list which contains the hierachy of categories for this business
				//first element in the list is the inner most category and the last element is the broad category
			} else {
				return "NF";
			}
		}

}

function saveThisHierachy(bus, subcategory, tree){
	var bus_tree = {};
	tree.push(subcategory);
	bus_tree[bus] = tree;
	businessAndCategories.push(JSON.stringify(bus_tree));
}
function getFavoritesWithinCategory(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));

	_.each(resultList, function(x) {
		if (x.categories == query) {
			feedback.push(x);
		}
	});
	return feedback;
}

function addBusinessToFavorite(business) {
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		resultList = [];

	}
	resultList.push(business);
	localStorage.setItem("results", JSON.stringify(resultList));
}

function deleteBusinessFromStorage(business) {
    var resultList = JSON.parse(localStorage.getItem("results"));
    var temp = removeA(resultList, business);
    localStorage.setItem("results", JSON.stringify(temp));
    getBookmarks(lastTerm[0]);
}

function removeA(array, item) {
	 for(var i in array){
    if(array[i].id == item.id) {
            array.splice(i,1);
            break;
            }
    }
	return array;
}

function metersToMiles(meters){
    return meters * 0.000621371192;
}

function saveBookmark(business, tags, notes) {
	if (tags == undefined) {
		tags = " ";
	}
	if (notes == undefined) {
		notes = " ";
	}
	business.tags = tags;
	business.notes = notes;
	business.distance = metersToMiles(business.distance);
	var d = new Date();
	var day = d.getDate();
	var month = d.getMonth() + 1;
	var time = d.getTime();
	var year = d.getFullYear();
	business.dateAdded = time + " " + month + "/" + day + "/" + year;
	addBusinessToFavorite(business);
}
<|endoftext|>


<commit_before>// Used to test in CI.

import { spawn } from 'child_process'
import assignEnvVars from './assign-env-vars'

// Set env vars.
assignEnvVars('test')

const tests = spawn('yarn', ['run', 'test-e2e'], {stdio: 'inherit'})

// Exit this process with the child process code.
tests.on('exit', (code) => process.exit(code))
<commit_msg>Script name fix.<commit_after>// Used to test in CI.

import { spawn } from 'child_process'
import assignEnvVars from './assign-env-vars'

// Set env vars.
assignEnvVars('test')

const tests = spawn('yarn', ['run', 'test:integration'], {stdio: 'inherit'})

// Exit this process with the child process code.
tests.on('exit', (code) => process.exit(code))
<|endoftext|>


<commit_before>/*
Sample file of exercises
*/

var animal1 = {
   'genus'        : 'cat',
   'species'      : 'biter',
   'callType'     : 'hissing',
   'quote'        : 'will look cute for bif',
   'maxOffspring' : 0,
   'noisy'        : false,
   'deadly'       : true
}

// Regular Expressions

var string1 = 'this is the best video'
var string2 = 'i love this video'
var string3 = 'it is the best ever'

var regex = /this/;

console.log( regex.test(string1) );
console.log( regex.test(string2) );
console.log( regex.test(string3) );

// Conditional Ifs

var	answer = window.promt('Type YES, NO, or MAYBE. Then click Ok.');

	if (answer === 'YES') { console.log('You brown noser!'); }

	else if (answer === 'NO') { console.log('How dare you deny me!'); }

	else if (answer === 'MAYBE') { console.log('What the fuck! Make up your mind!'); }

	else { console.log('This game is over.'); }

// Conditionals Switch

var	answer = window.promt('Type YES, NO, or MAYBE. Then click Ok.');

Switch (answer) {

	case 'YES' :
		console.log('You brown noser!');
		break;

	case 'MAYBE' :
		console.log('What the fuck! Make up your mind!');
		break;

	case 'NO' :
		console.log('How dare you deny me!');
		break;

	default :
		console.log('This game is over.');
		break;
}

// Terse Ifs: One-liners

var	cherub = 'Cupid';
  // cherub = 'Some other guy';

if (cherub === 'Cupid') console.log('Ouch, an arrow! Oh, I\'m in love!');

// Terse Ifs: Ternary Operator

var animal = 'cat';
// animal = 'dog';

animal === 'cat' ? console.log('You will be a cat herder') : console.log('You will be a dog catcher');

// var job = (animal === 'cat' ? 'cat herder' : 'dog catcher');

// For Loops - Sequencial

for (var i = 0; i < 100; i ++ 1) {
	console.log(i);
}

// Common use case; looping over an array

var pageNames = ['Home', 'About Us', 'Contact Us', 'JavaScript Playground', 'News', 'Blog'];

for (i = 0; i < pageNames.length; i+= 1) {
	if (document.title === pageNames[i]) {
		console.log('We are here: ' + pageNames[i]);
	} else {
		console.log('We are not here: ' + pageNames[i]);
	}
}

// Replace redundancy
var pageNames = ['Home', 'About Us', 'Contact Us', 'JavaScript Playground', 'News', 'Blog'];

for (i = 0; i < pageNames.length; i+= 1) {
	var currentPageTitle = pageNames[i];

	if (document.title === currentPageTitle) {
		console.log('We are here: ' + currentPageTitle);
	} else {
		console.log('We are not here: ' + currentPageTitle);
	}
}<commit_msg>added commands to JS sample file<commit_after>/*
Sample file of exercises
*/

// Create an Object

var animal1 = {
   'genus'        : 'cat',
   'species'      : 'biter',
   'callType'     : 'hissing',
   'quote'        : 'will look cute for bif',
   'maxOffspring' : 0,
   'noisy'        : false,
   'deadly'       : true
}

// Identify Object Value
animal1['quote']

// or
animal1.quote

// Display a value in html page
document.body.innerText = animal1.quote

// Adding a property to an Object
animal1.whereItLives = 'manhattan highrise';
// or
Animal1['whereItLives'] = 'manhattan highrise';

// Deleting a property to an Object
delete animal1.color;

/* References
	• This statement does not make the same copy of an object so changes to animal2 will apply to animal1.
	• This gives you two objects that point to the same value. You will only run into this when dealing with objects.
	• To copy an object, you will need to create another variable with the same properties.
*/
var animal2 = animal1;

// Regular Expressions

var string1 = 'this is the best video'
var string2 = 'i love this video'
var string3 = 'it is the best ever'

var regex = /this/;

console.log( regex.test(string1) );
console.log( regex.test(string2) );
console.log( regex.test(string3) );

// Conditional Ifs

var	answer = window.promt('Type YES, NO, or MAYBE. Then click Ok.');

	if (answer === 'YES') { console.log('You brown noser!'); }

	else if (answer === 'NO') { console.log('How dare you deny me!'); }

	else if (answer === 'MAYBE') { console.log('What the fuck! Make up your mind!'); }

	else { console.log('This game is over.'); }

// Conditionals Switch

var	answer = window.promt('Type YES, NO, or MAYBE. Then click Ok.');

Switch (answer) {

	case 'YES' :
		console.log('You brown noser!');
		break;

	case 'MAYBE' :
		console.log('What the fuck! Make up your mind!');
		break;

	case 'NO' :
		console.log('How dare you deny me!');
		break;

	default :
		console.log('This game is over.');
		break;
}

// Terse Ifs: One-liners

var	cherub = 'Cupid';
  // cherub = 'Some other guy';

if (cherub === 'Cupid') console.log('Ouch, an arrow! Oh, I\'m in love!');

// Terse Ifs: Ternary Operator

var animal = 'cat';
// animal = 'dog';

animal === 'cat' ? console.log('You will be a cat herder') : console.log('You will be a dog catcher');

// var job = (animal === 'cat' ? 'cat herder' : 'dog catcher');

// For Loops - Sequencial

for (var i = 0; i < 100; i ++ 1) {
	console.log(i);
}

// Common use case; looping over an array

var pageNames = ['Home', 'About Us', 'Contact Us', 'JavaScript Playground', 'News', 'Blog'];

for (i = 0; i < pageNames.length; i+= 1) {
	if (document.title === pageNames[i]) {
		console.log('We are here: ' + pageNames[i]);
	} else {
		console.log('We are not here: ' + pageNames[i]);
	}
}

// Replace redundancy
var pageNames = ['Home', 'About Us', 'Contact Us', 'JavaScript Playground', 'News', 'Blog'];

for (i = 0; i < pageNames.length; i+= 1) {
	var currentPageTitle = pageNames[i];

	if (document.title === currentPageTitle) {
		console.log('We are here: ' + currentPageTitle);
	} else {
		console.log('We are not here: ' + currentPageTitle);
	}
}

/* For Loops - Enumerative
   	Used for arrays and objects
	It's NOT adviced to use a 'for in' loop for an array since in an array, the order is important
	You can use it on other objects.
*/

// iterate over an array

var pageNames = ['Home', 'About Us', 'Contact Us', 'JavaScript Playground', 'News', 'Blog'];

for (var p in pageNames) {
	console.log(p + ' is ' + pageNames[p]);
}

// iterate over an object

var pages = {
	first  : 'Home',
	second : 'About Us',
	third  : 'Contact Us',
	fourth : 'JavaScript Playground',
	fifth  : 'Blog'
};

for (var p in pages) {
	if (pages.hasOwnProperty(p)) {
		console.log(p + ' is ' + pages[p]);
	}
}

<|endoftext|>


<commit_before>(function () {
  'use strict';

  describe('Invoices Admin Controller Tests', function () {
    // Initialize global variables
    var InvoicesAdminController,
      $scope,
      $httpBackend,
      $state,
      Authentication,
      InvoicesService,
      mockInvoice,
      Notification;

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _InvoicesService_, _Notification_) {
      // Set a new global scope
      $scope = $rootScope.$new();

      // Point global variables to injected services
      $httpBackend = _$httpBackend_;
      $state = _$state_;
      Authentication = _Authentication_;
      InvoicesService = _InvoicesService_;
      Notification = _Notification_;

      // Ignore parent template get on state transitions
      $httpBackend.whenGET('/modules/core/client/views/home.client.view.html').respond(200, '');

      // create mock invoice
      mockInvoice = new InvoicesService({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An Invoice about MEAN',
        content: 'MEAN rocks!'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['user']
      };

      // Initialize the Invoices controller.
      InvoicesAdminController = $controller('InvoicesAdminController as vm', {
        $scope: $scope,
        invoiceResolve: {}
      });

      // Spy on state go
      spyOn($state, 'go');
      spyOn(Notification, 'error');
      spyOn(Notification, 'success');
    }));

    describe('vm.save() as create', function () {
      var sampleInvoicePostData;

      beforeEach(function () {
        // Create a sample invoice object
        sampleInvoicePostData = new InvoicesService({
          title: 'An Invoice about MEAN',
          content: 'MEAN rocks!'
        });

        $scope.vm.invoice = sampleInvoicePostData;
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (InvoicesService) {
        // Set POST response
        $httpBackend.expectPOST('/api/invoices', sampleInvoicePostData).respond(mockInvoice);

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test Notification success was called
        expect(Notification.success).toHaveBeenCalledWith({ message: ' Invoice saved successfully!' });
        // Test URL redirection after the invoice was created
        expect($state.go).toHaveBeenCalledWith('admin.invoices.list');
      }));

      it('should call Notification.error if error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('/api/invoices', sampleInvoicePostData).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect(Notification.error).toHaveBeenCalledWith({ message: errorMessage, title: ' Invoice save error!' });
      });
    });

    describe('vm.save() as update', function () {
      beforeEach(function () {
        // Mock invoice in $scope
        $scope.vm.invoice = mockInvoice;
      });

      it('should update a valid invoice', inject(function (InvoicesService) {
        // Set PUT response
        $httpBackend.expectPUT(/api\/invoices\/([0-9a-fA-F]{24})$/).respond();

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test Notification success was called
        expect(Notification.success).toHaveBeenCalledWith({ message: ' Draft saved successfully!' });
        // Test URL location to new object
        expect($state.go).toHaveBeenCalledWith('admin.drafts.list');
      }));

      it('should  call Notification.error if error', inject(function (InvoicesService) {
        var errorMessage = 'error';
        $httpBackend.expectPUT(/api\/invoices\/([0-9a-fA-F]{24})$/).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect(Notification.error).toHaveBeenCalledWith({ message: errorMessage, title: ' Invoice save error!' });
      }));
    });

    describe('vm.remove()', function () {
      beforeEach(function () {
        // Setup invoices
        $scope.vm.invoice = mockInvoice;
      });

      it('should delete the invoice and redirect to invoices', function () {
        // Return true on confirm message
        spyOn(window, 'confirm').and.returnValue(true);

        $httpBackend.expectDELETE(/api\/invoices\/([0-9a-fA-F]{24})$/).respond(204);

        $scope.vm.remove();
        $httpBackend.flush();

        expect(Notification.success).toHaveBeenCalledWith({ message: ' Invoice deleted successfully!' });
        expect($state.go).toHaveBeenCalledWith('admin.invoices.list');
      });

      it('should should not delete the invoice and not redirect', function () {
        // Return false on confirm message
        spyOn(window, 'confirm').and.returnValue(false);

        $scope.vm.remove();

        expect($state.go).not.toHaveBeenCalled();
      });
    });
  });
}());
<commit_msg>tests<commit_after>(function () {
  'use strict';

  describe('Invoices Admin Controller Tests', function () {
    // Initialize global variables
    var InvoicesAdminController,
      $scope,
      $httpBackend,
      $state,
      Authentication,
      InvoicesService,
      mockInvoice,
      Notification;

    // The $resource service augments the response object with methods for updating and deleting the resource.
    // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
    // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
    // When the toEqualData matcher compares two objects, it takes only object properties into
    // account and ignores methods.
    beforeEach(function () {
      jasmine.addMatchers({
        toEqualData: function (util, customEqualityTesters) {
          return {
            compare: function (actual, expected) {
              return {
                pass: angular.equals(actual, expected)
              };
            }
          };
        }
      });
    });

    // Then we can start by loading the main application module
    beforeEach(module(ApplicationConfiguration.applicationModuleName));

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service.
    beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _InvoicesService_, _Notification_) {
      // Set a new global scope
      $scope = $rootScope.$new();

      // Point global variables to injected services
      $httpBackend = _$httpBackend_;
      $state = _$state_;
      Authentication = _Authentication_;
      InvoicesService = _InvoicesService_;
      Notification = _Notification_;

      // Ignore parent template get on state transitions
      $httpBackend.whenGET('/modules/core/client/views/home.client.view.html').respond(200, '');

      // create mock invoice
      mockInvoice = new InvoicesService({
        _id: '525a8422f6d0f87f0e407a33',
        title: 'An Invoice about MEAN',
        content: 'MEAN rocks!'
      });

      // Mock logged in user
      Authentication.user = {
        roles: ['user']
      };

      // Initialize the Invoices controller.
      InvoicesAdminController = $controller('InvoicesAdminController as vm', {
        $scope: $scope,
        invoiceResolve: {}
      });

      // Spy on state go
      spyOn($state, 'go');
      spyOn(Notification, 'error');
      spyOn(Notification, 'success');
    }));

    describe('vm.save() as create', function () {
      var sampleInvoicePostData;

      beforeEach(function () {
        // Create a sample invoice object
        sampleInvoicePostData = new InvoicesService({
          title: 'An Invoice about MEAN',
          content: 'MEAN rocks!'
        });

        $scope.vm.invoice = sampleInvoicePostData;
      });

      it('should send a POST request with the form input values and then locate to new object URL', inject(function (InvoicesService) {
        // Set POST response
        $httpBackend.expectPOST('/api/invoices', sampleInvoicePostData).respond(mockInvoice);

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test Notification success was called
        expect(Notification.success).toHaveBeenCalledWith({ message: ' Draft saved successfully!' });
        // Test URL redirection after the invoice was created
        expect($state.go).toHaveBeenCalledWith('admin.invoices.list');
      }));

      it('should call Notification.error if error', function () {
        var errorMessage = 'this is an error message';
        $httpBackend.expectPOST('/api/invoices', sampleInvoicePostData).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect(Notification.error).toHaveBeenCalledWith({ message: errorMessage, title: ' Invoice save error!' });
      });
    });

    describe('vm.save() as update', function () {
      beforeEach(function () {
        // Mock invoice in $scope
        $scope.vm.invoice = mockInvoice;
      });

      it('should update a valid invoice', inject(function (InvoicesService) {
        // Set PUT response
        $httpBackend.expectPUT(/api\/invoices\/([0-9a-fA-F]{24})$/).respond();

        // Run controller functionality
        $scope.vm.save(true);
        $httpBackend.flush();

        // Test Notification success was called
        expect(Notification.success).toHaveBeenCalledWith({ message: ' Draft saved successfully!' });
        // Test URL location to new object
        expect($state.go).toHaveBeenCalledWith('admin.drafts.list');
      }));

      it('should  call Notification.error if error', inject(function (InvoicesService) {
        var errorMessage = 'error';
        $httpBackend.expectPUT(/api\/invoices\/([0-9a-fA-F]{24})$/).respond(400, {
          message: errorMessage
        });

        $scope.vm.save(true);
        $httpBackend.flush();

        expect(Notification.error).toHaveBeenCalledWith({ message: errorMessage, title: ' Invoice save error!' });
      }));
    });

    describe('vm.remove()', function () {
      beforeEach(function () {
        // Setup invoices
        $scope.vm.invoice = mockInvoice;
      });

      it('should delete the invoice and redirect to invoices', function () {
        // Return true on confirm message
        spyOn(window, 'confirm').and.returnValue(true);

        $httpBackend.expectDELETE(/api\/invoices\/([0-9a-fA-F]{24})$/).respond(204);

        $scope.vm.remove();
        $httpBackend.flush();

        expect(Notification.success).toHaveBeenCalledWith({ message: ' Invoice deleted successfully!' });
        expect($state.go).toHaveBeenCalledWith('admin.invoices.list');
      });

      it('should should not delete the invoice and not redirect', function () {
        // Return false on confirm message
        spyOn(window, 'confirm').and.returnValue(false);

        $scope.vm.remove();

        expect($state.go).not.toHaveBeenCalled();
      });
    });
  });
}());
<|endoftext|>