<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('assert');

var expected = [

  // Project files
  '.jshintrc',
  '.editorconfig',
  '.htaccess',

  // Bower
  '.bowerrc',
  'bower.json',

  // Pkg
  'package.json',

  // Git
  '.gitattributes',
  '.gitignore',

  // Travis
  '.travis.yml',

  // Robots
  'robots.txt',

  // HTML
  'templates/header.html',
  'templates/index.html',
  'templates/footer.html',
  'pages.json',

  // Karma
  'karma.conf.js',

  // Humans
  'humans.txt',

  // Grunt
  'Gruntfile.js',
  'tasks/config.js',
  'tasks/options/clean.js',
  'tasks/options/concat.js',
  'tasks/options/connect.js',
  'tasks/options/copy.js',
  'tasks/options/imagemin.js',
  'tasks/options/jshint.js',
  'tasks/options/karma.js',
  'tasks/options/modernizr.js',
  'tasks/options/replace.js',
  'tasks/options/requirejs.js',
  'tasks/options/sass.js',
  'tasks/options/watch.js',

  // Javascript
  'js/modules/module.js',
  'js/plugins/console.js',
  'js/config.js',
  'js/main.js',

  // Authors
  'AUTHORS',

  // Ico
  'apple-touch-icon-precomposed.png',
  'favicon.ico',

  // Contribuiting
  'CONTRIBUTING.md',

  // Cossdomain
  'crossdomain.xml',

  // 404
  '404.html',

  // Test
  'test/specs/example.spec.js',
  'test/spec.js',
  'test/test-main.js'

];

// ---- Main generator
describe('main generator', function () {

  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('the generator can be required without throwing', function () {
    // not testing the actual run of generators yet
    var app = require('../app');
    assert(app !== undefined);
  });

  it('creates expected files for SCSS preprocessor', function (done) {

    helpers.mockPrompt(this.app, {
      'cssPreprocessor': 'Compass'
    });

    var expectedSCSS = [
      'scss/main.scss',
      'scss/elements/_typography.scss',
      'scss/helpers/_helpers.scss',
      'scss/helpers/_variables.scss',
      'scss/media/_print.scss',
      'scss/modules/_box.scss',
      'scss/page/_base.scss',
      'scss/page/_footer.scss',
      'scss/page/_header.scss',
      'scss/page/_main.scss'
    ];

    expectedSCSS.concat(expectedSCSS, expected);

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expectedSCSS);
      done();
    });

  });

  it('creates expected files for LESS preprocessor', function (done) {

    helpers.mockPrompt(this.app, {
      'cssPreprocessor': 'LESS'
    });

    var expectedLESS = [
      'less/main.less',
      'less/elements/_typography.less',
      'less/helpers/_helpers.less',
      'less/helpers/_variables.less',
      'less/media/_print.less',
      'less/modules/_box.less',
      'less/page/_base.less',
      'less/page/_footer.less',
      'less/page/_header.less',
      'less/page/_main.less'
    ];

    expectedLESS.concat(expectedLESS, expected);

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expectedLESS);
      done();
    });

  });

});

// ---- Page sub-generator

describe('page sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:page', [
        '../../page'
      ], ['test-page']);
      done();
    }.bind(this));
  });

  it('creates expected files for the page sub-generator', function (done) {

    var expected = [
      'templates/test-page.html'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});

// ---- Module sub-generator

describe('module sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:module', [
        '../../module'
      ], ['test']);
      done();
    }.bind(this));
  });

  it('creates expected files for the module sub-generator', function (done) {

    var expected = [
      'js/modules/test.js'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});

// ---- Jqueryplugin sub-generator

describe('jqueryplugin sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:jqueryplugin', [
        '../../jqueryplugin'
      ], ['test']);
      done();
    }.bind(this));
  });

  it('creates expected files for the jqueryplugin sub-generator', function (done) {

    var expected = [
      'js/plugins/jquery.test.js'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});
<commit_msg>Add the expected test spec file to the module test.<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = require('assert');

var expected = [

  // Project files
  '.jshintrc',
  '.editorconfig',
  '.htaccess',

  // Bower
  '.bowerrc',
  'bower.json',

  // Pkg
  'package.json',

  // Git
  '.gitattributes',
  '.gitignore',

  // Travis
  '.travis.yml',

  // Robots
  'robots.txt',

  // HTML
  'templates/header.html',
  'templates/index.html',
  'templates/footer.html',
  'pages.json',

  // Karma
  'karma.conf.js',

  // Humans
  'humans.txt',

  // Grunt
  'Gruntfile.js',
  'tasks/config.js',
  'tasks/options/clean.js',
  'tasks/options/concat.js',
  'tasks/options/connect.js',
  'tasks/options/copy.js',
  'tasks/options/imagemin.js',
  'tasks/options/jshint.js',
  'tasks/options/karma.js',
  'tasks/options/modernizr.js',
  'tasks/options/replace.js',
  'tasks/options/requirejs.js',
  'tasks/options/sass.js',
  'tasks/options/watch.js',

  // Javascript
  'js/modules/module.js',
  'js/plugins/console.js',
  'js/config.js',
  'js/main.js',

  // Authors
  'AUTHORS',

  // Ico
  'apple-touch-icon-precomposed.png',
  'favicon.ico',

  // Contribuiting
  'CONTRIBUTING.md',

  // Cossdomain
  'crossdomain.xml',

  // 404
  '404.html',

  // Test
  'test/specs/example.spec.js',
  'test/spec.js',
  'test/test-main.js'

];

// ---- Main generator
describe('main generator', function () {

  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:app', [
        '../../app'
      ]);
      done();
    }.bind(this));
  });

  it('the generator can be required without throwing', function () {
    // not testing the actual run of generators yet
    var app = require('../app');
    assert(app !== undefined);
  });

  it('creates expected files for SCSS preprocessor', function (done) {

    helpers.mockPrompt(this.app, {
      'cssPreprocessor': 'Compass'
    });

    var expectedSCSS = [
      'scss/main.scss',
      'scss/elements/_typography.scss',
      'scss/helpers/_helpers.scss',
      'scss/helpers/_variables.scss',
      'scss/media/_print.scss',
      'scss/modules/_box.scss',
      'scss/page/_base.scss',
      'scss/page/_footer.scss',
      'scss/page/_header.scss',
      'scss/page/_main.scss'
    ];

    expectedSCSS.concat(expectedSCSS, expected);

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expectedSCSS);
      done();
    });

  });

  it('creates expected files for LESS preprocessor', function (done) {

    helpers.mockPrompt(this.app, {
      'cssPreprocessor': 'LESS'
    });

    var expectedLESS = [
      'less/main.less',
      'less/elements/_typography.less',
      'less/helpers/_helpers.less',
      'less/helpers/_variables.less',
      'less/media/_print.less',
      'less/modules/_box.less',
      'less/page/_base.less',
      'less/page/_footer.less',
      'less/page/_header.less',
      'less/page/_main.less'
    ];

    expectedLESS.concat(expectedLESS, expected);

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expectedLESS);
      done();
    });

  });

});

