<commit_before>var assert = require('assert');
var extract = require('../lib/extract');

describe("extract", function() {
    it("should work with concatenated strings", function() {
        assert.deepEqual(
            extract("gettext('foo' + 'bar');"),
            [{
                method: 'gettext',
                params: {message: 'foobar'}
            }]);
    });

    it("should work with array joined strings", function() {
        assert.deepEqual(
            extract("gettext(['foo', 'bar'].join(' '));"),
            [{
                method: 'gettext',
                params: {message: 'foo bar'}
            }]);
    });

    describe("gettext", function() {
        it("should extract member calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                    "    this.gettext('foo');",
                    "    thing.gettext('bar');",
                    "    thing.gettext.call(null, 'baz');",
                    "    thing.gettext.apply(null, ['qux']);",
                    "    thing.subthing.gettext('corge');",
                    "    thing.subthing.gettext.call(null, 'grault');",
                    "    thing.subthing.gettext.apply(null, ['garply']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }, {
                    method: 'gettext',
                    params: {message: 'baz'}
                }, {
                    method: 'gettext',
                    params: {message: 'qux'}
                }, {
                    method: 'gettext',
                    params: {message: 'corge'}
                }, {
                    method: 'gettext',
                    params: {message: 'grault'}
                }, {
                    method: 'gettext',
                    params: {message: 'garply'}
                }]);
        });

        it("should extract direct calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext('foo');",
                        "gettext('bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.call' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.call(null, 'foo');",
                        "gettext.call(null, 'bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.apply' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.apply(null, ['foo']);",
                        "gettext.apply(null, ['bar']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });
    });

    describe("gettext.gettext", function() {
        it("should extract member calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                    "    this.gettext.gettext('foo');",
                    "    thing.gettext.gettext('bar');",
                    "    thing.gettext.gettext.call(null, 'baz');",
                    "    thing.gettext.gettext.apply(null, ['qux']);",
                    "    thing.subthing.gettext.gettext('corge');",
                    "    thing.subthing.gettext.gettext.call(null, 'grault');",
                    "    thing.subthing.gettext.gettext.apply(null, ['garply']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }, {
                    method: 'gettext',
                    params: {message: 'baz'}
                }, {
                    method: 'gettext',
                    params: {message: 'qux'}
                }, {
                    method: 'gettext',
                    params: {message: 'corge'}
                }, {
                    method: 'gettext',
                    params: {message: 'grault'}
                }, {
                    method: 'gettext',
                    params: {message: 'garply'}
                }]);
        });

        it("should extract direct calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext('foo');",
                        "gettext.gettext('bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.call' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext.call(null, 'foo');",
                        "gettext.gettext.call(null, 'bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.apply' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext.apply(null, ['foo']);",
                        "gettext.gettext.apply(null, ['bar']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });
    });
});
<commit_msg>Add a test for checking that optional keywords can be used<commit_after>var assert = require('assert');
var extract = require('../lib/extract');

describe("extract", function() {
    it("should work with concatenated strings", function() {
        assert.deepEqual(
            extract("gettext('foo' + 'bar');"),
            [{
                method: 'gettext',
                params: {message: 'foobar'}
            }]);
    });

    it("should work with array joined strings", function() {
        assert.deepEqual(
            extract("gettext(['foo', 'bar'].join(' '));"),
            [{
                method: 'gettext',
                params: {message: 'foo bar'}
            }]);
    });

    it("should allow a different keyword to be used", function() {
        assert.deepEqual(
            extract([
                "function luke() {",
                "    _('foo');",
                "    _.gettext('bar');",
                "    thing._('baz');",
                "    thing.subthing._('qux');",
                "    thing.subthing._.gettext('corge');",
                "}"
            ].join('\n'),
            {keyword: '_'}),
            [{
                method: 'gettext',
                params: {message: 'foo'}
            }, {
                method: 'gettext',
                params: {message: 'bar'}
            }, {
                method: 'gettext',
                params: {message: 'baz'}
            }, {
                method: 'gettext',
                params: {message: 'qux'}
            }, {
                method: 'gettext',
                params: {message: 'corge'}
            }]);
    });

    describe("gettext", function() {
        it("should extract member calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                    "    this.gettext('foo');",
                    "    thing.gettext('bar');",
                    "    thing.gettext.call(null, 'baz');",
                    "    thing.gettext.apply(null, ['qux']);",
                    "    thing.subthing.gettext('corge');",
                    "    thing.subthing.gettext.call(null, 'grault');",
                    "    thing.subthing.gettext.apply(null, ['garply']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }, {
                    method: 'gettext',
                    params: {message: 'baz'}
                }, {
                    method: 'gettext',
                    params: {message: 'qux'}
                }, {
                    method: 'gettext',
                    params: {message: 'corge'}
                }, {
                    method: 'gettext',
                    params: {message: 'grault'}
                }, {
                    method: 'gettext',
                    params: {message: 'garply'}
                }]);
        });

        it("should extract direct calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext('foo');",
                        "gettext('bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.call' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.call(null, 'foo');",
                        "gettext.call(null, 'bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.apply' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.apply(null, ['foo']);",
                        "gettext.apply(null, ['bar']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });
    });

    describe("gettext.gettext", function() {
        it("should extract member calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                    "    this.gettext.gettext('foo');",
                    "    thing.gettext.gettext('bar');",
                    "    thing.gettext.gettext.call(null, 'baz');",
                    "    thing.gettext.gettext.apply(null, ['qux']);",
                    "    thing.subthing.gettext.gettext('corge');",
                    "    thing.subthing.gettext.gettext.call(null, 'grault');",
                    "    thing.subthing.gettext.gettext.apply(null, ['garply']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }, {
                    method: 'gettext',
                    params: {message: 'baz'}
                }, {
                    method: 'gettext',
                    params: {message: 'qux'}
                }, {
                    method: 'gettext',
                    params: {message: 'corge'}
                }, {
                    method: 'gettext',
                    params: {message: 'grault'}
                }, {
                    method: 'gettext',
                    params: {message: 'garply'}
                }]);
        });

        it("should extract direct calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext('foo');",
                        "gettext.gettext('bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.call' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext.call(null, 'foo');",
                        "gettext.gettext.call(null, 'bar');",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });

        it("should extract '.apply' calls", function() {
            assert.deepEqual(
                extract([
                    "function luke() {",
                        "gettext.gettext.apply(null, ['foo']);",
                        "gettext.gettext.apply(null, ['bar']);",
                    "}"
                ].join('\n')),
                [{
                    method: 'gettext',
                    params: {message: 'foo'}
                }, {
                    method: 'gettext',
                    params: {message: 'bar'}
                }]);
        });
    });
});
<|endoftext|>


<commit_before>var
  npg = require('node-pre-gyp'),
  path = require('path'),
  gi = require(npg.find(
    path.resolve(path.join(__dirname, 'package.json')))
  )
;

exports.importNS = function(name, version) {
    return gi.importNS(name, version);
};

exports.startLoop = function() {
    gi.startLoop();
};
<commit_msg>spaces<commit_after>var
  npg = require('node-pre-gyp'),
  path = require('path'),
  gi = require(npg.find(
    path.resolve(path.join(__dirname, 'package.json')))
  )
;

exports.importNS = function(name, version) {
  return gi.importNS(name, version);
};

exports.startLoop = function() {
  gi.startLoop();
};
<|endoftext|>