// ---- Page sub-generator

describe('page sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:page', [
        '../../page'
      ], ['test-page']);
      done();
    }.bind(this));
  });

  it('creates expected files for the page sub-generator', function (done) {

    var expected = [
      'templates/test-page.html'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});

// ---- Module sub-generator

describe('module sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:module', [
        '../../module'
      ], ['test']);
      done();
    }.bind(this));
  });

  it('creates expected files for the module sub-generator', function (done) {

    var expected = [
      'js/modules/test.js',
      'test/specs/test.spec.js'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});

// ---- Jqueryplugin sub-generator

describe('jqueryplugin sub-generator', function () {
  beforeEach(function (done) {
    helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
      if (err) {
        return done(err);
      }

      this.app = helpers.createGenerator('init:jqueryplugin', [
        '../../jqueryplugin'
      ], ['test']);
      done();
    }.bind(this));
  });

  it('creates expected files for the jqueryplugin sub-generator', function (done) {

    var expected = [
      'js/plugins/jquery.test.js'
    ];

    this.app.options['skip-install'] = true;
    this.app.run({}, function () {
      helpers.assertFiles(expected);
      done();
    });

  });

});
<|endoftext|>


<commit_before>/*!
 * jScroll - jQuery Plugin for Infinite Scrolling / Auto-Paging
 * @see @link{http://jscroll.com}
 *
 * @copyright 2011-2017, Philip Klauzinski
 * @license Dual licensed under the MIT and GPL Version 2 licenses.
 * @author Philip Klauzinski (http://webtopian.com)
 * @version 2.3.7
 * @requires jQuery v1.4.3+
 * @preserve
 */
(function($) {

    'use strict';

    // Define the jscroll namespace and default settings
    $.jscroll = {
        defaults: {
            debug: true,
            autoTrigger: true,
            autoTriggerUntil: false,
            loadingHtml: 'Loading...',
            loadingFunction: false,
            padding: 0,
            nextSelector: 'a:last',
            contentSelector: '',
            pagingSelector: '',
            callback: false
        }
    };

    // Constructor
    var jScroll = function($e, options) {

        // Private vars and methods
        var _data = $e.data('jscroll'),
            _userOptions = (typeof options === 'function') ? { callback: options } : options,
            _options = $.extend({}, $.jscroll.defaults, _userOptions, _data || {}),
            _isWindow = ($e.css('overflow-y') === 'visible'),
            _$next = $e.find(_options.nextSelector).first(),
            _$window = $(window),
            _$body = $('body'),
            _$scroll = _isWindow ? _$window : $e,
            _nextHref = $.trim(_$next.attr('href') + ' ' + _options.contentSelector),

            // Check if a loading image is defined and preload
            _preloadImage = function() {
                var src = $(_options.loadingHtml).filter('img').attr('src');
                if (src) {
                    var image = new Image();
                    image.src = src;
                }
            },

            // Wrap inner content, if it isn't already
            _wrapInnerContent = function() {
                if (!$e.find('.jscroll-inner').length) {
                    $e.contents().wrapAll('
');
                }
            },

            // Find the next link's parent, or add one, and hide it
            _nextWrap = function($next) {
                var $parent;
                if (_options.pagingSelector) {
                    $next.closest(_options.pagingSelector).hide();
                } else {
                    $parent = $next.parent().not('.jscroll-inner,.jscroll-added').addClass('jscroll-next-parent').hide();
                    if (!$parent.length) {
                        $next.wrap('
').parent().hide();
                    }
                }
            },

            // Remove the jscroll behavior and data from an element
            _destroy = function() {
                return _$scroll.unbind('.jscroll')
                    .removeData('jscroll')
                    .find('.jscroll-inner').children().unwrap()
                    .filter('.jscroll-added').children().unwrap();
            },

            // Observe the scroll event for when to trigger the next load
            _observe = function() {
                if ($e.is(':visible')) {
                    _wrapInnerContent();
                    var $inner = $e.find('div.jscroll-inner').first(),
                        data = $e.data('jscroll'),
                        borderTopWidth = parseInt($e.css('borderTopWidth'), 10),
                        borderTopWidthInt = isNaN(borderTopWidth) ? 0 : borderTopWidth,
                        iContainerTop = parseInt($e.css('paddingTop'), 10) + borderTopWidthInt,
                        iTopHeight = _isWindow ? _$scroll.scrollTop() : $e.offset().top,
                        innerTop = $inner.length ? $inner.offset().top : 0,
                        iTotalHeight = Math.ceil(iTopHeight - innerTop + _$scroll.height() + iContainerTop);

                    if (!data.waiting && iTotalHeight + _options.padding >= $inner.outerHeight()) {
                        //data.nextHref = $.trim(data.nextHref + ' ' + _options.contentSelector);
                        _debug('info', 'jScroll:', $inner.outerHeight() - iTotalHeight, 'from bottom. Loading next request...');
                        return _load();
                    }
                }
            },

            // Check if the href for the next set of content has been set
            _checkNextHref = function(data) {
                data = data || $e.data('jscroll');
                if (!data || !data.nextHref) {
                    _debug('warn', 'jScroll: nextSelector not found - destroying');
                    _destroy();
                    return false;
                } else {
                    _setBindings();
                    return true;
                }
            },

            _setBindings = function() {
                var $next = $e.find(_options.nextSelector).first();
                if (!$next.length) {
                    return;
                }
                if (_options.autoTrigger && (_options.autoTriggerUntil === false || _options.autoTriggerUntil > 0)) {
                    _nextWrap($next);
                     var scrollingBodyHeight = _$body.height() - $e.offset().top,
                    	scrollingHeight = ($e.height() < scrollingBodyHeight) ? $e.height() : scrollingBodyHeight,
                    	windowHeight = ($e.offset().top - _$window.scrollTop() > 0) ? _$window.height() - ($e.offset().top - $(window).scrollTop()) : _$window.height();
                    if (scrollingHeight <= windowHeight) {
                        _observe();
                    }
                    _$scroll.unbind('.jscroll').bind('scroll.jscroll', function() {
                        return _observe();
                    });
                    if (_options.autoTriggerUntil > 0) {
                        _options.autoTriggerUntil--;
                    }
                } else {
                    _$scroll.unbind('.jscroll');
                    $next.bind('click.jscroll', function() {
                        _nextWrap($next);
                        _load();
                        return false;
                    });
                }
            },

            // Load the next set of content, if available
            _load = function() {
                var $inner = $e.find('div.jscroll-inner').first(),
                    data = $e.data('jscroll');

                data.waiting = true;
                $inner.append('
')
                    .children('.jscroll-added').last()
                    .html('
' + _options.loadingHtml + '
')
                    .promise()
                    .done(function(){
                        if (_options.loadingFunction) {
                            _options.loadingFunction();
                        }
                    });

                return $e.animate({scrollTop: $inner.outerHeight()}, 0, function() {
                    var nextHref = data.nextHref;
                    $inner.find('div.jscroll-added').last().load(nextHref, function(r, status) {
                        if (status === 'error') {
                            return _destroy();
                        }
                        var $next = $(this).find(_options.nextSelector).first();
                        data.waiting = false;
                        data.nextHref = $next.attr('href') ? $.trim($next.attr('href') + ' ' + _options.contentSelector) : false;
                        $('.jscroll-next-parent', $e).remove(); // Remove the previous next link now that we have a new one
                        _checkNextHref();
                        if (_options.callback) {
                            _options.callback.call(this, nextHref);
                        }
                        _debug('dir', data);
                    });
                });
            },

            // Safe console debug - http://klauzinski.com/javascript/safe-firebug-console-in-javascript
            _debug = function(m) {
                if (_options.debug && typeof console === 'object' && (typeof m === 'object' || typeof console[m] === 'function')) {
                    if (typeof m === 'object') {
                        var args = [];
                        for (var sMethod in m) {
                            if (typeof console[sMethod] === 'function') {
                                args = (m[sMethod].length) ? m[sMethod] : [m[sMethod]];
                                console[sMethod].apply(console, args);
                            } else {
                                console.log.apply(console, args);
                            }
                        }
                    } else {
                        console[m].apply(console, Array.prototype.slice.call(arguments, 1));
                    }
                }
            };

        // Initialization
        $e.data('jscroll', $.extend({}, _data, {initialized: true, waiting: false, nextHref: _nextHref}));
        _wrapInnerContent();
        _preloadImage();
        _setBindings();

        // Expose API methods via the jQuery.jscroll namespace, e.g. $('sel').jscroll.method()
        $.extend($e.jscroll, {
            destroy: _destroy
        });
        return $e;
    };

    // Define the jscroll plugin method and loop
    $.fn.jscroll = function(m) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('jscroll'), jscroll;

            // Instantiate jScroll on this element if it hasn't been already
            if (data && data.initialized) {
                return;
            }
            jscroll = new jScroll($this, m);
        });
    };

})(jQuery);
<commit_msg>Disabled debug on jscroll<commit_after>/*!
 * jScroll - jQuery Plugin for Infinite Scrolling / Auto-Paging
 * @see @link{http://jscroll.com}
 *
 * @copyright 2011-2017, Philip Klauzinski
 * @license Dual licensed under the MIT and GPL Version 2 licenses.
 * @author Philip Klauzinski (http://webtopian.com)
 * @version 2.3.7
 * @requires jQuery v1.4.3+
 * @preserve
 */
(function($) {

    'use strict';

    // Define the jscroll namespace and default settings
    $.jscroll = {
        defaults: {
            debug: false,
            autoTrigger: true,
            autoTriggerUntil: false,
            loadingHtml: 'Loading...',
            loadingFunction: false,
            padding: 0,
            nextSelector: 'a:last',
            contentSelector: '',
            pagingSelector: '',
            callback: false
        }
    };

    // Constructor
    var jScroll = function($e, options) {

        // Private vars and methods
        var _data = $e.data('jscroll'),
            _userOptions = (typeof options === 'function') ? { callback: options } : options,
            _options = $.extend({}, $.jscroll.defaults, _userOptions, _data || {}),
            _isWindow = ($e.css('overflow-y') === 'visible'),
            _$next = $e.find(_options.nextSelector).first(),
            _$window = $(window),
            _$body = $('body'),
            _$scroll = _isWindow ? _$window : $e,
            _nextHref = $.trim(_$next.attr('href') + ' ' + _options.contentSelector),

            // Check if a loading image is defined and preload
            _preloadImage = function() {
                var src = $(_options.loadingHtml).filter('img').attr('src');
                if (src) {
                    var image = new Image();
                    image.src = src;
                }
            },

            // Wrap inner content, if it isn't already
            _wrapInnerContent = function() {
                if (!$e.find('.jscroll-inner').length) {
                    $e.contents().wrapAll('
');
                }
            },

            // Find the next link's parent, or add one, and hide it
            _nextWrap = function($next) {
                var $parent;
                if (_options.pagingSelector) {
                    $next.closest(_options.pagingSelector).hide();
                } else {
                    $parent = $next.parent().not('.jscroll-inner,.jscroll-added').addClass('jscroll-next-parent').hide();
                    if (!$parent.length) {
                        $next.wrap('
').parent().hide();
                    }
                }
            },

            // Remove the jscroll behavior and data from an element
            _destroy = function() {
                return _$scroll.unbind('.jscroll')
                    .removeData('jscroll')
                    .find('.jscroll-inner').children().unwrap()
                    .filter('.jscroll-added').children().unwrap();
            },

            // Observe the scroll event for when to trigger the next load
            _observe = function() {
                if ($e.is(':visible')) {
                    _wrapInnerContent();
                    var $inner = $e.find('div.jscroll-inner').first(),
                        data = $e.data('jscroll'),
                        borderTopWidth = parseInt($e.css('borderTopWidth'), 10),
                        borderTopWidthInt = isNaN(borderTopWidth) ? 0 : borderTopWidth,
                        iContainerTop = parseInt($e.css('paddingTop'), 10) + borderTopWidthInt,
                        iTopHeight = _isWindow ? _$scroll.scrollTop() : $e.offset().top,
                        innerTop = $inner.length ? $inner.offset().top : 0,
                        iTotalHeight = Math.ceil(iTopHeight - innerTop + _$scroll.height() + iContainerTop);

                    if (!data.waiting && iTotalHeight + _options.padding >= $inner.outerHeight()) {
                        //data.nextHref = $.trim(data.nextHref + ' ' + _options.contentSelector);
                        _debug('info', 'jScroll:', $inner.outerHeight() - iTotalHeight, 'from bottom. Loading next request...');
                        return _load();
                    }
                }
            },

            // Check if the href for the next set of content has been set
            _checkNextHref = function(data) {
                data = data || $e.data('jscroll');
                if (!data || !data.nextHref) {
                    _debug('warn', 'jScroll: nextSelector not found - destroying');
                    _destroy();
                    return false;
                } else {
                    _setBindings();
                    return true;
                }
            },

            _setBindings = function() {
                var $next = $e.find(_options.nextSelector).first();
                if (!$next.length) {
                    return;
                }
                if (_options.autoTrigger && (_options.autoTriggerUntil === false || _options.autoTriggerUntil > 0)) {
                    _nextWrap($next);
                     var scrollingBodyHeight = _$body.height() - $e.offset().top,
                    	scrollingHeight = ($e.height() < scrollingBodyHeight) ? $e.height() : scrollingBodyHeight,
                    	windowHeight = ($e.offset().top - _$window.scrollTop() > 0) ? _$window.height() - ($e.offset().top - $(window).scrollTop()) : _$window.height();
                    if (scrollingHeight <= windowHeight) {
                        _observe();
                    }
                    _$scroll.unbind('.jscroll').bind('scroll.jscroll', function() {
                        return _observe();
                    });
                    if (_options.autoTriggerUntil > 0) {
                        _options.autoTriggerUntil--;
                    }
                } else {
                    _$scroll.unbind('.jscroll');
                    $next.bind('click.jscroll', function() {
                        _nextWrap($next);
                        _load();
                        return false;
                    });
                }
            },

            // Load the next set of content, if available
            _load = function() {
                var $inner = $e.find('div.jscroll-inner').first(),
                    data = $e.data('jscroll');

                data.waiting = true;
                $inner.append('
')
                    .children('.jscroll-added').last()
                    .html('
' + _options.loadingHtml + '
')
                    .promise()
                    .done(function(){
                        if (_options.loadingFunction) {
                            _options.loadingFunction();
                        }
                    });

                return $e.animate({scrollTop: $inner.outerHeight()}, 0, function() {
                    var nextHref = data.nextHref;
                    $inner.find('div.jscroll-added').last().load(nextHref, function(r, status) {
                        if (status === 'error') {
                            return _destroy();
                        }
                        var $next = $(this).find(_options.nextSelector).first();
                        data.waiting = false;
                        data.nextHref = $next.attr('href') ? $.trim($next.attr('href') + ' ' + _options.contentSelector) : false;
                        $('.jscroll-next-parent', $e).remove(); // Remove the previous next link now that we have a new one
                        _checkNextHref();
                        if (_options.callback) {
                            _options.callback.call(this, nextHref);
                        }
                        _debug('dir', data);
                    });
                });
            },

            // Safe console debug - http://klauzinski.com/javascript/safe-firebug-console-in-javascript
            _debug = function(m) {
                if (_options.debug && typeof console === 'object' && (typeof m === 'object' || typeof console[m] === 'function')) {
                    if (typeof m === 'object') {
                        var args = [];
                        for (var sMethod in m) {
                            if (typeof console[sMethod] === 'function') {
                                args = (m[sMethod].length) ? m[sMethod] : [m[sMethod]];
                                console[sMethod].apply(console, args);
                            } else {
                                console.log.apply(console, args);
                            }
                        }
                    } else {
                        console[m].apply(console, Array.prototype.slice.call(arguments, 1));
                    }
                }
            };

        // Initialization
        $e.data('jscroll', $.extend({}, _data, {initialized: true, waiting: false, nextHref: _nextHref}));
        _wrapInnerContent();
        _preloadImage();
        _setBindings();

        // Expose API methods via the jQuery.jscroll namespace, e.g. $('sel').jscroll.method()
        $.extend($e.jscroll, {
            destroy: _destroy
        });
        return $e;
    };

    // Define the jscroll plugin method and loop
    $.fn.jscroll = function(m) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('jscroll'), jscroll;

            // Instantiate jScroll on this element if it hasn't been already
            if (data && data.initialized) {
                return;
            }
            jscroll = new jScroll($this, m);
        });
    };

})(jQuery);
<|endoftext|>


<commit_before>var app = angular.module('PIR', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav', 'ngRoute', 'chart.js', 'ngResource']);
var sort_by = function(field, reverse, primer){
   var key = primer ?
       function(x) {return primer(x[field])} :
       function(x) {return x[field]};
   reverse = !reverse ? 1 : -1;
   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     }
};

['User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef']
.forEach((urlobject)=>{
    app.factory(urlobject, ['$resource',
        function($resource) {
            return $resource(`/restful/${urlobject}/:where/:value`, {}, {
                get: {method: 'GET', cache: false, isArray: false},
                query: {method:'GET', isArray:true, transformResponse: function (data)
                    {
                        return angular.fromJson(data);
                    },
                },
                save: {method: 'POST', cache: false, isArray: false},
                update: {method: 'PUT', cache: false, isArray: false},
                delete: {method: 'DELETE', cache: false, isArray: false}
            });
        }]
    );
});

['Log']
.forEach((urlobject)=>{
  app.factory(urlobject, ['$resource',
    function($resource) {
      return $resource(`/restful/${urlobject}/:where`, {}, {
          'get':    {method:'GET'},
          //'save':   {method:'POST'},
          //'query':  {method:'GET', isArray:true},
          //'remove': {method:'DELETE'},
          //'delete': {method:'DELETE'}
      });
    }]
  );
});
//controllers for resources
['Log', 'User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef']
.forEach((urlobject)=>{
    app.controller(urlobject + 'Controller',['$scope', urlobject, function ($scope, resource) {
        const newitem = -2;
        $scope.init = function(handler) {
          handler();
          $scope.$on('eventUpdateSelected', handler);
        };
        $scope.get = function (where) {
            //console.log(where);
            var res = resource.get(where, function() {
                $scope.load(res);
            });
        };
        $scope.getlatestselectedhandler = function() {
            var _where = (urlobject === 'Log') ? $scope.getlatestselected('User') : $scope.getlatestselected(urlobject);
            if (_where >= 0) {
                var res = resource.get({where: _where}, function() {
                    if(urlobject === 'Log') {
                        $scope.log = '';
                        res.data.forEach((item)=>{$scope.log += item.message + " @ " + item.timestamp + "\n"});
                    } else {
                        //$scope.data = [res];
                        //console.log(res);
                        $scope.load(res);
                    };
                });
            }
        }
        $scope.query = function (where, callback) {
            if(urlobject!=='Log') {
                $scope.registerSelected(urlobject);
                var res = resource.query(where, function(data) {
                    if (urlobject !== 'User') {
                        $scope.data = res.sort(sort_by('code'));
                    } else {
                        $scope.data = res.sort(sort_by('lname'));
                    }
                    if (callback !== undefined) {
                        callback($scope.data);
                    }
                    /*
                    if ($scope.getlatestselected(urlobject) > -1) {
                        var i = 0;
                        while(data[i++].id !== $scope.getlatestselected(urlobject));
                        $scope.load(data[i-1]);
                    }
                    */
                });
            };
        };
        $scope.isSelected = function (id) {
            return $scope.selectedHas(urlobject, id);
        };
        $scope.selectitem = function (id) {
            $scope.updateSelected(urlobject, id);
        };
        $scope.load = function (item) {
            $scope.item = item;
            /*
            for (key in item) {
                if (item.hasOwnProperty(key)){
                    $scope[key] = item[key];
                }
            }
            */
        };
        $scope.addnew = function () {
            $scope.updateSelected(urlobject, newitem);
        }
    }]);
});

app.controller('selectController', function ($scope) {
    var selected = {};
    $scope.registerSelected = function(key) {
        if (!(key in selected)) {
          selected[key] = new Set();
        }
    }
    $scope.updateSelected = function(key, value) {
        if (selected[key].has(value)) {
            selected[key].delete(value);
        } else {
            selected[key].add(value);
        }
        /*
        for (key_ in callbacks) {
            callbacks[key_]();
        }
        */
        $scope.$broadcast("eventUpdateSelected", {key: key, value: value});
    }
    $scope.selectedHas = function(key, value) {
        return selected[key].has(value);
    }
    $scope.selectedIsEmpty = function(key) {
        return (selected[key].size === 0)
    }
    $scope.getlatestselected = (key) => {
      return ((key in selected) && selected[key].size>0) ? [...selected[key]][selected[key].size-1] : -1;
    };
    $scope.filter = function (item) {
        var show = true;
        var hasrelation = false;
        for (key in selected) {
            var _key = key.toLowerCase() + '_id';
            if (_key !== 'user_id') {
                if (!item.hasOwnProperty(_key)) {
                    continue;
                }
                hasrelation = true;
                show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[_key]));
            } else {
                for (many in item) {
                    if (many.substring(0, 5) === 'user_') {
                        hasrelation = true;
                        show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[many]));
                    }
                }
            }
        }
        return !hasrelation || show;
    };
});