<commit_before>/**
 * Copyright 2017 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
  var fs = require('fs'),
    temp = require('temp');

  var hummus = require('hummus');
  var _ = require('lodash');
  var extractText = require('./lib/text-extraction');

  temp.track();

  function verifyPayload(msg) {
    if (!msg.payload) {
      return Promise.reject('Missing property: msg.payload');
    } else if (msg.payload instanceof Buffer) {
            return Promise.resolve();
    } else {
      return Promise.reject('msg.payload should be pdf buffer');
    }
  }

  function openTheFile() {
    var p = new Promise(function resolver(resolve, reject){
      temp.open({
        suffix: '.pdf'
      }, function(err, info) {
        if (err) {
          reject('Error receiving the data buffer');
        } else {
          resolve(info);
        }
      });
    });
    return p;
  }

  function syncTheFile(info, msg) {
    var p = new Promise(function resolver(resolve, reject){
      fs.writeFile(info.path, msg.payload, function(err) {
        if (err) {
          reject('Error processing pdf buffer');
        }
        resolve();
      });
    });
    return p;
  }

  function createStream(info) {
    var theStream = hummus.createReader(info.path);
    return Promise.resolve(theStream);
  }

  function processPDF(theStream) {
    var p = new Promise(function resolver(resolve, reject) {
      var pagesPlacements = extractText(theStream);
      resolve(pagesPlacements);
    });
    return p;
  }

  function createResponse(msg, pages) {
    var p = new Promise(function resolver(resolve, reject) {
      msg.payload = pages;
      reject('nothing yet implemented');
    });
    return p;
  }

  function doSomething() {
    var p = new Promise(function resolver(resolve, reject) {
      reject('nothing yet implemented');
    });
    return p;
  }

  function reportError(node, msg, err) {
    var messageTxt = err;
    //if (err.code && 'ENOENT' === err.code) {
    //  messageTxt = 'Invalid File Path';
    //}
    if (err.error) {
      messageTxt = err.error;
    } else if (err.description) {
      messageTxt = err.description;
    } else if (err.message) {
      messageTxt = err.message;
    }
    node.status({
      fill: 'red',
      shape: 'dot',
      text: messageTxt
    });

    msg.result = {};
    msg.result['error'] = err;
    node.error(messageTxt, msg);
  }

  function Node(config) {
    var node = this;
    RED.nodes.createNode(this, config);

    this.on('input', function(msg) {
      //var message = '';
      node.status({
        fill: 'blue',
        shape: 'dot',
        text: 'loading file'
      });

      var fileInfo = null;

      verifyPayload(msg)
        .then(function() {
          return openTheFile();
        })
        .then(function(info){
          fileInfo = info;
          return syncTheFile(fileInfo, msg);
        })
        .then(function(){
          return createStream(fileInfo);
        })
        .then(function(theStream){
          return processPDF(theStream);
        })
        .then(function(pages){
          return createResponse(msg, pages);
        })
        .then(function() {
          temp.cleanup();
          node.status({});
          node.send(msg);
        })
        .catch(function(err) {
          temp.cleanup();
          reportError(node,msg,err);
          node.send(msg);
        });

    });
  }

  RED.nodes.registerType('pdf-hummus', Node, {
    credentials: {
      token: {
        type: 'text'
      }
    }
  });
};
<commit_msg>Raw working version<commit_after>/**
 * Copyright 2017 IBM Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

module.exports = function(RED) {
  var fs = require('fs'),
    temp = require('temp');

  var hummus = require('hummus');
  var _ = require('lodash');
  var extractText = require('./lib/text-extraction');

  temp.track();

  function verifyPayload(msg) {
    if (!msg.payload) {
      return Promise.reject('Missing property: msg.payload');
    } else if (msg.payload instanceof Buffer) {
            return Promise.resolve();
    } else {
      return Promise.reject('msg.payload should be pdf buffer');
    }
  }

  function openTheFile() {
    var p = new Promise(function resolver(resolve, reject){
      temp.open({
        suffix: '.pdf'
      }, function(err, info) {
        if (err) {
          reject('Error receiving the data buffer');
        } else {
          resolve(info);
        }
      });
    });
    return p;
  }

  function syncTheFile(info, msg) {
    var p = new Promise(function resolver(resolve, reject){
      fs.writeFile(info.path, msg.payload, function(err) {
        if (err) {
          reject('Error processing pdf buffer');
        }
        resolve();
      });
    });
    return p;
  }

  function createStream(info) {
    var theStream = hummus.createReader(info.path);
    return Promise.resolve(theStream);
  }

  function processPDF(theStream) {
    var p = new Promise(function resolver(resolve, reject) {
      var pagesPlacements = extractText(theStream);
      resolve(pagesPlacements);
    });
    return p;
  }

  function createResponse(msg, pages) {
    var p = new Promise(function resolver(resolve, reject) {
      msg.payload = pages;
      resolve();
    });
    return p;
  }

  function doSomething() {
    var p = new Promise(function resolver(resolve, reject) {
      reject('nothing yet implemented');
    });
    return p;
  }

  function reportError(node, msg, err) {
    var messageTxt = err;
    //if (err.code && 'ENOENT' === err.code) {
    //  messageTxt = 'Invalid File Path';
    //}
    if (err.error) {
      messageTxt = err.error;
    } else if (err.description) {
      messageTxt = err.description;
    } else if (err.message) {
      messageTxt = err.message;
    }
    node.status({
      fill: 'red',
      shape: 'dot',
      text: messageTxt
    });

    msg.result = {};
    msg.result['error'] = err;
    node.error(messageTxt, msg);
  }

  function Node(config) {
    var node = this;
    RED.nodes.createNode(this, config);

    this.on('input', function(msg) {
      //var message = '';
      node.status({
        fill: 'blue',
        shape: 'dot',
        text: 'loading file'
      });

      var fileInfo = null;

      verifyPayload(msg)
        .then(function() {
          return openTheFile();
        })
        .then(function(info){
          fileInfo = info;
          return syncTheFile(fileInfo, msg);
        })
        .then(function(){
          return createStream(fileInfo);
        })
        .then(function(theStream){
          return processPDF(theStream);
        })
        .then(function(pages){
          return createResponse(msg, pages);
        })
        .then(function() {
          temp.cleanup();
          node.status({});
          node.send(msg);
        })
        .catch(function(err) {
          temp.cleanup();
          reportError(node,msg,err);
          node.send(msg);
        });

    });
  }

  RED.nodes.registerType('pdf-hummus', Node, {
    credentials: {
      token: {
        type: 'text'
      }
    }
  });
};
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function () {
  var experienceFormGroup = document.getElementById('experience-form-group')
  var experience = document.getElementById('experience')
  var message = document.getElementById('experienceMessage')
  experience.onkeyup = function() {
    if (experience.value.length < 501) {
      if (experience.classList.contains('form-control-warning') && experienceFormGroup.classList.contains('form-control-warning')) {
        experience.classList.remove('form-control-warning')
        experienceFormGroup.classList.remove('has-warning')
      }
      if (!experience.classList.contains('form-control-success') && !experienceFormGroup.classList.contains('form-control-success')) {
        experience.classList.add('form-control-success')
        experienceFormGroup.classList.add('has-success')
      }
      message.textContent = 'Characters remaining: ' + (500 - experience.value.length)
    } else {
      if (experience.classList.contains('form-control-success') && experienceFormGroup.classList.contains('form-control-success')) {
        experience.classList.remove('form-control-success')
        experienceFormGroup.classList.remove('has-success')
      }
      if (!experience.classList.contains('form-control-warning') && !experienceFormGroup.classList.contains('form-control-warning')) {
        experience.classList.add('form-control-warning')
        experienceFormGroup.classList.add('has-warning')
      }
      message.textContent = 'Too much information'
    }
  }
})
<commit_msg>Fix expLengthCheck bug<commit_after>document.addEventListener('DOMContentLoaded', function () {
  var experienceFormGroup = document.getElementById('experience-form-group')
  var experience = document.getElementById('experience')
  var message = document.getElementById('experienceMessage')
  experience.onkeyup = function() {
    if (experience.value.length < 501) {
      if (experience.classList.contains('form-control-warning') && experienceFormGroup.classList.contains('has-warning')) {
        experience.classList.remove('form-control-warning')
        experienceFormGroup.classList.remove('has-warning')
      }
      if (!experience.classList.contains('form-control-success') && !experienceFormGroup.classList.contains('has-success')) {
        experience.classList.add('form-control-success')
        experienceFormGroup.classList.add('has-success')
      }
      message.textContent = 'Characters remaining: ' + (500 - experience.value.length)
    } else {
      if (experience.classList.contains('form-control-success') && experienceFormGroup.classList.contains('has-success')) {
        experience.classList.remove('form-control-success')
        experienceFormGroup.classList.remove('has-success')
      }
      if (!experience.classList.contains('form-control-warning') && !experienceFormGroup.classList.contains('has-warning')) {
        experience.classList.add('form-control-warning')
        experienceFormGroup.classList.add('has-warning')
      }
      message.textContent = 'Too much information'
    }
  }
})
<|endoftext|>


<commit_before>// global angular
(function(angular) {

  'use strict';

  angular.module(APP_NAME).controller('gamesPlayCtrl', gamesPlayCtrl);

  gamesPlayCtrl.$inject = ['$filter', '$state', '$stateParams', '$mdDialog', 'gamesService', 'dialogService'];

  function gamesPlayCtrl($filter, $state, $stateParams, $mdDialog, gamesService, dialogService) {

    var vm = this;

    vm.getGame = function(id) {
      vm.game = gamesService.api(id).get(function() {
        if (!vm.game.inProgress) {
          vm.game.startTime = Date.now(),
            vm.game.inProgress = true;
          vm.game.$save();
        }
      });
    }

    vm.playerOut = function(attendee) {
      var idx = getNextRankOut();
      attendee.score = getScore(idx);
      attendee.cashedOutTime = Date.now();
      attendee.rank = idx + 1;
      vm.game.$save();
    }

    vm.playerBackIn = function(attendee) {
      var rankedPlayers = $filter('filter')(vm.game.players, function(player) {
        return player.rank < attendee.rank;
      });
      zeroOutAttendee(attendee);
      adjustAttendeeScores(rankedPlayers);
      vm.game.$save();
    }

    vm.finalTable = function() {
      var nextRankOut = getNextRankOut() + 1;
      var message;
      if (nextRankOut > 8) {
        message = `You have more than 8 players remaining. Do you want to
        just select members of the final table?`
        return dialogService.confirm(message).then(() => {
          $state.go('games.ft', {
            id: vm.game._id
          })
        })
      }
      message = `Are you sure you want to start the final table? Players
      cannot buy back in but you will be able to edit the final standings later.`
      dialogService.confirm(message).then(() => {
        vm.game.finalTable = true;
        vm.game.$save();
      })

    }

    vm.finalizeGame = function() {
      var message = `Are you sure you want to finalize the game? The next screen
      will allow you to edit standings if there was a mistake or press complete
      to finish.`
      dialogService.confirm(message).then(() => {
        vm.game.finalize = true;
      })
    }

    vm.checkScore = function(player) {
      var oldRank = getRank(player.score);

      if (!player.rank && player.rank !== 0) {
        return false;
      }
      if (player.rank > 8 || player.rank < 1) {
        player.rank = oldRank;
        return false;
      }
      if (player.rank > vm.game.players.length) {
        player.rank = vm.game.players.length;
      }
      var newScore = getScore(player.rank - 1);
      var counterPart = $filter('filter')(vm.game.players, {
        score: newScore
      })[0];
      counterPart.rank = oldRank;
      counterPart.score = getScore(oldRank - 1);
      player.score = newScore;
    }

    vm.noBlankAllowed = function(player) {
      if (!player.rank) {
        player.rank = getRank(player.score);
      }
    }

    vm.completeGame = function() {
      if (!vm.game.finalize) {
        return false;
      }
      var message = `Game will be marked complete and scores cannot be changed.
      Scores will be submitted to season standings.`
      dialogService.confirm(message).then(() => {
        vm.game.completed = true;
        vm.game.$save();
      })
    }

    vm.isFinalizeable = function() {
      return getNextRankOut() < 0;
    }

    function getNextRankOut() {

      var unscoredPlayers = $filter('filter')(vm.game.players, {
        score: 1
      }, function(a, e) {
        return a < e || a === undefined;
      })
      return unscoredPlayers.length - 1;
    }

    function getScore(idx) {
      if (idx === 0) {
        return 10;
      } else if (idx < 8) {
        return 9 - idx;
      } else {
        return 1;
      }
    }

    function getRank(score) {
      if (score == 10) {
        return 1;
      } else if (score > 1 && score < 9) {
        return 10 - score;
      } else {
        return 9;
      }
    }

    function zeroOutAttendee(attendee) {
      delete attendee.score;
      delete attendee.cashedOutTime;
      delete attendee.rank;
    }

    function adjustAttendeeScores(rankedPlayers) {
      angular.forEach(rankedPlayers, function(player) {
        player.score = getScore(player.rank);
        player.rank = player.rank + 1;
      })

    }

    function initialize() {
      vm.getGame($stateParams.id);
    }

    initialize();

  }

})(angular);
<commit_msg>feature/RHP_87-allow-players-to-buy-back-in<commit_after>// global angular
(function(angular) {

  'use strict';

  angular.module(APP_NAME).controller('gamesPlayCtrl', gamesPlayCtrl);

  gamesPlayCtrl.$inject = ['$filter', '$state', '$stateParams', '$mdDialog', 'gamesService', 'dialogService'];

  function gamesPlayCtrl($filter, $state, $stateParams, $mdDialog, gamesService, dialogService) {

    var vm = this;

    vm.getGame = function(id) {
      vm.game = gamesService.api(id).get(function() {
        if (!vm.game.inProgress) {
          vm.game.startTime = Date.now(),
            vm.game.inProgress = true;
          vm.game.$save();
        }
      });
    }

    vm.playerOut = function(attendee) {
      var idx = getNextRankOut();
      attendee.score = getScore(idx);
      attendee.cashedOutTime = Date.now();
      attendee.rank = idx + 1;
      vm.game.$save();
    }

    vm.playerBackIn = function(attendee) {
      var message = `Marking a player back in will adjust all currently ranked
        players and remove this player's score and rank. Is this okay?`
      dialogService.confirm(message).then(() => {
        var rankedPlayers = $filter('filter')(vm.game.players, function(player) {
          return player.rank < attendee.rank;
        });
        zeroOutAttendee(attendee);
        adjustAttendeeScores(rankedPlayers);
        vm.game.$save();
      })
    }

    vm.finalTable = function() {
      var nextRankOut = getNextRankOut() + 1;
      var message;
      if (nextRankOut > 8) {
        message = `You have more than 8 players remaining. Do you want to
        just select members of the final table?`
        return dialogService.confirm(message).then(() => {
          $state.go('games.ft', {
            id: vm.game._id
          })
        })
      }
      message = `Are you sure you want to start the final table? Players
      cannot buy back in but you will be able to edit the final standings later.`
      dialogService.confirm(message).then(() => {
        vm.game.finalTable = true;
        vm.game.$save();
      })

    }

    vm.finalizeGame = function() {
      var message = `Are you sure you want to finalize the game? The next screen
      will allow you to edit standings if there was a mistake or press complete
      to finish.`
      dialogService.confirm(message).then(() => {
        vm.game.finalize = true;
      })
    }

    vm.checkScore = function(player) {
      var oldRank = getRank(player.score);

      if (!player.rank && player.rank !== 0) {
        return false;
      }
      if (player.rank > 8 || player.rank < 1) {
        player.rank = oldRank;
        return false;
      }
      if (player.rank > vm.game.players.length) {
        player.rank = vm.game.players.length;
      }
      var newScore = getScore(player.rank - 1);
      var counterPart = $filter('filter')(vm.game.players, {
        score: newScore
      })[0];
      counterPart.rank = oldRank;
      counterPart.score = getScore(oldRank - 1);
      player.score = newScore;
    }

    vm.noBlankAllowed = function(player) {
      if (!player.rank) {
        player.rank = getRank(player.score);
      }
    }

    vm.completeGame = function() {
      if (!vm.game.finalize) {
        return false;
      }
      var message = `Game will be marked complete and scores cannot be changed.
      Scores will be submitted to season standings.`
      dialogService.confirm(message).then(() => {
        vm.game.completed = true;
        vm.game.$save();
      })
    }

    vm.isFinalizeable = function() {
      return getNextRankOut() < 0;
    }

    function getNextRankOut() {

      var unscoredPlayers = $filter('filter')(vm.game.players, {
        score: 1
      }, function(a, e) {
        return a < e || a === undefined;
      })
      return unscoredPlayers.length - 1;
    }

    function getScore(idx) {
      if (idx === 0) {
        return 10;
      } else if (idx < 8) {
        return 9 - idx;
      } else {
        return 1;
      }
    }

    function getRank(score) {
      if (score == 10) {
        return 1;
      } else if (score > 1 && score < 9) {
        return 10 - score;
      } else {
        return 9;
      }
    }

    function zeroOutAttendee(attendee) {
      delete attendee.score;
      delete attendee.cashedOutTime;
      delete attendee.rank;
    }

    function adjustAttendeeScores(rankedPlayers) {
      angular.forEach(rankedPlayers, function(player) {
        player.score = getScore(player.rank);
        player.rank = player.rank + 1;
      })

    }

    function initialize() {
      vm.getGame($stateParams.id);
    }

    initialize();

  }

})(angular);
<|endoftext|>


<commit_before>var
	vows = require('vows'),
	assert = require('assert'),
	FnQueue = require('../lib/fnqueue');

function returnsArguments(askedResults, exptectedResults) {
	return function (results) {
		assert.deepEqual(FnQueue.prototype.getDependencies.apply(results, [askedResults]), exptectedResults);
	};
}

vows.describe('FnQueue').addBatch({
	'When we require FnQueue': {
		topic: FnQueue.prototype,
		'FnQueue.verbose should be false by default': function (prototype) {
			assert.isFalse(prototype.isVerbose);
		}
	}
}).addBatch({
	'FnQueue.getFunctionArguments should success': {
		'without spaces': function () {
			assert.deepEqual(FnQueue.prototype.getFunctionArguments(function (foo,bar,callback) {}), ['foo', 'bar', 'callback']);
		},
		'with spaces': function () {
			assert.deepEqual(FnQueue.prototype.getFunctionArguments(function ( foo , bar , callback ) { }), ['foo', 'bar', 'callback']);
		},
		'with newline': function () {
			assert.deepEqual(FnQueue.prototype.getFunctionArguments(function (
				foo,
				bar,
				callback
			) {//foo bar
				//foo bar
				var a = 5;
				for(var b = 0; b < 1000; b ++) { }
				if (a == 5) { }
			}), ['foo', 'bar', 'callback']);
		}
	}
}).addBatch({
	'Given an object of results': {
		topic: {
			results: {
				foo1: { result: 'foo1-result' },
				bar1: { result: 'bar1-result' },
				foo2: { result: 'foo2-result' },
				bar2: { result: 'bar2-result' }
			}
		},
		'FnQueue.getDependencies should return': {
			'foo1-result, bar1-result': returnsArguments(['foo1', 'bar1'], ['foo1-result', 'bar1-result']),
			'bar2-result, foo1-result, foo1-result': returnsArguments(['bar2', 'foo1', 'foo1'], ['bar2-result', 'foo1-result', 'foo1-result']),
			'false': returnsArguments(['foo1', 'bar1', 'youShouldNotFindMe'], false),
		},
		'FnQueue.getResults should return': {
			'{ foo1: "foo1-result", bar1: "bar1-result", foo2: "foo2-result", bar2: "bar2-result" }': function (result) {
				assert.deepEqual(FnQueue.prototype.getResults.apply(result), { foo1: "foo1-result", bar1: "bar1-result", foo2: "foo2-result", bar2: "bar2-result" });
			}
		}
	},
	'Given an empty object of results': {
		topic: { results: {} },
		'FnQueue.getDependencies should return': {
			'false for [foo1, bar1]': returnsArguments(['foo1', 'bar1'], false),
			'false for [bar2, foo1]': returnsArguments(['bar2', 'foo1', 'foo1'], false),
			'false for [foo1, bar1, youShouldnotFindMe]': returnsArguments(['foo1', 'bar1', 'youShouldNotFindMe'], false),
		},
		'FnQueue.getResults should return': {
			'{}': function (result) {
				assert.deepEqual(FnQueue.prototype.getResults.apply(result), {});
			}
		}
	},
	'FnQueue.destroy, given a dummy object': {
		topic: { results: {}, callback: {}, tasks: {} },
		'should delete results, callback and tasks properties': function (obj) {
			FnQueue.prototype.destroy.apply(obj);
			assert.isEmpty(obj);
		}
	},
	'FnQueue with an example queue of functions': {
		topic: function () {
			new FnQueue({
				fn1: function (callback) {
					setTimeout(callback.bind(null, null, 'fn1'), 500);
				},
				fn2: function (callback) {
					setTimeout(callback.bind(null, null, 'fn2'), 500);
				},
				fn3: function (callback) {
					setTimeout(callback.bind(null, null, undefined), 500);
				},
				fn4: function (callback) {
					setTimeout(callback.bind(null, null, false), 500);
				}
			}, this.callback);
		},
		'should not return error': function (err, data) {
			assert.isNull(err);
		},
		'data should be an Object': function (err, data) {
			assert.isObject(data);
		},
		'data should contains all the queue results': function (err, data) {
			assert.deepEqual(data,{
				fn1: 'fn1',
				fn2: 'fn2',
				fn3: undefined,
				fn4: false,
			});
		}
	},
	'FnQueue with some error throwing function': {
		topic: function () {
			new FnQueue({
				fn1: function (callback) {
					setTimeout(callback.bind(null, null, 'fn1'), 200);
				},
				fn2: function (callback) {
					setTimeout(callback.bind(null, new Error('This is thrown by fn2'), 'fn2'), 300);
				},
				fn3: function (callback) {
					setTimeout(callback.bind(null, new Error('This is thrown by fn3'), undefined), 200);
				},
				fn4: function (callback) {
					setTimeout(callback.bind(null, null, false), 200);
				}
			}, this.callback);
		},
		'should call the main callback with an error': function (err, data) {
			assert.isNotNull(err);
		},
		'error message should be "This is thrown by fn3"': function (err, data) {
			assert.equal(err.message, 'This is thrown by fn3');
		},
		'data should contains partial results': function (err, data) {
			assert.deepEqual(data, { fn1: 'fn1' });
		}
	}
}).addBatch({
	'FnQueue with unresolvable dependencies': {
		topic: function () {
			new FnQueue({
				fn1: function (fn2, fn4, fn3, callback) {
					setTimeout(callback.bind(null, null, 'fn1'), 100);
				},
				fn2: function (fn4, callback) {
					setTimeout(callback.bind(null, null, 'fn2'), 100);
				},
				fn3: function (fn2, fn1, callback) {
					setTimeout(callback.bind(null, null, undefined), 100);
				},
				fn4: function (callback) {
					setTimeout(callback.bind(null, null, false), 100);
				}
			}, this.callback);
		},
		'should call the main callback with an error': function (err, data) {
			assert.isNotNull(err);
		},
		'error should match the "Unresolvable dependencies..." messgae': function (err, data) {
			assert.match(err.message, /^Unresolvable dependencies/);
		},
		'data should contain partial results': function (err, data) {
			assert.deepEqual(data, { fn4: false, fn2: 'fn2' });
		}
	}
}).addBatch({
	'FnQueue with some dependencies': {
		topic: function () {
			new FnQueue({
				fn1: function (fn2, fn4, fn3, callback) {
					setTimeout(callback.bind(null, null, 'fn1'), 100);
				},
				fn2: function (fn4, callback) {
					setTimeout(callback.bind(null, null, 'fn2'), 100);
				},
				fn3: function (fn2, callback) {
					setTimeout(callback.bind(null, null, undefined), 100);
				},
				fn4: function (callback) {
					setTimeout(callback.bind(null, null, false), 100);
				}
			}, this.callback);
		},
		'should follow dependecies constrains in call sequence': function (err, data) {
			assert.deepEqual(this.callSequence, ['fn4', 'fn2', 'fn3', 'fn1']);
		}
	}
}).addBatch({
	'FnQueue with an example queue of functions and a concurrency level of 2': {
		topic: function () {

			var fnQueue = new FnQueue({
				fn1: function (callback) {
					setTimeout(getCallback(2, callback), 200);
				},
				fn2: function (fn9, callback) {
					setTimeout(getCallback(null, callback), 200);
				},
				fn3: function (fn9, fn8, callback) {
					setTimeout(getCallback(null, callback), 200);
				},
				fn4: function (callback) {
					setTimeout(getCallback(3, callback), 200);
				},
				fn5: function (callback) {
					setTimeout(getCallback(null, callback), 200);
				},
				fn6: function (callback) {
					setTimeout(getCallback(null, callback), 200);
				},
				fn7: function (callback) {
					setTimeout(getCallback(1, callback), 200);
				},
				fn8: function (callback) {
					setTimeout(getCallback(2, callback), 200);
				},
				fn9: function (fn7, fn8, callback) {
					setTimeout(getCallback(null, callback), 200);
				}
			}, this.callback, 1, true);

			fnQueue.concurrencySequence = [];

			function getCallback(concurrecyLevel, callback) {
				return function () {
					concurrecyLevel && (fnQueue.concurrecyLevel = concurrecyLevel);
					fnQueue.concurrencySequence.push(fnQueue.runningNb);
					callback(null, fnQueue.runningNb);
				};
			}

			fnQueue.start();
		},
		'should not return error': function (err, data) {
			assert.isNull(err);
		},
		'max concurrency should follow the expected concurrency sequence': function (err, data) {
			assert.deepEqual(this.concurrencySequence, [ 1, 2, 3, 3, 2, 1, 1, 2, 1 ]);
		},
	},
}).export(module);<commit_msg>tab to spaces in test suite<commit_after>var
  vows = require('vows'),
  assert = require('assert'),
  FnQueue = require('../lib/fnqueue');

function returnsArguments(askedResults, exptectedResults) {
  return function (results) {
    assert.deepEqual(FnQueue.prototype.getDependencies.apply(results, [askedResults]), exptectedResults);
  };
}

vows.describe('FnQueue').addBatch({
  'When we require FnQueue': {
    topic: FnQueue.prototype,
    'FnQueue.verbose should be false by default': function (prototype) {
      assert.isFalse(prototype.isVerbose);
    }
  }
}).addBatch({
  'FnQueue.getFunctionArguments should success': {
    'without spaces': function () {
      assert.deepEqual(FnQueue.prototype.getFunctionArguments(function (foo,bar,callback) {}), ['foo', 'bar', 'callback']);
    },
    'with spaces': function () {
      assert.deepEqual(FnQueue.prototype.getFunctionArguments(function ( foo , bar , callback ) { }), ['foo', 'bar', 'callback']);
    },
    'with newline': function () {
      assert.deepEqual(FnQueue.prototype.getFunctionArguments(function (
        foo,
        bar,
        callback
      ) {//foo bar
        //foo bar
        var a = 5;
        for(var b = 0; b < 1000; b ++) { }
        if (a == 5) { }
      }), ['foo', 'bar', 'callback']);
    }
  }
}).addBatch({
  'Given an object of results': {
    topic: {
      results: {
        foo1: { result: 'foo1-result' },
        bar1: { result: 'bar1-result' },
        foo2: { result: 'foo2-result' },
        bar2: { result: 'bar2-result' }
      }
    },
    'FnQueue.getDependencies should return': {
      'foo1-result, bar1-result': returnsArguments(['foo1', 'bar1'], ['foo1-result', 'bar1-result']),
      'bar2-result, foo1-result, foo1-result': returnsArguments(['bar2', 'foo1', 'foo1'], ['bar2-result', 'foo1-result', 'foo1-result']),
      'false': returnsArguments(['foo1', 'bar1', 'youShouldNotFindMe'], false),
    },
    'FnQueue.getResults should return': {
      '{ foo1: "foo1-result", bar1: "bar1-result", foo2: "foo2-result", bar2: "bar2-result" }': function (result) {
        assert.deepEqual(FnQueue.prototype.getResults.apply(result), { foo1: "foo1-result", bar1: "bar1-result", foo2: "foo2-result", bar2: "bar2-result" });
      }
    }
  },
  'Given an empty object of results': {
    topic: { results: {} },
    'FnQueue.getDependencies should return': {
      'false for [foo1, bar1]': returnsArguments(['foo1', 'bar1'], false),
      'false for [bar2, foo1]': returnsArguments(['bar2', 'foo1', 'foo1'], false),
      'false for [foo1, bar1, youShouldnotFindMe]': returnsArguments(['foo1', 'bar1', 'youShouldNotFindMe'], false),
    },
    'FnQueue.getResults should return': {
      '{}': function (result) {
        assert.deepEqual(FnQueue.prototype.getResults.apply(result), {});
      }
    }
  },
  'FnQueue.destroy, given a dummy object': {
    topic: { results: {}, callback: {}, tasks: {} },
    'should delete results, callback and tasks properties': function (obj) {
      FnQueue.prototype.destroy.apply(obj);
      assert.isEmpty(obj);
    }
  },
  'FnQueue with an example queue of functions': {
    topic: function () {
      new FnQueue({
        fn1: function (callback) {
          setTimeout(callback.bind(null, null, 'fn1'), 500);
        },
        fn2: function (callback) {
          setTimeout(callback.bind(null, null, 'fn2'), 500);
        },
        fn3: function (callback) {
          setTimeout(callback.bind(null, null, undefined), 500);
        },
        fn4: function (callback) {
          setTimeout(callback.bind(null, null, false), 500);
        }
      }, this.callback);
    },
    'should not return error': function (err, data) {
      assert.isNull(err);
    },
    'data should be an Object': function (err, data) {
      assert.isObject(data);
    },
    'data should contains all the queue results': function (err, data) {
      assert.deepEqual(data,{
        fn1: 'fn1',
        fn2: 'fn2',
        fn3: undefined,
        fn4: false,
      });
    }
  },
  'FnQueue with some error throwing function': {
    topic: function () {
      new FnQueue({
        fn1: function (callback) {
          setTimeout(callback.bind(null, null, 'fn1'), 200);
        },
        fn2: function (callback) {
          setTimeout(callback.bind(null, new Error('This is thrown by fn2'), 'fn2'), 300);
        },
        fn3: function (callback) {
          setTimeout(callback.bind(null, new Error('This is thrown by fn3'), undefined), 200);
        },
        fn4: function (callback) {
          setTimeout(callback.bind(null, null, false), 200);
        }
      }, this.callback);
    },
    'should call the main callback with an error': function (err, data) {
      assert.isNotNull(err);
    },
    'error message should be "This is thrown by fn3"': function (err, data) {
      assert.equal(err.message, 'This is thrown by fn3');
    },
    'data should contains partial results': function (err, data) {
      assert.deepEqual(data, { fn1: 'fn1' });
    }
  }
}).addBatch({
  'FnQueue with unresolvable dependencies': {
    topic: function () {
      new FnQueue({
        fn1: function (fn2, fn4, fn3, callback) {
          setTimeout(callback.bind(null, null, 'fn1'), 100);
        },
        fn2: function (fn4, callback) {
          setTimeout(callback.bind(null, null, 'fn2'), 100);
        },
        fn3: function (fn2, fn1, callback) {
          setTimeout(callback.bind(null, null, undefined), 100);
        },
        fn4: function (callback) {
          setTimeout(callback.bind(null, null, false), 100);
        }
      }, this.callback);
    },
    'should call the main callback with an error': function (err, data) {
      assert.isNotNull(err);
    },
    'error should match the "Unresolvable dependencies..." messgae': function (err, data) {
      assert.match(err.message, /^Unresolvable dependencies/);
    },
    'data should contain partial results': function (err, data) {
      assert.deepEqual(data, { fn4: false, fn2: 'fn2' });
    }
  }
}).addBatch({
  'FnQueue with some dependencies': {
    topic: function () {
      new FnQueue({
        fn1: function (fn2, fn4, fn3, callback) {
          setTimeout(callback.bind(null, null, 'fn1'), 100);
        },
        fn2: function (fn4, callback) {
          setTimeout(callback.bind(null, null, 'fn2'), 100);
        },
        fn3: function (fn2, callback) {
          setTimeout(callback.bind(null, null, undefined), 100);
        },
        fn4: function (callback) {
          setTimeout(callback.bind(null, null, false), 100);
        }
      }, this.callback);
    },
    'should follow dependecies constrains in call sequence': function (err, data) {
      assert.deepEqual(this.callSequence, ['fn4', 'fn2', 'fn3', 'fn1']);
    }
  }
}).addBatch({
  'FnQueue with an example queue of functions and a concurrency level of 2': {
    topic: function () {

      var fnQueue = new FnQueue({
        fn1: function (callback) {
          setTimeout(getCallback(2, callback), 200);
        },
        fn2: function (fn9, callback) {
          setTimeout(getCallback(null, callback), 200);
        },
        fn3: function (fn9, fn8, callback) {
          setTimeout(getCallback(null, callback), 200);
        },
        fn4: function (callback) {
          setTimeout(getCallback(3, callback), 200);
        },
        fn5: function (callback) {
          setTimeout(getCallback(null, callback), 200);
        },
        fn6: function (callback) {
          setTimeout(getCallback(null, callback), 200);
        },
        fn7: function (callback) {
          setTimeout(getCallback(1, callback), 200);
        },
        fn8: function (callback) {
          setTimeout(getCallback(2, callback), 200);
        },
        fn9: function (fn7, fn8, callback) {
          setTimeout(getCallback(null, callback), 200);
        }
      }, this.callback, 1, true);

      fnQueue.concurrencySequence = [];

      function getCallback(concurrecyLevel, callback) {
        return function () {
          concurrecyLevel && (fnQueue.concurrecyLevel = concurrecyLevel);
          fnQueue.concurrencySequence.push(fnQueue.runningNb);
          callback(null, fnQueue.runningNb);
        };
      }

      fnQueue.start();
    },
    'should not return error': function (err, data) {
      assert.isNull(err);
    },
    'max concurrency should follow the expected concurrency sequence': function (err, data) {
      assert.deepEqual(this.concurrencySequence, [ 1, 2, 3, 3, 2, 1, 1, 2, 1 ]);
    },
  },
}).export(module);<|endoftext|>


<commit_before>var  mn = document.getElementById("head-nav");
    mns = "head-nav-scrolled";
    hdr = document.getElementsByTagName('header')[0].offsetHeight;
var scrollTop = function() {
  return (window.pageYOffset !== undefined) ? window.pageYOffset :
    (document.documentElement || document.body.parentNode ||
    document.body).scrollTop;}

function arrToString(arr, ct=-1) {
  var s = "";
  if (ct != -1) {
    var truncateAfter = ct;
  } else {
    var truncateAfter = arr.length;
  }
  for (var i = 0; i < truncateAfter; i++) {
      s += arr[i].word;
      s += (i < truncateAfter - 1 ) ? ", ": "";
  }
  return s;
}

window.onscroll = function() {
  if( scrollTop() > hdr ) {
    mn.className = mns;
  } else {
    mn.className = "";
  }
};

appendSlider("#vertical-slide", true);
appendSlider("#horizontal-slide", false,
  [data_start_year - 1, data_end_year - 1]);

d3.select(".vis-no-title")
  .style("min-width", width + $(".vert-slide-wrap").outerWidth(true) + "px");

function startLoad() {
  $("#loader").css("display","block");
}
function endLoad() {
  $("#loader").css("display","none");
}
function updateTopicsSelected(e) {
  startLoad();
  $.ajax({
    type : "GET",
    url : topic_data_link,
    data : {
      json_data : JSON.stringify({'topics' : topics.getKeys()})
    },
    success : function(data) {
      console.log("UPDATE");
      console.log(data);
      $("#topic-titles").html("");
      var output = "";
      $.each(data, function(key, val) {
        output = "TOPIC " + val.key +"";
        $("#topic-titles").append(output);
      });
      if (topics.count > 0) {
        $("#topic-link").addClass("available");
      } else {
        $("#topic-link").removeClass("available").removeClass("active");
      }
      createTopicOverTimeVis(topics.getKeys())
      endLoad();
    },
    error : function(textStatus, errorThrown) {
      console.log(textStatus);
    }
  });
}

function updateTopicsList(search) {
  startLoad();
  $.ajax({
    type : "GET",
    url : all_topic_list_link,
    data : {
      json_data : JSON.stringify({'keywords' : search})
    },
    success : function(data) {
      console.log("UPDATE TOPICS");
      console.log(data);
      $("#corpus-topics").html("");
      var output = "";
      $.each(data, function(key, t) {
        console.log(t.words)
        var cls = "";
        var clr = "transparent";
        if (topics.contains(t.key)){
          cls = "selected";
          clr = topics.getColor(t.key);
        }
        output = "
"
            + ""
              + arrToString(t.words, 5)
            + "" + " "
            + ""
          + "
";
        $("#corpus-topics").append(output);
      });
      endLoad();
    },
    error : function(textStatus, errorThrown) {
      console.log(textStatus);
    }
  });
}

$("nav").on("click", "li:not(.available) a", function(e){ e.preventDefault() });
$("nav").on("click", "li.available:not(.active) a", function(e){
  $(".active").removeClass("active");
  $(this.parentNode).addClass("active");
});

$(".topic-list").on("mouseover", "li:not(.selected)", function(){
  if (tenMode) {
    //$(this).find("i").css("display","block");
    fadeOutRects(this.dataset.topic);
  } else {
    highlightRects(this.dataset.topic);
  }
});

$(".topic-list").on("mouseout", "li:not(.selected)", function(){
  if (tenMode) {
    unfadeOutRects(this.dataset.topic);
  } else {
    unhighlightRects(this.dataset.topic);
  }
});

$(".topic-list").on("click", "li", function(e) {
  var t = this.dataset.topic;
  var add = ! d3.select(this).classed("selected");
  if (add) {
    addTopicToSelected(this, t);
    updateTopicsSelected(e);
  } else {
    removeTopicFromSelected(this,t);
    updateTopicsSelected(e);
  }
});

$("#clear-selected").on("click", function(e) {
  clearSelected();
  updateTopicsSelected(e);
});
$(".view-ten").click(function(e) {
  switchMode();
});

$(".view-all").click(function(e) {
  switchMode();
});

$("[name='keyword']").keydown(function(e){
  if ((e.keyCode || e.which) == 13){
    updateTopicsList($("[name='keyword']").val());
  }
});
$("[name='submit-search']").click(function(e){
  updateTopicsList($("[name='keyword']").val());
});

d3.selectAll(".topic-list")
  .style('height', function() {
    return d3.select("#corpus-chart").style('height');
  })

d3.selectAll(".topic-sort").on('click', function(){
  d3.select(this.parentNode).select('.sort-menu')
    .style("display", function(){
      return (d3.select(this).style("display") == "none") ? "block" : "none";
    });
})
<commit_msg>search now updates topic ordering across all data<commit_after>var  mn = document.getElementById("head-nav");
    mns = "head-nav-scrolled";
    hdr = document.getElementsByTagName('header')[0].offsetHeight;
var scrollTop = function() {
  return (window.pageYOffset !== undefined) ? window.pageYOffset :
    (document.documentElement || document.body.parentNode ||
    document.body).scrollTop;}

function arrToString(arr, ct=-1) {
  var s = "";
  if (ct != -1) {
    var truncateAfter = ct;
  } else {
    var truncateAfter = arr.length;
  }
  for (var i = 0; i < truncateAfter; i++) {
      s += arr[i].word;
      s += (i < truncateAfter - 1 ) ? ", ": "";
  }
  return s;
}

window.onscroll = function() {
  if( scrollTop() > hdr ) {
    mn.className = mns;
  } else {
    mn.className = "";
  }
};

appendSlider("#vertical-slide", true);
appendSlider("#horizontal-slide", false,
  [data_start_year - 1, data_end_year - 1]);

d3.select(".vis-no-title")
  .style("min-width", width + $(".vert-slide-wrap").outerWidth(true) + "px");

function startLoad() {
  $("#loader").css("display","block");
}
function endLoad() {
  $("#loader").css("display","none");
}
function updateTopicsSelected(e) {
  // startLoad();
  $.ajax({
    type : "GET",
    url : topic_data_link,
    data : {
      json_data : JSON.stringify({'topics' : topics.getKeys()})
    },
    success : function(data) {
      console.log("UPDATE");
      console.log(data);
      $("#topic-titles").html("");
      var output = "";
      $.each(data, function(key, val) {
        output = "TOPIC " + val.key +"";
        $("#topic-titles").append(output);
      });
      if (topics.count > 0) {
        $("#topic-link").addClass("available");
      } else {
        $("#topic-link").removeClass("available").removeClass("active");
      }
      createTopicOverTimeVis(topics.getKeys())
      // endLoad();
    },
    error : function(textStatus, errorThrown) {
      console.log(textStatus);
    }
  });
}

function updateTopicsList(search) {
  startLoad();
  $.ajax({
    type : "GET",
    url : all_topic_list_link,
    data : {
      json_data : JSON.stringify({'keywords' : search})
    },
    success : function(data) {
      console.log("UPDATE TOPICS");
      console.log(data);
      $("#corpus-topics").html("");
      var output = "";
      allTopicList = [];
      allKeys = [];
      $.each(data, function(key, t) {
        allTopicList.push({
          key:t.key,
          desc: arrToString(t.words, 10)
        })
        allKeys.push(t.key);
        var cls = "";
        var clr = "transparent";
        if (topics.contains(t.key)){
          cls = "selected";
          clr = topics.getColor(t.key);
        }
        output = "
"
            + ""
              + arrToString(t.words, 5)
            + "" + " "
            + ""
          + "
";
        $("#corpus-topics").append(output);
      });
      endLoad();
    },
    error : function(textStatus, errorThrown) {
      console.log(textStatus);
    }
  });
}

$("nav").on("click", "li:not(.available) a", function(e){ e.preventDefault() });
$("nav").on("click", "li.available:not(.active) a", function(e){
  $(".active").removeClass("active");
  $(this.parentNode).addClass("active");
});

$(".topic-list").on("mouseover", "li:not(.selected)", function(){
  if (tenMode) {
    //$(this).find("i").css("display","block");
    fadeOutRects(this.dataset.topic);
  } else {
    highlightRects(this.dataset.topic);
  }
});

$(".topic-list").on("mouseout", "li:not(.selected)", function(){
  if (tenMode) {
    unfadeOutRects(this.dataset.topic);
  } else {
    unhighlightRects(this.dataset.topic);
  }
});

$(".topic-list").on("click", "li", function(e) {
  var t = this.dataset.topic;
  var add = ! d3.select(this).classed("selected");
  if (add) {
    addTopicToSelected(this, t);
    updateTopicsSelected(e);
  } else {
    removeTopicFromSelected(this,t);
    updateTopicsSelected(e);
  }
});

$("#clear-selected").on("click", function(e) {
  clearSelected();
  updateTopicsSelected(e);
});
$(".view-ten").click(function(e) {
  switchMode();
});

$(".view-all").click(function(e) {
  switchMode();
});

$("[name='keyword']").keydown(function(e){
  if ((e.keyCode || e.which) == 13){
    updateTopicsList($("[name='keyword']").val());
  }
});
$("[name='submit-search']").click(function(e){
  updateTopicsList($("[name='keyword']").val());
});

d3.selectAll(".topic-list")
  .style('height', function() {
    return d3.select("#corpus-chart").style('height');
  })

d3.selectAll(".topic-sort").on('click', function(){
  d3.select(this.parentNode).select('.sort-menu')
    .style("display", function(){
      return (d3.select(this).style("display") == "none") ? "block" : "none";
    });
})
<|endoftext|>


<commit_before>'use strict';

!function(){
    if(!console){
        console = {
            log: function(){},
            error: function(){}
        }
    }

    var Rimg = function() {
        var hidden = {
            status : 'init',
            observer : null,
            breakpoints : [],
            resizeWait: null,
            resizeDimensions: '',
            disableIntrospection: false
        };

        function parseBreakpoints(value){
            //custom: (once) -small 640w 1x, -retina-small 640w 2x, -medium 1280w 1x, -retina-medium 1280w 2x
            //custom: (per image) data-src="image.jpg"
            if(typeof value === 'string'){
                var breakpoints = value.split(',');
                if(breakpoints.length === 0){
                    //invalid
                    hidden.status = 'error';
                    console.error('Rimg: your breakpoint-definition '+ value +' is invalid, check the documentation.');
                    return null;
                }
                var definition = [];
                var i = 0;
                var il = breakpoints.length;
                while(i<il){
                    var bp = breakpoints[i];
                    var bpDefinition = {
                        src: [],
                        width: -1,
                        height: -1,
                        pixelRatio: [],
                        getSrc: function(value){
                            var ratios = this.pixelRatio.length;
                            if(ratios === 0){
                                hidden.status = 'error';
                                console.error('Rimg: missing a pixelRatio definition, check the documentation.');
                                return '';
                            }else if(ratios === 1){
                                return this.src[0];
                            }else if(ratios === 2){
                                if(value <= 1){
                                    return this.src[0];
                                }else{
                                    return this.src[1];
                                }
                            }else{
                                //determine which pixelRatio matches most closely with current device pixel ratio.
                                var s = 0;
                                var sl = this.pixelRatio.length;
                                while(s<sl){
                                    //possible that pixelRatio is 1.5 or 2.25
                                    if(value == this.pixelRatio[s] || Math.round(value) == this.pixelRatio[s]){
                                        return this.src[s];
                                    }
                                    s++;
                                }
                                //use last reference
                                return this.src[ratios-1];
                            }
                        }
                    };
                    var parts = bp.split(' ');
                    var p = 0;
                    var pl = parts.length;
                    while(p<pl){
                        var part = parts[p];
                        if(part.replace(' ','') === ''){
                            //ignore, empty = typo
                        }else{
                            if(part.match(/^[0-9]{0,4}w/gi) != null){
                                bpDefinition.width = Number(part.substr(0,part.length-1));
                            }else if(part.match(/^[0-9]{0,4}h/gi) != null){
                                bpDefinition.height = Number(part.substr(0,part.length-1));
                            }else if(part.match(/[0-9]{1}x/gi) != null){
                                bpDefinition.pixelRatio.push(Number(part.substr(0,part.length-1)));
                            }else{
                                bpDefinition.src.push(part);
                            }
                        }
                        p++;
                    }

                    //check if already defined (pixelRatio)
                    var d = 0;
                    var dl = definition.length;
                    var found = false;
                    while(d<dl){
                        var def = definition[d];
                        if((def.width === bpDefinition.width  && def.width != -1) || (def.height === bpDefinition.height && def.height != -1)){
                            //a match
                            def.pixelRatio.push(bpDefinition.pixelRatio[0]);
                            def.src.push(bpDefinition.src[0]);
                            found = true;
                            break;
                        }
                        d++;
                    }
                    if(!found){
                        //new breakpoint definition
                        definition.push(bpDefinition);
                    }

                    i++;
                }
                if(definition.length > 0){
                    return definition;
                }else{
                    hidden.status = 'error';
                    console.error('Rimg: your breakpoint-definition misses valid breakpoints, check the documentation.');
                    return null;
                }
            }else{
                //invalid
                hidden.status = 'error';
                console.error('Rimg: your breakpoint-definition is not a String, check the documentation.');
                return null;
            }
        }

        //discover initial settings
        if(typeof RimgBreakpoint !== 'undefined'){
            //validate
            var bpts = parseBreakpoints(RimgBreakpoint);
            if(bpts != null){
                hidden.breakpoints = bpts;
            }
            //TODO put on window also?
            //clean reference
            RimgBreakpoint = undefined;
        }else{
            console.log('(remark) Rimg: no breakpoints defined, check the documentation.');
        }

        function event(type,evt,func,target){
            //add/remote event listeners
            if(target === undefined){
                target = document;
            }
            if(evt === 'resize'){
                target = window;
            }
            if(type == 'add'){
                target.addEventListener(evt,func,false);
            }else{
                target.removeEventListener(evt,func,false);
            }
        }

        function adjust(value){
            //change src property when appropriate
            var ratio = window.devicePixelRatio || 1;
            var data = value.getAttribute('data-src');
            if(data != null){
                //only adjust images with data-src property
                var file = data.substr(0,data.lastIndexOf('.'));
                var extension = data.substr(data.lastIndexOf('.'));
                var size = {x:value.width,y:value.height};
                //firefox presents width/height with 0, so check getComputedStyle if necessary:
                if(value.width == 0){
                    size.x = window.getComputedStyle(value,null).maxWidth;
                    size.x = size.x.replace('px','');
                    size.x = Number(size.x);
                }
                if(value.height == 0){
                    size.y = window.getComputedStyle(value,null).maxHeight;
                    size.y = size.y.replace('px','');
                    size.y = Number(size.y);
                }
                var i = 0;
                var il = hidden.breakpoints.length;
                var breakpoint;
                while(i<il){
                    var bp = hidden.breakpoints[i];
                    var wd = size.x;
                    if(size.x < size.y){
                        wd = size.y;
                    }
                    if(wd <= bp.width){
                        breakpoint = bp;
                        break;
                    }
                    i++;
                }
                if(breakpoint === undefined){
                    //use latest
                    breakpoint = hidden.breakpoints[hidden.breakpoints.length-1];
                }

                if(value.getAttribute('src') != file+breakpoint.getSrc(ratio)+extension){
                    //set the appropriate version of the image
                    value.setAttribute('src',file+breakpoint.getSrc(ratio)+extension);
                }
            }
        }

        function inspect(value){
            //check node itself if it is an image or has children
            if(value.nodeName.toLowerCase() === 'img'){
                adjust(value);
            }else{
                //walk through all node children until you find img files
                var i = 0;
                var il = value.children.length;
                while(i<il){
                    var item = value.children[i];
                    inspect(item);
                    i++;
                }
            }
        }

        function resize(){
            //window is resized, execute checkup, if necessary
            clearInterval(hidden.resizeWait);

            //execute only with different window dimensions (on mobile executed twice!)
            var nw = window.innerWidth+'x'+window.innerHeight;
            if(hidden.resizeDimensions !== nw){
                hidden.resizeDimensions = nw;
                this.execute(document);
            }
        }

        function nodeInserted(e){
            this.execute(e.target);
        }

        return {
            version: '0.4.1',
            execute: function(target){
                //only possible when DOM is loaded and no errors appeared
                if(hidden.status === 'error'){
                    console.error('Rimg.execute(): error-status so no actions can be executed, check your code.');
                    return;
                }else if(target === undefined){
                    console.error('Rimg.execute(): undefined value, check your code to add a valid DOM element to this function.');
                    return;
                }
                if(target.nodeName === '#document'){
                    if(target.childNodes.length > 1){
                        //find html node
                        var html;
                        if(target.childNodes[1].nodeName != 'HTML'){
                            //needed to skip HTML comments which are detected as nodes
                            var i = 0;
                            var il = target.childNodes.length;
                            while(i<il){
                                if(target.childNodes[i].nodeName === 'HTML'){
                                    html = target.childNodes[i];
                                    break;
                                }
                                i++;
                            }
                        }else{
                            //second option is <html>
                            html = target.childNodes[1];
                        }
                        //find body node
                        if(html.childNodes[1].nodeName != 'BODY'){
                            var i = 0;
                            var il = html.childNodes.length;
                            while(i<il){
                                if(html.childNodes[i].nodeName === 'BODY'){
                                    inspect(html.childNodes[i]);
                                    break;
                                }
                                i++;
                            }
                        }else{
                            //second option is <body>
                            inspect(html.childNodes[1]);
                        }
                    }else{
                        console.error('Rimg.execute(): not a valid DOM representation, check your code.');
                    }
                }else{
                    if(target != undefined && target.nodeName != undefined && target.nodeName.toLowerCase() === 'img'){
                        //direct reference
                        inspect(target);
                    }else if(target[0] != undefined && target[0].nodeName.toLowerCase() === 'img'){
                        //child reference (after add)
                        inspect(target[0]);
                    }else{
                        //no <img> element found
                    }
                }
            },
            configure: function(value){
                var breakpoints = parseBreakpoints(value);
                if(breakpoints != null){
                    hidden.breakpoints = breakpoints;
                }

                if(hidden.status === 'ready' && !hidden.disableIntrospection){
                    //if DOM loaded, execute right away
                    this.execute(document);
                }
            },
            resized: function(e){
                if(hidden.status != 'ready'){
                    //not available anymore
                    return;
                }

                //cleanup
                if(hidden.resizeWait != null){
                    clearInterval(hidden.resizeWait);
                }
                //wait 100ms to ensure performant and not a blocking script execution
                hidden.resizeWait = setInterval(resize.bind(this),100);
            },
            loaded: function(e){
                if(hidden.status != 'progress'){
                    //not available anymore
                    return;
                }

                //cleanup listener
                event('remove','DOMContentLoaded',this.loaded);

                //initial DOM checkup
                if(!hidden.disableIntrospection){
                    // DOM content loaded
                    if (hidden.observer === null) {
                        //check the whole page before any changes happen
                        this.execute(e.target);
                    }else{
                        hidden.observer.observe(document.body, {
                            attributes: true,
                            childList: true,
                            characterData: true,
                            subtree: true,
                            attributeFilter: ['data-src']
                        });
                        //check full DOM
                        this.execute(document);
                    }

                    //listen for browser resize
                    event('add','resize',this.resized.bind(this));
                }
                hidden.status = 'ready';
            },
            disableIntrospection: function(){
                hidden.disableIntrospection = true;

                //remove mutation listeners
                if(hidden.observer){
                    hidden.observer.disconnect();
                }else{
                    event('remove','DOMNodeInserted',nodeInserted);
                }
            },
            initialize: function(){
                if(hidden.status != 'init'){
                    if(hidden.status != 'error'){
                        console.error('Rimg.initialize(): Already initialized. No forced initialization supported, check your code.');
                    }
                    return;
                }

                //listen for DOM & change events
                var base = this;
                var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
                if (MutationObserver === undefined) {
                    event('add','DOMAttrModified',function(e){
                        //DOM attribute modified, not supported in webkit
                        //TODO Safari 5.0+ MutationObserver support, Chrome 18
                    });
                    //TODO issues with IE9 - http://help.dottoro.com/ljmcxjla.php
                    event('add','DOMNodeInserted',nodeInserted.bind(base));
                    event('add','DOMSubtreeModified',function(e){
                        //TODO nothing?
                        //console.debug('Rimg:','DOM subtree modified',e.target);
                    });
                }else{
                    hidden.observer = new MutationObserver(function(mutations) {
                        mutations.forEach(function(mutation) {
                            if(mutation.addedNodes.length > 0){
                                base.execute(mutation.addedNodes);
                            }else if(mutation.attributeName === 'data-src'){
                                base.execute(mutation.target);
                            }
                        });
                    });
                }
                hidden.status = 'progress';

                // wait until DOM is loaded
                event('add','DOMContentLoaded',this.loaded.bind(this));
            }
        };
    };

    // browser
    window.Rimg = Object.create(Rimg());
    // start listening
    window.Rimg.initialize();
}();<commit_msg>Update rimg.js<commit_after>'use strict';

!function(){
    if(!console){
        console = {
            log: function(){},
            error: function(){}
        }
    }

    var Rimg = function() {
        var hidden = {
            status : 'init',
            observer : null,
            breakpoints : [],
            resizeWait: null,
            resizeDimensions: '',
            disableIntrospection: false
        };

        function parseBreakpoints(value){
            //custom: (once) -small 640w 1x, -retina-small 640w 2x, -medium 1280w 1x, -retina-medium 1280w 2x
            //custom: (per image) data-src="image.jpg"
            if(typeof value === 'string'){
                var breakpoints = value.split(',');
                if(breakpoints.length === 0){
                    //invalid
                    hidden.status = 'error';
                    console.error('Rimg: your breakpoint-definition '+ value +' is invalid, check the documentation.');
                    return null;
                }
                var definition = [];
                var i = 0;
                var il = breakpoints.length;
                while(i<il){
                    var bp = breakpoints[i];
                    var bpDefinition = {
                        src: [],
                        width: -1,
                        height: -1,
                        pixelRatio: [],
                        getSrc: function(value){
                            var ratios = this.pixelRatio.length;
                            if(ratios === 0){
                                hidden.status = 'error';
                                console.error('Rimg: missing a pixelRatio definition, check the documentation.');
                                return '';
                            }else if(ratios === 1){
                                return this.src[0];
                            }else if(ratios === 2){
                                if(value <= 1){
                                    return this.src[0];
                                }else{
                                    return this.src[1];
                                }
                            }else{
                                //determine which pixelRatio matches most closely with current device pixel ratio.
                                var s = 0;
                                var sl = this.pixelRatio.length;
                                while(s<sl){
                                    //possible that pixelRatio is 1.5 or 2.25
                                    if(value === this.pixelRatio[s] || Math.round(value) === this.pixelRatio[s]){
                                        return this.src[s];
                                    }
                                    s++;
                                }
                                //use last reference
                                return this.src[ratios-1];
                            }
                        }
                    };
                    var parts = bp.split(' ');
                    var p = 0;
                    var pl = parts.length;
                    while(p<pl){
                        var part = parts[p];
                        if(part.replace(' ','') === ''){
                            //ignore, empty = typo
                        }else{
                            if(part.match(/^[0-9]{0,4}w/gi) !== null){
                                bpDefinition.width = Number(part.substr(0,part.length-1));
                            }else if(part.match(/^[0-9]{0,4}h/gi) !== null){
                                bpDefinition.height = Number(part.substr(0,part.length-1));
                            }else if(part.match(/[0-9]{1}x/gi) !== null){
                                bpDefinition.pixelRatio.push(Number(part.substr(0,part.length-1)));
                            }else{
                                bpDefinition.src.push(part);
                            }
                        }
                        p++;
                    }

                    //check if already defined (pixelRatio)
                    var d = 0;
                    var dl = definition.length;
                    var found = false;
                    while(d<dl){
                        var def = definition[d];
                        if((def.width === bpDefinition.width  && def.width !== -1) || (def.height === bpDefinition.height && def.height !== -1)){
                            //a match
                            def.pixelRatio.push(bpDefinition.pixelRatio[0]);
                            def.src.push(bpDefinition.src[0]);
                            found = true;
                            break;
                        }
                        d++;
                    }
                    if(!found){
                        //new breakpoint definition
                        definition.push(bpDefinition);
                    }

                    i++;
                }
                if(definition.length > 0){
                    return definition;
                }else{
                    hidden.status = 'error';
                    console.error('Rimg: your breakpoint-definition misses valid breakpoints, check the documentation.');
                    return null;
                }
            }else{
                //invalid
                hidden.status = 'error';
                console.error('Rimg: your breakpoint-definition is not a String, check the documentation.');
                return null;
            }
        }

        //discover initial settings
        if(typeof RimgBreakpoint !== 'undefined'){
            //validate
            var bpts = parseBreakpoints(RimgBreakpoint);
            if(bpts !== null){
                hidden.breakpoints = bpts;
            }
            //TODO put on window also?
            //clean reference
            RimgBreakpoint = undefined;
        }else{
            console.log('(remark) Rimg: no breakpoints defined, check the documentation.');
        }

        function event(type,evt,func,target){
            //add/remote event listeners
            if(target === undefined){
                target = document;
            }
            if(evt === 'resize'){
                target = window;
            }
            if(type === 'add'){
                target.addEventListener(evt,func,false);
            }else{
                target.removeEventListener(evt,func,false);
            }
        }

        function adjust(value){
            //change src property when appropriate
            var ratio = window.devicePixelRatio || 1;
            var data = value.getAttribute('data-src');
            if(data !== null){
                //only adjust images with data-src property
                var file = data.substr(0,data.lastIndexOf('.'));
                var extension = data.substr(data.lastIndexOf('.'));
                var size = {x:value.width,y:value.height};
                //firefox presents width/height with 0, so check getComputedStyle if necessary:
                if(value.width === 0){
                    size.x = window.getComputedStyle(value,null).maxWidth;
                    size.x = size.x.replace('px','');
                    size.x = Number(size.x);
                }
                if(value.height === 0){
                    size.y = window.getComputedStyle(value,null).maxHeight;
                    size.y = size.y.replace('px','');
                    size.y = Number(size.y);
                }
                var i = 0;
                var il = hidden.breakpoints.length;
                var breakpoint;
                while(i<il){
                    var bp = hidden.breakpoints[i];
                    var wd = size.x;
                    if(size.x < size.y){
                        wd = size.y;
                    }
                    if(wd <= bp.width){
                        breakpoint = bp;
                        break;
                    }
                    i++;
                }
                if(breakpoint === undefined){
                    //use latest
                    breakpoint = hidden.breakpoints[hidden.breakpoints.length-1];
                }

                if(value.getAttribute('src') !== file+breakpoint.getSrc(ratio)+extension){
                    //set the appropriate version of the image
                    value.setAttribute('src',file+breakpoint.getSrc(ratio)+extension);
                }
            }
        }

        function inspect(value){
            //check node itself if it is an image or has children
            if(value.nodeName.toLowerCase() === 'img'){
                adjust(value);
            }else{
                //walk through all node children until you find img files
                var i = 0;
                var il = value.children.length;
                while(i<il){
                    var item = value.children[i];
                    inspect(item);
                    i++;
                }
            }
        }

        function resize(){
            //window is resized, execute checkup, if necessary
            clearInterval(hidden.resizeWait);

            //execute only with different window dimensions (on mobile executed twice!)
            var nw = window.innerWidth+'x'+window.innerHeight;
            if(hidden.resizeDimensions !== nw){
                hidden.resizeDimensions = nw;
                this.execute(document);
            }
        }

        function nodeInserted(e){
            this.execute(e.target);
        }

        return {
            version: '0.4.1',
            execute: function(target){
                //only possible when DOM is loaded and no errors appeared
                if(hidden.status === 'error'){
                    console.error('Rimg.execute(): error-status so no actions can be executed, check your code.');
                    return;
                }else if(target === undefined){
                    console.error('Rimg.execute(): undefined value, check your code to add a valid DOM element to this function.');
                    return;
                }
                if(target.nodeName === '#document'){
                    if(target.childNodes.length > 1){
                        //find html node
                        var html;
                        if(target.childNodes[1].nodeName !== 'HTML'){
                            //needed to skip HTML comments which are detected as nodes
                            var i = 0;
                            var il = target.childNodes.length;
                            while(i<il){
                                if(target.childNodes[i].nodeName === 'HTML'){
                                    html = target.childNodes[i];
                                    break;
                                }
                                i++;
                            }
                        }else{
                            //second option is <html>
                            html = target.childNodes[1];
                        }
                        //find body node
                        if(html.childNodes[1].nodeName !== 'BODY'){
                            var i = 0;
                            var il = html.childNodes.length;
                            while(i<il){
                                if(html.childNodes[i].nodeName === 'BODY'){
                                    inspect(html.childNodes[i]);
                                    break;
                                }
                                i++;
                            }
                        }else{
                            //second option is <body>
                            inspect(html.childNodes[1]);
                        }
                    }else{
                        console.error('Rimg.execute(): not a valid DOM representation, check your code.');
                    }
                }else{
                    if(target !== undefined && target.nodeName != undefined && target.nodeName.toLowerCase() === 'img'){
                        //direct reference
                        inspect(target);
                    }else if(target[0] != undefined && target[0].nodeName.toLowerCase() === 'img'){
                        //child reference (after add)
                        inspect(target[0]);
                    }else{
                        //no <img> element found
                    }
                }
            },
            configure: function(value){
                var breakpoints = parseBreakpoints(value);
                if(breakpoints !== null){
                    hidden.breakpoints = breakpoints;
                }

                if(hidden.status === 'ready' && !hidden.disableIntrospection){
                    //if DOM loaded, execute right away
                    this.execute(document);
                }
            },
            resized: function(e){
                if(hidden.status !== 'ready'){
                    //not available anymore
                    return;
                }

                //cleanup
                if(hidden.resizeWait !== null){
                    clearInterval(hidden.resizeWait);
                }
                //wait 100ms to ensure performant and not a blocking script execution
                hidden.resizeWait = setInterval(resize.bind(this),100);
            },
            loaded: function(e){
                if(hidden.status !== 'progress'){
                    //not available anymore
                    return;
                }

                //cleanup listener
                event('remove','DOMContentLoaded',this.loaded);

                //initial DOM checkup
                if(!hidden.disableIntrospection){
                    // DOM content loaded
                    if (hidden.observer === null) {
                        //check the whole page before any changes happen
                        this.execute(e.target);
                    }else{
                        hidden.observer.observe(document.body, {
                            attributes: true,
                            childList: true,
                            characterData: true,
                            subtree: true,
                            attributeFilter: ['data-src']
                        });
                        //check full DOM
                        this.execute(document);
                    }

                    //listen for browser resize
                    event('add','resize',this.resized.bind(this));
                }
                hidden.status = 'ready';
            },
            disableIntrospection: function(){
                hidden.disableIntrospection = true;

                //remove mutation listeners
                if(hidden.observer){
                    hidden.observer.disconnect();
                }else{
                    event('remove','DOMNodeInserted',nodeInserted);
                }
            },
            initialize: function(){
                if(hidden.status !== 'init'){
                    if(hidden.status !== 'error'){
                        console.error('Rimg.initialize(): Already initialized. No forced initialization supported, check your code.');
                    }
                    return;
                }

                //listen for DOM & change events
                var base = this;
                var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
                if (MutationObserver === undefined) {
                    event('add','DOMAttrModified',function(e){
                        //DOM attribute modified, not supported in webkit
                        //TODO Safari 5.0+ MutationObserver support, Chrome 18
                    });
                    //TODO issues with IE9 - http://help.dottoro.com/ljmcxjla.php
                    event('add','DOMNodeInserted',nodeInserted.bind(base));
                    event('add','DOMSubtreeModified',function(e){
                        //TODO nothing?
                        //console.debug('Rimg:','DOM subtree modified',e.target);
                    });
                }else{
                    hidden.observer = new MutationObserver(function(mutations) {
                        mutations.forEach(function(mutation) {
                            if(mutation.addedNodes.length > 0){
                                base.execute(mutation.addedNodes);
                            }else if(mutation.attributeName === 'data-src'){
                                base.execute(mutation.target);
                            }
                        });
                    });
                }
                hidden.status = 'progress';

                // wait until DOM is loaded
                event('add','DOMContentLoaded',this.loaded.bind(this));
            }
        };
    };

    // browser
    window.Rimg = Object.create(Rimg());
    // start listening
    window.Rimg.initialize();
}();
<|endoftext|>