app.controller('scopeUpdater', function ($scope) {
    $scope.setVar = function (varName, x) {
        $scope[varName] = x;
    }
});

app.directive("searchresult", function() {
    return {
        link: function(scope, el, attrs) {
          if(scope.results === undefined) {
            scope.results = {};
          }
          scope.results[attrs.searchQuery] = [
            {
              text: attrs.searchQuery
            },
            {
              text: attrs.searchQuery
            }
          ]
        }
    };
});
<commit_msg>load log<commit_after>var app = angular.module('PIR', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav', 'ngRoute', 'chart.js', 'ngResource']);
var sort_by = function(field, reverse, primer){
   var key = primer ?
       function(x) {return primer(x[field])} :
       function(x) {return x[field]};
   reverse = !reverse ? 1 : -1;
   return function (a, b) {
       return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
     }
};

['User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef']
.forEach((urlobject)=>{
    app.factory(urlobject, ['$resource',
        function($resource) {
            return $resource(`/restful/${urlobject}/:where/:value`, {}, {
                get: {method: 'GET', cache: false, isArray: false},
                query: {method:'GET', isArray:true, transformResponse: function (data)
                    {
                        return angular.fromJson(data);
                    },
                },
                save: {method: 'POST', cache: false, isArray: false},
                update: {method: 'PUT', cache: false, isArray: false},
                delete: {method: 'DELETE', cache: false, isArray: false}
            });
        }]
    );
});

['Log']
.forEach((urlobject)=>{
  app.factory(urlobject, ['$resource',
    function($resource) {
      return $resource(`/restful/${urlobject}/:where`, {}, {
          'get':    {method:'GET'},
          //'save':   {method:'POST'},
          //'query':  {method:'GET', isArray:true},
          //'remove': {method:'DELETE'},
          //'delete': {method:'DELETE'}
      });
    }]
  );
});
//controllers for resources
['Log', 'User', 'ReportClass', 'VariableCat_1', 'VariableCat_2', 'VariableCat_3', 'VariableDef', 'vVariableDef']
.forEach((urlobject)=>{
    app.controller(urlobject + 'Controller',['$scope', urlobject, function ($scope, resource) {
        const newitem = -2;
        $scope.init = function(handler) {
          handler();
          $scope.$on('eventUpdateSelected', handler);
        };
        $scope.get = function (where) {
            //console.log(where);
            var res = resource.get(where, function() {
                $scope.load(res);
            });
        };
        $scope.getlatestselectedhandler = function() {
            var _where = (urlobject === 'Log') ? $scope.getlatestselected('User') : $scope.getlatestselected(urlobject);
            if (_where >= 0) {
                var res = resource.get({where: _where}, function() {
                    if(urlobject === 'Log') {
                        $scope.item = {};
                        $scope.item.log = '';
                        res.data.forEach((item)=>{$scope.item.log += item.message + " @ " + item.timestamp + "\n"});
                    } else {
                        //$scope.data = [res];
                        //console.log(res);
                        $scope.load(res);
                    };
                });
            }
        }
        $scope.query = function (where, callback) {
            if(urlobject!=='Log') {
                $scope.registerSelected(urlobject);
                var res = resource.query(where, function(data) {
                    if (urlobject !== 'User') {
                        $scope.data = res.sort(sort_by('code'));
                    } else {
                        $scope.data = res.sort(sort_by('lname'));
                    }
                    if (callback !== undefined) {
                        callback($scope.data);
                    }
                    /*
                    if ($scope.getlatestselected(urlobject) > -1) {
                        var i = 0;
                        while(data[i++].id !== $scope.getlatestselected(urlobject));
                        $scope.load(data[i-1]);
                    }
                    */
                });
            };
        };
        $scope.isSelected = function (id) {
            return $scope.selectedHas(urlobject, id);
        };
        $scope.selectitem = function (id) {
            $scope.updateSelected(urlobject, id);
        };
        $scope.load = function (item) {
            $scope.item = item;
            /*
            for (key in item) {
                if (item.hasOwnProperty(key)){
                    $scope[key] = item[key];
                }
            }
            */
        };
        $scope.addnew = function () {
            $scope.updateSelected(urlobject, newitem);
        }
    }]);
});

app.controller('selectController', function ($scope) {
    var selected = {};
    $scope.registerSelected = function(key) {
        if (!(key in selected)) {
          selected[key] = new Set();
        }
    }
    $scope.updateSelected = function(key, value) {
        if (selected[key].has(value)) {
            selected[key].delete(value);
        } else {
            selected[key].add(value);
        }
        /*
        for (key_ in callbacks) {
            callbacks[key_]();
        }
        */
        $scope.$broadcast("eventUpdateSelected", {key: key, value: value});
    }
    $scope.selectedHas = function(key, value) {
        return selected[key].has(value);
    }
    $scope.selectedIsEmpty = function(key) {
        return (selected[key].size === 0)
    }
    $scope.getlatestselected = (key) => {
      return ((key in selected) && selected[key].size>0) ? [...selected[key]][selected[key].size-1] : -1;
    };
    $scope.filter = function (item) {
        var show = true;
        var hasrelation = false;
        for (key in selected) {
            var _key = key.toLowerCase() + '_id';
            if (_key !== 'user_id') {
                if (!item.hasOwnProperty(_key)) {
                    continue;
                }
                hasrelation = true;
                show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[_key]));
            } else {
                for (many in item) {
                    if (many.substring(0, 5) === 'user_') {
                        hasrelation = true;
                        show = show && (($scope.selectedIsEmpty(key)) || $scope.selectedHas(key, item[many]));
                    }
                }
            }
        }
        return !hasrelation || show;
    };
});

app.controller('scopeUpdater', function ($scope) {
    $scope.setVar = function (varName, x) {
        $scope[varName] = x;
    }
});

app.directive("searchresult", function() {
    return {
        link: function(scope, el, attrs) {
          if(scope.results === undefined) {
            scope.results = {};
          }
          scope.results[attrs.searchQuery] = [
            {
              text: attrs.searchQuery
            },
            {
              text: attrs.searchQuery
            }
          ]
        }
    };
});
<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('event-emitter');
const expect = require('chai').expect;
const nock = require('nock');
const mockRequire = require('mock-require');
const got = require('got');
const promiseDelay = require('promise-delay');
const isLinkWorking = require('../');
const pkg = require('../package.json');

before(() => { isLinkWorking.connectivityCacheDuration = 0; });
afterEach(() => mockRequire.stopAll());

it('should resolve to true for http://google.com (HEAD)', () => {
    return isLinkWorking('http://google.com')
    .then((working) => expect(working).to.equal(true));
});

it('should resolve to true for http://google.com (GET)', () => {
    const nocked = nock('http://google.com')
    .head('/')
    .reply(404, () => nock.cleanAll());

    return isLinkWorking('http://google.com')
    .then((working) => expect(working).to.equal(true))
    .then(() => nocked.done(), (err) => {
        nock.cleanAll();
        throw err;
    });
});

it('should resolve to false for http://thisdomainwillneverexist.org (domain not found)', () => {
    return isLinkWorking('http://thisdomainwillneverexist.org')
    .then((working) => expect(working).to.equal(false));
});

it('should resolve to false for https://github.com/somepagethatwillneverexist (404)', () => {
    return isLinkWorking('https://github.com/somepagethatwillneverexist')
    .then((working) => expect(working).to.equal(false));
});

it('should pass the correct options to `got`', () => {
    let options;

    mockRequire('got', {
        head: (url, _options) => {
            options = _options;
            return Promise.resolve();
        },
        stream: (url, _options) => {
            options = _options;
            return Promise.resolve(new EventEmitter());
        },
    });

    const isLinkWorking = mockRequire.reRequire('../');

    return Promise.resolve()
    .then(() => {
        return isLinkWorking('http://google.com')
        .then(() => {
            expect(options).to.eql({
                followRedirect: true,
                retries: 3,
                timeout: 15000,
                agent: null,
                headers: {
                    'user-agent': `is-link-working/${pkg.version} (https://github.com/IndigoUnited/is-link-working)`,
                },
            });
        });
    })
    .then(() => {
        return isLinkWorking('http://somepagethatwillneverexist.org', {
            followRedirect: false,
            retries: 1,
            timeout: 5000,
        })
        .then(() => {
            expect(options).to.eql({
                followRedirect: false,
                retries: 1,
                timeout: 5000,
                agent: null,
                headers: {
                    'user-agent': `is-link-working/${pkg.version} (https://github.com/IndigoUnited/is-link-working)`,
                },
            });
        });
    });
});

it('should report broken with urls having wrong protocols', () => {
    return isLinkWorking('htttps://google.com')
    .then((working) => expect(working).to.equal(false));
});

describe('connectivity check', () => {
    it('should NOT check connectivity if options.checkConnectivity is false', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org')
        .then((working) => {
            expect(called).to.equal(false);
            expect(working).to.equal(false);
        });
    });

    it('should resolve to false if request failed but we are online', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then((working) => {
            expect(called).to.equal(true);
            expect(working).to.equal(false);
        });
    });

    it('should reject if request failed and we are NOT online', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, false);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, (err) => {
            expect(called).to.equal(true);
            expect(err).to.be.an.instanceOf(got.RequestError);
        });
    });

    it('should handle connectivity check errors, rejecting with the original request error', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(new Error('foo'));
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, (err) => {
            expect(called).to.equal(true);
            expect(err).to.be.an.instanceOf(got.RequestError);
        });
    });
});

describe('connectivity cache', () => {
    it('should cache is-online result', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        isLinkWorking.connectivityCacheDuration = 100;

        return Promise.resolve()
        .then(() => {
            return Promise.all([
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                promiseDelay(50).then(() => isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })),
            ])
            .then((working) => {
                expect(working).to.eql([false, false]);
                expect(nrCalls).to.equal(1);
            });
        })
        .then(() => promiseDelay(75))
        .then(() => {
            return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
            .then((working) => {
                expect(working).to.equal(false);
                expect(nrCalls).to.equal(2);
            });
        });
    });

    it('should not cache is-online errors', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(new Error('foo'));
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, () => {
            mockRequire('is-online', (callback) => {
                nrCalls += 1;
                return callback(null, true);
            });

            const isLinkWorking = mockRequire.reRequire('../');

            return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
            .then((working) => {
                expect(nrCalls).to.equal(2);
                expect(working).to.equal(false);
            });
        });
    });

    it('should not cache if connectivityCacheDuration is 0', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        isLinkWorking.connectivityCacheDuration = 0;

        return Promise.resolve()
        .then(() => {
            return Promise.all([
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                promiseDelay(50).then(() => isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })),
            ])
            .then((working) => {
                expect(working).to.eql([false, false, false]);
                expect(nrCalls).to.equal(3);
            });
        });
    });
});
<commit_msg>Fix test.<commit_after>'use strict';

const EventEmitter = require('events');
const expect = require('chai').expect;
const nock = require('nock');
const mockRequire = require('mock-require');
const got = require('got');
const promiseDelay = require('promise-delay');
const isLinkWorking = require('../');
const pkg = require('../package.json');

before(() => { isLinkWorking.connectivityCacheDuration = 0; });
afterEach(() => mockRequire.stopAll());

it('should resolve to true for http://google.com (HEAD)', () => {
    return isLinkWorking('http://google.com')
    .then((working) => expect(working).to.equal(true));
});

it('should resolve to true for http://google.com (GET)', () => {
    const nocked = nock('http://google.com')
    .head('/')
    .reply(404, () => nock.cleanAll());

    return isLinkWorking('http://google.com')
    .then((working) => expect(working).to.equal(true))
    .then(() => nocked.done(), (err) => {
        nock.cleanAll();
        throw err;
    });
});

it('should resolve to false for http://thisdomainwillneverexist.org (domain not found)', () => {
    return isLinkWorking('http://thisdomainwillneverexist.org')
    .then((working) => expect(working).to.equal(false));
});

it('should resolve to false for https://github.com/somepagethatwillneverexist (404)', () => {
    return isLinkWorking('https://github.com/somepagethatwillneverexist')
    .then((working) => expect(working).to.equal(false));
});

it('should pass the correct options to `got`', () => {
    let options;

    mockRequire('got', {
        head: (url, _options) => {
            options = _options;
            return Promise.resolve();
        },
        stream: (url, _options) => {
            options = _options;
            return Promise.resolve(new EventEmitter());
        },
    });

    const isLinkWorking = mockRequire.reRequire('../');

    return Promise.resolve()
    .then(() => {
        return isLinkWorking('http://google.com')
        .then(() => {
            expect(options).to.eql({
                followRedirect: true,
                retries: 3,
                timeout: 15000,
                agent: null,
                headers: {
                    'user-agent': `is-link-working/${pkg.version} (https://github.com/IndigoUnited/is-link-working)`,
                },
            });
        });
    })
    .then(() => {
        return isLinkWorking('http://somepagethatwillneverexist.org', {
            followRedirect: false,
            retries: 1,
            timeout: 5000,
        })
        .then(() => {
            expect(options).to.eql({
                followRedirect: false,
                retries: 1,
                timeout: 5000,
                agent: null,
                headers: {
                    'user-agent': `is-link-working/${pkg.version} (https://github.com/IndigoUnited/is-link-working)`,
                },
            });
        });
    });
});

it('should report broken with urls having wrong protocols', () => {
    return isLinkWorking('htttps://google.com')
    .then((working) => expect(working).to.equal(false));
});

describe('connectivity check', () => {
    it('should NOT check connectivity if options.checkConnectivity is false', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org')
        .then((working) => {
            expect(called).to.equal(false);
            expect(working).to.equal(false);
        });
    });

    it('should resolve to false if request failed but we are online', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then((working) => {
            expect(called).to.equal(true);
            expect(working).to.equal(false);
        });
    });

    it('should reject if request failed and we are NOT online', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(null, false);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, (err) => {
            expect(called).to.equal(true);
            expect(err).to.be.an.instanceOf(got.RequestError);
        });
    });

    it('should handle connectivity check errors, rejecting with the original request error', () => {
        let called = false;

        mockRequire('is-online', (callback) => {
            called = true;
            return callback(new Error('foo'));
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, (err) => {
            expect(called).to.equal(true);
            expect(err).to.be.an.instanceOf(got.RequestError);
        });
    });
});

describe('connectivity cache', () => {
    it('should cache is-online result', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        isLinkWorking.connectivityCacheDuration = 100;

        return Promise.resolve()
        .then(() => {
            return Promise.all([
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                promiseDelay(50).then(() => isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })),
            ])
            .then((working) => {
                expect(working).to.eql([false, false]);
                expect(nrCalls).to.equal(1);
            });
        })
        .then(() => promiseDelay(75))
        .then(() => {
            return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
            .then((working) => {
                expect(working).to.equal(false);
                expect(nrCalls).to.equal(2);
            });
        });
    });

    it('should not cache is-online errors', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(new Error('foo'));
        });

        const isLinkWorking = mockRequire.reRequire('../');

        return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
        .then(() => {
            throw new Error('Should have failed');
        }, () => {
            mockRequire('is-online', (callback) => {
                nrCalls += 1;
                return callback(null, true);
            });

            const isLinkWorking = mockRequire.reRequire('../');

            return isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })
            .then((working) => {
                expect(nrCalls).to.equal(2);
                expect(working).to.equal(false);
            });
        });
    });

    it('should not cache if connectivityCacheDuration is 0', () => {
        let nrCalls = 0;

        mockRequire('is-online', (callback) => {
            nrCalls += 1;
            return callback(null, true);
        });

        const isLinkWorking = mockRequire.reRequire('../');

        isLinkWorking.connectivityCacheDuration = 0;

        return Promise.resolve()
        .then(() => {
            return Promise.all([
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true }),
                promiseDelay(50).then(() => isLinkWorking('http://thisdomainwillneverexist.org', { checkConnectivity: true })),
            ])
            .then((working) => {
                expect(working).to.eql([false, false, false]);
                expect(nrCalls).to.equal(3);
            });
        });
    });
});
<|endoftext|>


<commit_before>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < players.length; j++) {
                        if (players[j].toLowerCase() == targets[i].toLowerCase()) {
                            // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                            gameData.votes[i].target = players[j];
                        }
                    }
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    // add a new key (property) to the object for every vote target
                    voters[targets[i]] = [];
                    activeVoters[targets[i]] = [];
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[j].day) {
                        for (var j = 0; j < targets.length; j++) {
                            for (var z = 0; z < activeVoters[targets[j]].length; z++) {
                                var remainingVoters = activeVoters[targets[j]];
                                if (remainingVoters[z] == gameData.votes[j].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voter
                                    remainingVoters.splice(z, 1);
                                }
                                activeVoters[targets[j]] = remainingVoters;
                            }
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < activeVoters[targets[i]].length; j++) {
                        targetsVoters = activeVoters[targets[i]];
                        for (var z = 0; z < nonvoters; z++) {
                            if (targetsVoters[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < voters[targets[i]].length; j++) {
                            if (activeVoters[targets[i]].indexOf(voters[targets[i]][j]) == -1) {
                                voters[targets[i]][j] = "<s>" + voters[targets[i]][j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + voters[targets[i]].join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < voters[targets[i]].length; j++) {
                            if (activeVoters[targets[i]].indexOf(voters[targets[i]][j]) == -1) {
                                voters[targets[i]][j] = "[s]" + voters[targets[i]][j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + voters[targets[i]].join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<commit_msg>more small fixes<commit_after>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game! (reload the page to see the result)
";

            var nicknames = {
                "27ninjabunnies": ["27nb", "nb", "ninja", "bunnies", "ninjabunnies"],
                "Alakaslam": ["slam"],
                "Artanis[Xp]": ["art", "artanis"],
                "batsnacks": ["bat", "bats"],
                "Bill Murray": ["bm", "bill", "murray"],
                "Blazinghand": ["bh", "blazing"],
                "boxerfred": ["bf", "boxer"],
                "Chezinu": ["che", "chez"],
                "Clarity_nl": ["clarity"],
                "Damdred": ["damd", "damdy"],
                "EdgarAllanPoE": ["edgar", "allan", "poe", "edgarallenpoe"],
                "Fecalfeast": ["ff", "fecal"],
                "Fidei86": ["fidei"],
                "FirmTofu": ["ft", "firm", "tofu"],
                "GlowingBear": ["gb", "glowing", "bear"],
                "Half the Sky": ["hts", "sky"],
                "Hapahauli": ["hapa"],
                "Holyflare": ["hf"],
                "IAmRobik": ["robik"],
                "JudgeJudy": ["jj", "judge", "judy"],
                "justanothertownie": ["jat"],
                "Keirathi": ["kei", "keir"],
                "LightningStrike": ["ls", "lightning"],
                "marvellosity": ["marv", "marvy", "marvel", "marvelocity", "marshmallow"],
                "Oatsmaster": ["oat", "oats"],
                "ObiWanShinobi": ["ows", "obi", "obiwan", "shinobi"],
                "Onegu": ["o", "oneg"],
                "raynpelikoneet": ["ray", "rayn", "raypelikoneet"],
                "rsoultin": ["rs", "rsou", "rsoul"],
                "sandroba": ["sand", "roba"],
                "[UoN]Sentinel": ["sent", "sentinel"],
                "scott31337": ["scott"],
                "Stutters695": ["stutters"],
                "The Shining": ["shining"],
                "Tubesock": ["ts", "tube"],
                "VayneAuthority": ["va", "vayne"],
                "VisceraEyes": ["ve", "viscera"],
                "WaveofShadow": ["wos", "wave"],
                "Xatalos": ["xat", "xata"],
                "yamato77": ["yam", "yama", "yamato"]
            };

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target.toLowerCase()) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < players.length; j++) {
                        if (players[j].toLowerCase() == targets[i].toLowerCase()) {
                            // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name
                            targets[i] = players[j];
                        }
                    }
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < targets.length; i++) {
                    // add a new key (property) to the object for every vote target
                    voters[targets[i]] = [];
                    activeVoters[targets[i]] = [];
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[j].day) {
                        for (var j = 0; j < targets.length; j++) {
                            for (var z = 0; z < activeVoters[targets[j]].length; z++) {
                                var remainingVoters = activeVoters[targets[j]];
                                if (remainingVoters[z] == gameData.votes[j].voter) {
                                    // every time a new vote is given, remove every previous ACTIVE vote from the voter
                                    remainingVoters.splice(z, 1);
                                }
                                activeVoters[targets[j]] = remainingVoters;
                            }
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[j].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < activeVoters[targets[i]].length; j++) {
                        var targetsVoters = activeVoters[targets[i]];
                        for (var z = 0; z < nonvoters; z++) {
                            if (targetsVoters[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < voters[targets[i]].length; j++) {
                            if (activeVoters[targets[i]].indexOf(voters[targets[i]][j]) == -1) {
                                voters[targets[i]][j] = "<s>" + voters[targets[i]][j] + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + voters[targets[i]].join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    for (var j = 0; j < voters[targets[i]].length; j++) {
                            if (activeVoters[targets[i]].indexOf(voters[targets[i]][j]) == -1) {
                                voters[targets[i]][j] = "[s]" + voters[targets[i]][j] + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + voters[targets[i]].join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<|endoftext|>