<commit_before>'use strict'

const common = require('./common')
const debug = require('debug')('electron-packager')
const path = require('path')
const targets = require('./targets')

const DEFAULT_IGNORES = [
  '/node_modules/electron($|/)',
  '/node_modules/electron-prebuilt(-compile)?($|/)',
  '/node_modules/electron-packager($|/)',
  '/\\.git($|/)',
  '/node_modules/\\.bin($|/)',
  '\\.o(bj)?$'
]

function generateIgnores (opts) {
  if (typeof (opts.ignore) !== 'function') {
    if (opts.ignore) {
      opts.ignore = common.ensureArray(opts.ignore).concat(DEFAULT_IGNORES)
    } else {
      opts.ignore = [].concat(DEFAULT_IGNORES)
    }
    if (process.platform === 'linux') {
      opts.ignore.push(common.baseTempDir(opts))
    }

    debug('Ignored path regular expressions:', opts.ignore)
  }
}

function generateOutIgnores (opts) {
  let normalizedOut = opts.out ? path.resolve(opts.out) : null
  let outIgnores = []
  if (normalizedOut === null || normalizedOut === process.cwd()) {
    for (const platform of Object.keys(targets.officialPlatformArchCombos)) {
      for (const arch of targets.officialPlatformArchCombos[platform]) {
        let basenameOpts = {
          arch: arch,
          name: opts.name,
          platform: platform
        }
        outIgnores.push(path.join(process.cwd(), common.generateFinalBasename(basenameOpts)))
      }
    }
  } else {
    outIgnores.push(normalizedOut)
  }

  debug('Ignored paths based on the out param:', outIgnores)

  return outIgnores
}

function userIgnoreFilter (opts) {
  let ignore = opts.ignore || []
  let ignoreFunc = null

  if (typeof (ignore) === 'function') {
    ignoreFunc = file => { return !ignore(file) }
  } else {
    ignore = common.ensureArray(ignore)

    ignoreFunc = function filterByRegexes (file) {
      return !ignore.some(regex => file.match(regex))
    }
  }

  let outIgnores = generateOutIgnores(opts)

  return function filter (file) {
    if (outIgnores.indexOf(file) !== -1) {
      return false
    }

    let name = file.split(path.resolve(opts.dir))[1]

    /* istanbul ignore if */
    if (path.sep === '\\') {
      // convert slashes so unix-format ignores work
      name = name.replace(/\\/g, '/')
    }

    return ignoreFunc(name)
  }
}

module.exports = {
  generateIgnores: generateIgnores,
  generateOutIgnores: generateOutIgnores,
  userIgnoreFilter: userIgnoreFilter
}
<commit_msg>Remove a now unnecessary istanbul ignore directive<commit_after>'use strict'

const common = require('./common')
const debug = require('debug')('electron-packager')
const path = require('path')
const targets = require('./targets')

const DEFAULT_IGNORES = [
  '/node_modules/electron($|/)',
  '/node_modules/electron-prebuilt(-compile)?($|/)',
  '/node_modules/electron-packager($|/)',
  '/\\.git($|/)',
  '/node_modules/\\.bin($|/)',
  '\\.o(bj)?$'
]

function generateIgnores (opts) {
  if (typeof (opts.ignore) !== 'function') {
    if (opts.ignore) {
      opts.ignore = common.ensureArray(opts.ignore).concat(DEFAULT_IGNORES)
    } else {
      opts.ignore = [].concat(DEFAULT_IGNORES)
    }
    if (process.platform === 'linux') {
      opts.ignore.push(common.baseTempDir(opts))
    }

    debug('Ignored path regular expressions:', opts.ignore)
  }
}

function generateOutIgnores (opts) {
  let normalizedOut = opts.out ? path.resolve(opts.out) : null
  let outIgnores = []
  if (normalizedOut === null || normalizedOut === process.cwd()) {
    for (const platform of Object.keys(targets.officialPlatformArchCombos)) {
      for (const arch of targets.officialPlatformArchCombos[platform]) {
        let basenameOpts = {
          arch: arch,
          name: opts.name,
          platform: platform
        }
        outIgnores.push(path.join(process.cwd(), common.generateFinalBasename(basenameOpts)))
      }
    }
  } else {
    outIgnores.push(normalizedOut)
  }

  debug('Ignored paths based on the out param:', outIgnores)

  return outIgnores
}

function userIgnoreFilter (opts) {
  let ignore = opts.ignore || []
  let ignoreFunc = null

  if (typeof (ignore) === 'function') {
    ignoreFunc = file => { return !ignore(file) }
  } else {
    ignore = common.ensureArray(ignore)

    ignoreFunc = function filterByRegexes (file) {
      return !ignore.some(regex => file.match(regex))
    }
  }

  let outIgnores = generateOutIgnores(opts)

  return function filter (file) {
    if (outIgnores.indexOf(file) !== -1) {
      return false
    }

    let name = file.split(path.resolve(opts.dir))[1]

    if (path.sep === '\\') {
      // convert slashes so unix-format ignores work
      name = name.replace(/\\/g, '/')
    }

    return ignoreFunc(name)
  }
}

module.exports = {
  generateIgnores: generateIgnores,
  generateOutIgnores: generateOutIgnores,
  userIgnoreFilter: userIgnoreFilter
}
<|endoftext|>


<commit_before>import $ from 'jquery';

import BibliodataView from '../../../../scripts/manager/views/BibliodataView';
import CostCenterCollection from '../../../../scripts/manager/models/CostCenterCollection';
import PublicationModel from '../../../../scripts/manager/models/PublicationModel';
import PublicationTypeCollection from '../../../../scripts/manager/models/PublicationTypeCollection';

describe('BibliodataView', function() {
    let pubTypeFetchDeferred, costCenterFetchActiveDeferred, costCenterFetchNotActiveDeferred;
    let pubModel;
    let testView;

    beforeEach(function() {
        $('body').append('

');

        pubModel = new PublicationModel();

        pubTypeFetchDeferred = $.Deferred();
        costCenterFetchActiveDeferred = $.Deferred();
        costCenterFetchNotActiveDeferred = $.Deferred();

        spyOn(window, 'setInterval');  // So the tinymce does not get initialized

        spyOn(PublicationTypeCollection.prototype, 'fetch').and.returnValue(pubTypeFetchDeferred);
        spyOn(CostCenterCollection.prototype, 'fetch').and.callFake(function(options) {
            if (options.data.active === 'y') {
                return costCenterFetchActiveDeferred;
            } else {
                return costCenterFetchNotActiveDeferred;
            }
        });
    });

    afterEach(function() {
        testView.remove();
        $('#test-div').remove();
    });

    it('Expects that the publicationType lookup values are fetched at initialization', function() {
        testView = new BibliodataView({
            model : pubModel,
            el : '#test-div'
        });

        expect(PublicationTypeCollection.prototype.fetch).toHaveBeenCalled();
    });

    it('Expects that the both the active and not active cost centers are fetched at initialization', function() {
        testView = new BibliodataView({
            model : pubModel,
            el : '#test-div'
        });

        expect(CostCenterCollection.prototype.fetch.calls.count()).toBe(2);
        expect(CostCenterCollection.prototype.fetch.calls.argsFor(0)[0].data.active).toEqual('y');
        expect(CostCenterCollection.prototype.fetch.calls.argsFor(1)[0].data.active).toEqual('n');
    });

    describe('Tests for render', function() {

        beforeEach(function() {
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });
            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2').and.callThrough();
        });

        it('Expects that stickit is initialized', function() {
            testView.render();
            expect(testView.stickit).toHaveBeenCalled();
        });

        it('Expects that select2\'s that do not preload their selections are initialized', function() {
            testView.render();
            expect($.fn.select2.calls.count()).toBe(3);
        });

        // TODO: figure out how to test select2's better. In particular I'd like to test setting up the new transport option
        // for the pub-subtype-input
        it('Expects that the publication type and larger work type input\'s are initialized when the publication type fetch is done', function() {
            let select2Count;
            testView.render();
            select2Count = $.fn.select2.calls.count();
            pubTypeFetchDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count + 2);
        });

        it('Expects that the costCenter select is initialized after both cost center fetches are complete', function() {
            let select2Count;
            testView.render();
            select2Count = $.fn.select2.calls.count();
            costCenterFetchActiveDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count);
            costCenterFetchNotActiveDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count + 1);
        });
    });

    describe('Test DOM event handling for the select2\'s', function() {
        let ev;

        beforeEach(function() {
            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2');

            pubModel.set({
                publicationType : {id : 1, text : 'Type 1'},
                publicationSubtype : {id : 2, text : 'Subtype 2'},
                seriesTitle : {id : 3, text : 'Series Title 3'},
                costCenters : [{id : 4, text : 'CC 4'}, {id : 5, text : 'CC 5'}],
                largerWorkType : {id : 6, text : 'Type 6'},
                largerWorkSubtype : {id : 7, text : 'Subtype 7'}
            });
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });
            testView.render();
        });

        it('Expects that when a pub type is selected, the publicationType is updated and the publicationSubtype and seriesTitle are unset', function() {
            ev = {
                currentTarget : {
                    value : 11,
                    selectedOptions : [{innerHTML : 'Type11'}]
                }
            };
            testView.selectPubType(ev);
            expect(pubModel.get('publicationType')).toEqual({id : 11, text : 'Type11'});
            expect(pubModel.get('publicationSubType')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub type is cleared, the publicationType, publicationSubtype, and seriesTitle are unset', function() {
            testView.resetPubType();
            expect(pubModel.get('publicationType')).toBeUndefined();
            expect(pubModel.get('publicationSubtype')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub subtype is selected, the publicationSubtype is updated and the seriesTitle is unset', function() {
            ev = {
                currentTarget : {
                    value : 12,
                    selectedOptions : [{innerHTML : 'Subtype 12'}]
                }
            };
            testView.selectPubSubtype(ev);
            expect(pubModel.get('publicationSubtype')).toEqual({id : 12, text : 'Subtype 12'});
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub subtype is cleared, the publicationSubtype and seriesTitle are unset', function() {
            testView.resetPubSubtype();
            expect(pubModel.get('publicationSubtype')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects than when a series title is selected, the seriesTitle is updated', function() {
            ev = {
                currentTarget : {
                    value : 13,
                    selectedOptions : [{innerHTML : 'Series Title 13'}]
                }
            };
            testView.selectSeriesTitle(ev);
            expect(pubModel.get('seriesTitle')).toEqual({id : 13, text : 'Series Title 13'});
        });

        it('Expects that when a series title is cleared, the seriesTitle is unset', function() {
            testView.resetSeriesTitle();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a cost center is selected, it is added to the current costCenters', function() {
            let costCenters;
            ev = {
                params : {
                    data : {id : 15, text : 'CC 15'}
                }
            };

            testView.selectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(3);
            expect(costCenters).toContain({id : 4, text : 'CC 4'});
            expect(costCenters).toContain({id : 5, text : 'CC 5'});
            expect(costCenters).toContain({id : 15, text : 'CC 15'});

            pubModel.unset('costCenters');
            testView.selectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(1);
            expect(costCenters).toContain({id : 15, text : 'CC 15'});
        });

        it('Expects that when a cost center is removed, costCenters is updated appropriately', function() {
            let costCenters;
            ev = {
                params : {
                    data : {id : 4, text : 'CC 4'}
                }
            };
            testView.unselectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(1);
            expect(costCenters).toEqual([{id : 5, text : 'CC 5'}]);
        });

        it('Expects that when a larger work type is selected, the largerWorkType is updated and the largerWorkSubtype is unset', function() {
            ev = {
                currentTarget : {
                    value : 20,
                    selectedOptions: [{innerHTML : 'Type 20'}]
                }
            };
            testView.selectLargerWorkType(ev);
            expect(pubModel.get('largerWorkType')).toEqual({id : 20, text : 'Type 20'});
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });

        it('Expects that when a larger work type is cleared, the largerWorkType  and largerWorkSubtype are unset', function() {
            testView.resetLargerWorkType();
            expect(pubModel.get('largerWorkType')).toBeUndefined();
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });

        it('Expects that when a larger work subtype is selected, the largerWorkSubtype is updated', function() {
            ev = {
                currentTarget : {
                    value : 20,
                    selectedOptions: [{innerHTML : 'Subtype 20'}]
                }
            };
            testView.selectLargerWorkSubtype(ev);
            expect(pubModel.get('largerWorkSubtype')).toEqual({id : 20, text : 'Subtype 20'});
        });

        it('Expects that when a larger work subtype is cleared, the largerWorkSubtype is unset', function() {
            testView.resetLargerWorkSubtype();
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });
    });

    describe('Tests for model event listeners', function() {

        beforeEach(function() {
            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2').and.callThrough();

            pubModel.set({
                publicationType : {id : 1, text : 'Type 1'},
                publicationSubtype : {id : 2, text : 'Subtype 2'},
                seriesTitle : {id : 3, text : 'Series Title 3'},
                costCenters : [{id : 4, text : 'CC 4'}, {id : 5, text : 'CC 5'}],
                largerWorkType : {id : 6, text : 'Type 6'},
                largerWorkSubtype : {id : 7, text : 'Subtype 7'}
            });
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });

            // For static select2's need to add options.
            testView.publicationTypeCollection.set([{id : 1, text : 'Type1'}, {id : 11, text : 'Type 11'}]);
            testView.activeCostCenters.set([{id : 4, text : 'CC 4'}, {id : 6, text : 'CC 6'}]);
            testView.notActiveCostCenters.set([{id : 5, text : 'CC 5'}]);

            pubTypeFetchDeferred.resolve();
            costCenterFetchActiveDeferred.resolve();
            costCenterFetchNotActiveDeferred.resolve();

            testView.render();
        });

        it('Expects that if publicationType is updated, the pubType DOM element is updated and the subtype DOM element is disabled when publicationType is unset', function() {
            const $type = testView.$('#pub-type-input');
            const $subtype = testView.$('#pub-subtype-input');
            pubModel.set('publicationType', {id : 11, text : 'Type 11'});
            expect($type.val()).toEqual('11');
            expect($subtype.is(':disabled')).toBe(false);

            pubModel.unset('publicationType');
            expect($type.val()).toBeNull();
            expect($subtype.is(':disabled')).toBe(true);
        });

        it('Expects that if publicationSubtype is updated, the pubSubtype DOM element is updated and the seriesTitle DOM element is disabled when there is no publicationSubtype', function() {
            const $subtype = testView.$('#pub-subtype-input');
            const $seriesTitle = testView.$('#series-title-input');
            pubModel.set('publicationSubtype', {id : 12, text : 'Subtype 12'});
            expect($subtype.val()).toEqual('12');
            expect($seriesTitle.is(':disabled')).toBe(false);

            pubModel.unset('publicationSubtype');
            expect($subtype.val()).toBeNull();
            expect($seriesTitle.is(':disabled')).toBe(true);
        });

        it('Expects that if seriesTitle is updated, the seriesTitle DOM element is updated', function() {
            const $seriesTitle = testView.$('#series-title-input');
            pubModel.set('seriesTitle', {id : 13, text : 'Series Title 13'});
            expect($seriesTitle.val()).toEqual('13');

            pubModel.unset('seriesTitle');
            expect($seriesTitle.val()).toBeNull();
        });

        it('Expects that if costCenters is updated, the DOM reflects the change', function() {
            const $costCenters = testView.$('#cost-centers-input');
            pubModel.set('costCenters', [{id : 4, text : 'CC 4'}, {id : 6, text : 'CC 6'}]);
            expect($costCenters.val()).toEqual(['4', '6']);

            pubModel.set('costCenters', [{id : 6, text : 'CC 6'}]);
            expect($costCenters.val()).toEqual(['6']);

            pubModel.set('costCenters', []);
            expect($costCenters.val()).toEqual([]);
        });

        it('Expects that if largerWork is updated, the DOM is updated and the largerSubType DOM is disabled as appropriate', function() {
            const $type = testView.$('#larger-work-type-input');
            const $subtype = testView.$('#larger-work-subtype-input');
            pubModel.set('largerWorkType', {id : 11, text : 'Type 11'});
            expect($type.val()).toEqual('11');
            expect($subtype.is(':disabled')).toBe(false);

            pubModel.unset('largerWorkType');
            expect($type.val()).toBeNull();
            expect($subtype.is(':disabled')).toBe(true);
        });

        it('Expects that if largerWorkSubtype is updated, the DOM is updated', function() {
            const $subtype = testView.$('#larger-work-subtype-input');
            pubModel.set('largerWorkSubtype', {id : 12, text : 'Subtype 12'});
            expect($subtype.val()).toEqual('12');

            pubModel.unset('largerWorkSubtype');
            expect($subtype.val()).toBeNull();
        });

        it('Expects that if docAbstract is updated, the DOM is updated', function() {
            const $abstract = testView.$('#docAbstract-input');
            pubModel.set('docAbstract', 'This is an abstract');
            expect($abstract.val()).toEqual('This is an abstract');

            pubModel.set('docAbstract', '');
            expect($abstract.val()).toEqual('');
        });

        it('Expects that if the tableOfContents is updated, the DOM is updated', function() {
            const $tableOfContents = testView.$('#tableOfContents-input');
            pubModel.set('tableOfContents', 'This is a table of contents');
            expect($tableOfContents.val()).toEqual('This is a table of contents');

            pubModel.set('tableOfContents', '');
            expect($tableOfContents.val()).toEqual('');
        });
    });
});
<commit_msg>Fixed a potential ordering issue in the tests.<commit_after>import $ from 'jquery';

import BibliodataView from '../../../../scripts/manager/views/BibliodataView';
import CostCenterCollection from '../../../../scripts/manager/models/CostCenterCollection';
import PublicationModel from '../../../../scripts/manager/models/PublicationModel';
import PublicationTypeCollection from '../../../../scripts/manager/models/PublicationTypeCollection';

describe('BibliodataView', function() {
    let pubTypeFetchDeferred, costCenterFetchActiveDeferred, costCenterFetchNotActiveDeferred;
    let pubModel;
    let testView;

    beforeEach(function() {
        $('body').append('

');

        pubModel = new PublicationModel();

        pubTypeFetchDeferred = $.Deferred();
        costCenterFetchActiveDeferred = $.Deferred();
        costCenterFetchNotActiveDeferred = $.Deferred();

        spyOn(window, 'setInterval');  // So the tinymce does not get initialized

        spyOn(PublicationTypeCollection.prototype, 'fetch').and.returnValue(pubTypeFetchDeferred);
        spyOn(CostCenterCollection.prototype, 'fetch').and.callFake(function(options) {
            if (options.data.active === 'y') {
                return costCenterFetchActiveDeferred;
            } else {
                return costCenterFetchNotActiveDeferred;
            }
        });
    });

    afterEach(function() {
        testView.remove();
        $('#test-div').remove();
    });

    it('Expects that the publicationType lookup values are fetched at initialization', function() {
        testView = new BibliodataView({
            model : pubModel,
            el : '#test-div'
        });

        expect(PublicationTypeCollection.prototype.fetch).toHaveBeenCalled();
    });

    it('Expects that the both the active and not active cost centers are fetched at initialization', function() {
        testView = new BibliodataView({
            model : pubModel,
            el : '#test-div'
        });

        expect(CostCenterCollection.prototype.fetch.calls.count()).toBe(2);
        expect(CostCenterCollection.prototype.fetch.calls.argsFor(0)[0].data.active).toEqual('y');
        expect(CostCenterCollection.prototype.fetch.calls.argsFor(1)[0].data.active).toEqual('n');
    });

    describe('Tests for render', function() {

        beforeEach(function() {
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });
            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2').and.callThrough();
        });

        it('Expects that stickit is initialized', function() {
            testView.render();
            expect(testView.stickit).toHaveBeenCalled();
        });

        it('Expects that select2\'s that do not preload their selections are initialized', function() {
            testView.render();
            expect($.fn.select2.calls.count()).toBe(3);
        });

        // TODO: figure out how to test select2's better. In particular I'd like to test setting up the new transport option
        // for the pub-subtype-input
        it('Expects that the publication type and larger work type input\'s are initialized when the publication type fetch is done', function() {
            let select2Count;
            testView.render();
            select2Count = $.fn.select2.calls.count();
            pubTypeFetchDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count + 2);
        });

        it('Expects that the costCenter select is initialized after both cost center fetches are complete', function() {
            let select2Count;
            testView.render();
            select2Count = $.fn.select2.calls.count();
            costCenterFetchActiveDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count);
            costCenterFetchNotActiveDeferred.resolve();
            expect($.fn.select2.calls.count()).toBe(select2Count + 1);
        });
    });

    describe('Test DOM event handling for the select2\'s', function() {
        let ev;

        beforeEach(function() {
            pubModel.set({
                publicationType : {id : 1, text : 'Type 1'},
                publicationSubtype : {id : 2, text : 'Subtype 2'},
                seriesTitle : {id : 3, text : 'Series Title 3'},
                costCenters : [{id : 4, text : 'CC 4'}, {id : 5, text : 'CC 5'}],
                largerWorkType : {id : 6, text : 'Type 6'},
                largerWorkSubtype : {id : 7, text : 'Subtype 7'}
            });
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });
            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2');

            testView.render();
        });

        it('Expects that when a pub type is selected, the publicationType is updated and the publicationSubtype and seriesTitle are unset', function() {
            ev = {
                currentTarget : {
                    value : 11,
                    selectedOptions : [{innerHTML : 'Type11'}]
                }
            };
            testView.selectPubType(ev);
            expect(pubModel.get('publicationType')).toEqual({id : 11, text : 'Type11'});
            expect(pubModel.get('publicationSubType')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub type is cleared, the publicationType, publicationSubtype, and seriesTitle are unset', function() {
            testView.resetPubType();
            expect(pubModel.get('publicationType')).toBeUndefined();
            expect(pubModel.get('publicationSubtype')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub subtype is selected, the publicationSubtype is updated and the seriesTitle is unset', function() {
            ev = {
                currentTarget : {
                    value : 12,
                    selectedOptions : [{innerHTML : 'Subtype 12'}]
                }
            };
            testView.selectPubSubtype(ev);
            expect(pubModel.get('publicationSubtype')).toEqual({id : 12, text : 'Subtype 12'});
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a pub subtype is cleared, the publicationSubtype and seriesTitle are unset', function() {
            testView.resetPubSubtype();
            expect(pubModel.get('publicationSubtype')).toBeUndefined();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects than when a series title is selected, the seriesTitle is updated', function() {
            ev = {
                currentTarget : {
                    value : 13,
                    selectedOptions : [{innerHTML : 'Series Title 13'}]
                }
            };
            testView.selectSeriesTitle(ev);
            expect(pubModel.get('seriesTitle')).toEqual({id : 13, text : 'Series Title 13'});
        });

        it('Expects that when a series title is cleared, the seriesTitle is unset', function() {
            testView.resetSeriesTitle();
            expect(pubModel.get('seriesTitle')).toBeUndefined();
        });

        it('Expects that when a cost center is selected, it is added to the current costCenters', function() {
            let costCenters;
            ev = {
                params : {
                    data : {id : 15, text : 'CC 15'}
                }
            };

            testView.selectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(3);
            expect(costCenters).toContain({id : 4, text : 'CC 4'});
            expect(costCenters).toContain({id : 5, text : 'CC 5'});
            expect(costCenters).toContain({id : 15, text : 'CC 15'});

            pubModel.unset('costCenters');
            testView.selectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(1);
            expect(costCenters).toContain({id : 15, text : 'CC 15'});
        });

        it('Expects that when a cost center is removed, costCenters is updated appropriately', function() {
            let costCenters;
            ev = {
                params : {
                    data : {id : 4, text : 'CC 4'}
                }
            };
            testView.unselectCostCenter(ev);
            costCenters = pubModel.get('costCenters');
            expect(costCenters.length).toBe(1);
            expect(costCenters).toEqual([{id : 5, text : 'CC 5'}]);
        });

        it('Expects that when a larger work type is selected, the largerWorkType is updated and the largerWorkSubtype is unset', function() {
            ev = {
                currentTarget : {
                    value : 20,
                    selectedOptions: [{innerHTML : 'Type 20'}]
                }
            };
            testView.selectLargerWorkType(ev);
            expect(pubModel.get('largerWorkType')).toEqual({id : 20, text : 'Type 20'});
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });

        it('Expects that when a larger work type is cleared, the largerWorkType  and largerWorkSubtype are unset', function() {
            testView.resetLargerWorkType();
            expect(pubModel.get('largerWorkType')).toBeUndefined();
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });

        it('Expects that when a larger work subtype is selected, the largerWorkSubtype is updated', function() {
            ev = {
                currentTarget : {
                    value : 20,
                    selectedOptions: [{innerHTML : 'Subtype 20'}]
                }
            };
            testView.selectLargerWorkSubtype(ev);
            expect(pubModel.get('largerWorkSubtype')).toEqual({id : 20, text : 'Subtype 20'});
        });

        it('Expects that when a larger work subtype is cleared, the largerWorkSubtype is unset', function() {
            testView.resetLargerWorkSubtype();
            expect(pubModel.get('largerWorkSubtype')).toBeUndefined();
        });
    });

    describe('Tests for model event listeners', function() {

        beforeEach(function() {
            pubModel.set({
                publicationType : {id : 1, text : 'Type 1'},
                publicationSubtype : {id : 2, text : 'Subtype 2'},
                seriesTitle : {id : 3, text : 'Series Title 3'},
                costCenters : [{id : 4, text : 'CC 4'}, {id : 5, text : 'CC 5'}],
                largerWorkType : {id : 6, text : 'Type 6'},
                largerWorkSubtype : {id : 7, text : 'Subtype 7'}
            });
            testView = new BibliodataView({
                model : pubModel,
                el : '#test-div'
            });

            spyOn(testView, 'stickit');
            spyOn($.fn, 'select2').and.callThrough();

            // For static select2's need to add options.
            testView.publicationTypeCollection.set([{id : 1, text : 'Type1'}, {id : 11, text : 'Type 11'}]);
            testView.activeCostCenters.set([{id : 4, text : 'CC 4'}, {id : 6, text : 'CC 6'}]);
            testView.notActiveCostCenters.set([{id : 5, text : 'CC 5'}]);

            pubTypeFetchDeferred.resolve();
            costCenterFetchActiveDeferred.resolve();
            costCenterFetchNotActiveDeferred.resolve();

            testView.render();
        });

        it('Expects that if publicationType is updated, the pubType DOM element is updated and the subtype DOM element is disabled when publicationType is unset', function() {
            const $type = testView.$('#pub-type-input');
            const $subtype = testView.$('#pub-subtype-input');
            pubModel.set('publicationType', {id : 11, text : 'Type 11'});
            expect($type.val()).toEqual('11');
            expect($subtype.is(':disabled')).toBe(false);

            pubModel.unset('publicationType');
            expect($type.val()).toBeNull();
            expect($subtype.is(':disabled')).toBe(true);
        });

        it('Expects that if publicationSubtype is updated, the pubSubtype DOM element is updated and the seriesTitle DOM element is disabled when there is no publicationSubtype', function() {
            const $subtype = testView.$('#pub-subtype-input');
            const $seriesTitle = testView.$('#series-title-input');
            pubModel.set('publicationSubtype', {id : 12, text : 'Subtype 12'});
            expect($subtype.val()).toEqual('12');
            expect($seriesTitle.is(':disabled')).toBe(false);

            pubModel.unset('publicationSubtype');
            expect($subtype.val()).toBeNull();
            expect($seriesTitle.is(':disabled')).toBe(true);
        });

        it('Expects that if seriesTitle is updated, the seriesTitle DOM element is updated', function() {
            const $seriesTitle = testView.$('#series-title-input');
            pubModel.set('seriesTitle', {id : 13, text : 'Series Title 13'});
            expect($seriesTitle.val()).toEqual('13');

            pubModel.unset('seriesTitle');
            expect($seriesTitle.val()).toBeNull();
        });

        it('Expects that if costCenters is updated, the DOM reflects the change', function() {
            const $costCenters = testView.$('#cost-centers-input');
            pubModel.set('costCenters', [{id : 4, text : 'CC 4'}, {id : 6, text : 'CC 6'}]);
            expect($costCenters.val()).toEqual(['4', '6']);

            pubModel.set('costCenters', [{id : 6, text : 'CC 6'}]);
            expect($costCenters.val()).toEqual(['6']);

            pubModel.set('costCenters', []);
            expect($costCenters.val()).toEqual([]);
        });

        it('Expects that if largerWork is updated, the DOM is updated and the largerSubType DOM is disabled as appropriate', function() {
            const $type = testView.$('#larger-work-type-input');
            const $subtype = testView.$('#larger-work-subtype-input');
            pubModel.set('largerWorkType', {id : 11, text : 'Type 11'});
            expect($type.val()).toEqual('11');
            expect($subtype.is(':disabled')).toBe(false);

            pubModel.unset('largerWorkType');
            expect($type.val()).toBeNull();
            expect($subtype.is(':disabled')).toBe(true);
        });

        it('Expects that if largerWorkSubtype is updated, the DOM is updated', function() {
            const $subtype = testView.$('#larger-work-subtype-input');
            pubModel.set('largerWorkSubtype', {id : 12, text : 'Subtype 12'});
            expect($subtype.val()).toEqual('12');

            pubModel.unset('largerWorkSubtype');
            expect($subtype.val()).toBeNull();
        });

        it('Expects that if docAbstract is updated, the DOM is updated', function() {
            const $abstract = testView.$('#docAbstract-input');
            pubModel.set('docAbstract', 'This is an abstract');
            expect($abstract.val()).toEqual('This is an abstract');

            pubModel.set('docAbstract', '');
            expect($abstract.val()).toEqual('');
        });

        it('Expects that if the tableOfContents is updated, the DOM is updated', function() {
            const $tableOfContents = testView.$('#tableOfContents-input');
            pubModel.set('tableOfContents', 'This is a table of contents');
            expect($tableOfContents.val()).toEqual('This is a table of contents');

            pubModel.set('tableOfContents', '');
            expect($tableOfContents.val()).toEqual('');
        });
    });
});
<|endoftext|>


<commit_before>// Load all tabs
const tabs = getElementsByClassName('hero-tab')
const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

// Preload images and randomly rotate
const fadeInTab = tabIndex => {
	// Fade in Hero Image
	tabs[tabIndex].classList.add('fade-in')
	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i], tabIndex)
			title.classList.add('fade-slide')
		}
	}, 500)
	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button', tabIndex)
		heroButton.classList.add('fade-slide')
	}, 800)
	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows', tabIndex)
		heroArrows.classList.add('fade-slide')
	}, 1100)
}

const resetSlide = tabIndex => {
	// Hide Hero Text
	for (let i = 0; i < 3; i++) {
		const title = getElementByClassName('hero-title ' + literalNumbers[i], tabIndex)
		title.classList.remove('fade-slide')
	}
	// Hide Hero Button
	const heroButton = getElementByClassName('hero-button', tabIndex)
	heroButton.classList.remove('fade-slide')
	// Hide Hero Arrows
	const heroArrows = getElementByClassName('hero-arrows', tabIndex)
	heroArrows.classList.remove('fade-slide')
}

// Begin
if (window.location.pathname === '/') {

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrows = getElementsByClassName('hero-arrow right')
	for (let tabIndex = 0; tabIndex < rightArrows.length; tabIndex++) {
		rightArrows[tabIndex].addEventListener('click', tabIndex => {
			// Get next image
			const nextTab = tabIndex === tabs.length - 1
				? 0
				: tabIndex + 1
			console.log(tabs)
			console.log(nextTab, tabIndex)
			// Deactivate current tab
			tabs[tabIndex].classList.add('fade-out')
			// Fade in new slide
			fadeInTab(nextTab)
			// Reset current slide
			resetSlide(tabIndex)
		})
	}

	// Fade in first slide
	fadeInTab(0)

}<commit_msg>Hero.<commit_after>// Load all tabs
const tabs = getElementsByClassName('hero-tab')
const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

// Preload images and randomly rotate
const fadeInTab = tabIndex => {
	// Fade in Hero Image
	tabs[tabIndex].classList.add('fade-in')
	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i], tabIndex)
			title.classList.add('fade-slide')
		}
	}, 500)
	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button', tabIndex)
		heroButton.classList.add('fade-slide')
	}, 800)
	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows', tabIndex)
		heroArrows.classList.add('fade-slide')
	}, 1100)
}

const resetSlide = tabIndex => {
	// Hide Hero Text
	for (let i = 0; i < 3; i++) {
		const title = getElementByClassName('hero-title ' + literalNumbers[i], tabIndex)
		title.classList.remove('fade-slide')
	}
	// Hide Hero Button
	const heroButton = getElementByClassName('hero-button', tabIndex)
	heroButton.classList.remove('fade-slide')
	// Hide Hero Arrows
	const heroArrows = getElementByClassName('hero-arrows', tabIndex)
	heroArrows.classList.remove('fade-slide')
}

// Begin
if (window.location.pathname === '/') {

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrows = getElementsByClassName('hero-arrow right')
	for (let tabIndex = 0; tabIndex < rightArrows.length; tabIndex++) {
		rightArrows[tabIndex].addEventListener('click', tabIndex => {
			// Get next image
			const nextTabIndex = tabIndex === tabs.length - 1
				? 0
				: tabIndex + 1
			console.log(tabs)
			console.log(nextTabIndex, tabIndex)
			// Deactivate current tab
			tabs[tabIndex].classList.add('fade-out')
			// Fade in new slide
			fadeInTab(nextTabIndex)
			// Reset current slide
			resetSlide(tabIndex)
		})
	}

	// Fade in first slide
	fadeInTab(0)

}<|endoftext|>


<commit_before>/* Copyright 2012 The Go Authors.   All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
'use strict';

angular.module('tour.values', []).

// List of modules with description and lessons in it.
value('tableOfContents', [{
    'id': 'mechanics',
    'title': 'Using the tour',
    'description': '
Welcome to a tour of the Go programming language. The tour covers the most important features of the language, mainly:
',
    'lessons': ['welcome']
}, {
    'id': 'basics',
    'title': 'Basics',
    'description': '
The starting point, learn all the basics of the language.

Declaring variables, calling functions, and all the things you need to know before moving to the next lessons.
',
    'lessons': ['basics', 'flowcontrol', 'moretypes']
}, {
    'id': 'methods',
    'title': 'Methods and interfaces',
    'description': '
Learn how to define methods on types, how to declare interfaces, and how to put everything together.
',
    'lessons': ['methods']
}, {
    'id': 'concurrency',
    'title': 'Concurrency',
    'description': '
Go provides concurrency features as part of the core language.

This module goes over goroutines and channels, and how they are used to implement different concurrency patterns.
',
    'lessons': ['concurrency']
}]).

// translation
value('translation', {
    'off': 'off',
    'on': 'on',
    'syntax': 'Syntax-Highlighting',
    'lineno': 'Line-Numbers',
    'reset': 'Reset Slide',
    'format': 'Format Source Code',
    'kill': 'Kill Program',
    'run': 'Run',
    'compile': 'Compile and Run',
    'more': 'Options',
    'toc': 'Table of Contents',
    'prev': 'Previous',
    'next': 'Next',
    'waiting': 'Waiting for remote server...',
    'errcomm': 'Error communicating with remote server.',
    'submit-feedback': 'Send feedback about this page',

    // GitHub issue template: update repo and messaging when translating.
    'github-repo': 'github.com/golang/go',
    'issue-title': 'tour: [short description of the issue]',
    'issue-message': 'Describe your feedback here, including code if necessary',
    'context': 'Context',
}).

// Config for codemirror plugin
value('ui.config', {
    codemirror: {
        mode: 'text/x-go',
        matchBrackets: true,
        lineNumbers: true,
        autofocus: true,
        indentWithTabs: true,
        indentUnit: 4,
        tabSize: 4,
        lineWrapping: true,
        extraKeys: {
            'Shift-Enter': function() {
                $('#run').click();
            },
            'Ctrl-Enter': function() {
                $('#format').click();
            },
            'PageDown': function() {
                return false;
            },
            'PageUp': function() {
                return false;
            },
        },
        // TODO: is there a better way to do this?
        // AngularJS values can't depend on factories.
        onChange: function() {
            if (window.codeChanged !== null) window.codeChanged();
        }
    }
});
<commit_msg>[x/tour] tour: make bug template more descriptive<commit_after>/* Copyright 2012 The Go Authors.   All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */
'use strict';

angular.module('tour.values', []).

// List of modules with description and lessons in it.
value('tableOfContents', [{
    'id': 'mechanics',
    'title': 'Using the tour',
    'description': '
Welcome to a tour of the Go programming language. The tour covers the most important features of the language, mainly:
',
    'lessons': ['welcome']
}, {
    'id': 'basics',
    'title': 'Basics',
    'description': '
The starting point, learn all the basics of the language.

Declaring variables, calling functions, and all the things you need to know before moving to the next lessons.
',
    'lessons': ['basics', 'flowcontrol', 'moretypes']
}, {
    'id': 'methods',
    'title': 'Methods and interfaces',
    'description': '
Learn how to define methods on types, how to declare interfaces, and how to put everything together.
',
    'lessons': ['methods']
}, {
    'id': 'concurrency',
    'title': 'Concurrency',
    'description': '
Go provides concurrency features as part of the core language.

This module goes over goroutines and channels, and how they are used to implement different concurrency patterns.
',
    'lessons': ['concurrency']
}]).

// translation
value('translation', {
    'off': 'off',
    'on': 'on',
    'syntax': 'Syntax-Highlighting',
    'lineno': 'Line-Numbers',
    'reset': 'Reset Slide',
    'format': 'Format Source Code',
    'kill': 'Kill Program',
    'run': 'Run',
    'compile': 'Compile and Run',
    'more': 'Options',
    'toc': 'Table of Contents',
    'prev': 'Previous',
    'next': 'Next',
    'waiting': 'Waiting for remote server...',
    'errcomm': 'Error communicating with remote server.',
    'submit-feedback': 'Send feedback about this page',

    // GitHub issue template: update repo and messaging when translating.
    'github-repo': 'github.com/golang/go',
    'issue-title': 'tour: [REPLACE WITH SHORT DESCRIPTION]',
    'issue-message': 'Change the title above to describe your issue and add your feedback here, including code if necessary',
    'context': 'Context',
}).

// Config for codemirror plugin
value('ui.config', {
    codemirror: {
        mode: 'text/x-go',
        matchBrackets: true,
        lineNumbers: true,
        autofocus: true,
        indentWithTabs: true,
        indentUnit: 4,
        tabSize: 4,
        lineWrapping: true,
        extraKeys: {
            'Shift-Enter': function() {
                $('#run').click();
            },
            'Ctrl-Enter': function() {
                $('#format').click();
            },
            'PageDown': function() {
                return false;
            },
            'PageUp': function() {
                return false;
            },
        },
        // TODO: is there a better way to do this?
        // AngularJS values can't depend on factories.
        onChange: function() {
            if (window.codeChanged !== null) window.codeChanged();
        }
    }
});
<|endoftext|>


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

    var ImgFit = function() {
        this.settings = {
            style: {
                container: {
                    position: "relative",
                    overflow: "hidden"
                },

                image: {
                    position: "absolute",
                    top: 0,
                    left: 0,
                    opacity: 0,
                    width: "100%",
                    height: "auto"
                },

                transition: {
                    transition: "opacity .2s linear"
                }
            }
        };
    };

    ImgFit.prototype.getPrefix = function() {
        var style = window.getComputedStyle(document.documentElement),
            match = Array.prototype.join.call(style, "").match(/-(?:o|moz|webkit|ms)-/i);

        return match && match[0];
    };

    ImgFit.prototype.getStyle = function(element) {
        var tempStyle = element.getAttribute("style");

        if(tempStyle) {
            var currentStyle = tempStyle.split("; "),
                i = 0, length = currentStyle.length,
                temp;

            tempStyle = {};

            for( ; i < length; i++) {
                temp = currentStyle[i].split(": ");

                tempStyle[temp[0]] = temp[1];
            }
        }

        return tempStyle || {};
    };

    ImgFit.prototype.setStyle = function(element, style) {
        var i, margin,
            currentStyle = this.getStyle(element),
            tempStyle = [];

        for(i in style) {
            if(i === "transition") {
                var prefixTrans = this.prefix + i;

                style[prefixTrans] = style[i];

                delete style[i];

                i = prefixTrans;
            }

            if(currentStyle[i])
                delete currentStyle[i];

            currentStyle[i] = style[i];
        }

        for(i in currentStyle) {
            margin = i.split("margin");

            tempStyle.push((margin.length > 1 ? "margin-"+ margin[1].toLowerCase() : i) +": "+ currentStyle[i]);
        }

        element.setAttribute("style", tempStyle.join("; "));
    };

    ImgFit.prototype.setPosition = function(container, image) {
        if(image.offsetHeight === 0) {
            var self = this;

            setTimeout(function() {
                self.setPosition(container, image);
            }, 100);
        }
        else {
            if(image.offsetWidth / image.offsetHeight <= container.offsetWidth / container.offsetHeight) {
                this.setStyle(image, {
                    top: "50%",
                    opacity: 1,
                    marginTop: -image.offsetHeight / 2 + "px"
                });
            }
            else {
                this.setStyle(image, {
                    left: "50%",
                    opacity: 1,
                    width: "auto",
                    height: "100%"
                });

                image.style.marginLeft = -image.offsetWidth / 2 + "px";
            }
        }
    };

    ImgFit.prototype.fit = function(container) {
        var self = this,
            image = container.children[0];

        this.setStyle(container, this.settings.style.container);
        this.setStyle(image, this.settings.style.image);

        setTimeout(function() {
            self.setStyle(image, self.settings.style.transition);

            if(image.offsetWidth > 0 && image.offsetWidth === container.offsetWidth)
                self.setPosition(container, image);

            image.onload = function() {
                self.setPosition(container, image);
            };
        });
    };

    ImgFit.prototype.init = function(target) {
        this.prefix = this.getPrefix();

        var img = document.getElementsByClassName(target),
            i = 0, length = img.length;

        for( ; i < length; i++)
            this.fit(img[i]);
    };

    window.imgFit = new ImgFit();
})();

<commit_msg>Fix: pre-computed margin-left<commit_after>(function() {
    "use strict";

    var ImgFit = function() {
        this.settings = {
            style: {
                container: {
                    position: "relative",
                    overflow: "hidden"
                },

                image: {
                    position: "absolute",
                    top: 0,
                    left: 0,
                    opacity: 0,
                    width: "100%",
                    height: "auto"
                },

                transition: {
                    transition: "opacity .2s linear"
                }
            }
        };
    };

    ImgFit.prototype.getPrefix = function() {
        var style = window.getComputedStyle(document.documentElement),
            match = Array.prototype.join.call(style, "").match(/-(?:o|moz|webkit|ms)-/i);

        return match && match[0];
    };

    ImgFit.prototype.getStyle = function(element) {
        var tempStyle = element.getAttribute("style");

        if(tempStyle) {
            var currentStyle = tempStyle.split("; "),
                i = 0, length = currentStyle.length,
                temp;

            tempStyle = {};

            for( ; i < length; i++) {
                temp = currentStyle[i].split(": ");

                tempStyle[temp[0]] = temp[1];
            }
        }

        return tempStyle || {};
    };

    ImgFit.prototype.setStyle = function(element, style) {
        var i, margin,
            currentStyle = this.getStyle(element),
            tempStyle = [];

        for(i in style) {
            if(i === "transition") {
                var prefixTrans = this.prefix + i;

                style[prefixTrans] = style[i];

                delete style[i];

                i = prefixTrans;
            }

            if(currentStyle[i])
                delete currentStyle[i];

            currentStyle[i] = style[i];
        }

        for(i in currentStyle) {
            margin = i.split("margin");

            tempStyle.push((margin.length > 1 ? "margin-"+ margin[1].toLowerCase() : i) +": "+ currentStyle[i]);
        }

        element.setAttribute("style", tempStyle.join("; "));
    };

    ImgFit.prototype.setPosition = function(container, image) {
        if(image.offsetHeight === 0) {
            var self = this;

            setTimeout(function() {
                self.setPosition(container, image);
            }, 100);
        }
        else {
            if(image.offsetWidth / image.offsetHeight <= container.offsetWidth / container.offsetHeight) {
                this.setStyle(image, {
                    top: "50%",
                    opacity: 1,
                    marginTop: -image.offsetHeight / 2 +"px"
                });
            }
            else {
                this.setStyle(image, {
                    left: "50%",
                    opacity: 1,
                    width: "auto",
                    height: "100%",
                    marginLeft: -(container.offsetHeight * image.offsetWidth / image.offsetHeight) / 2 +"px"
                });
            }
        }
    };

    ImgFit.prototype.fit = function(container) {
        var self = this,
            image = container.children[0];

        this.setStyle(container, this.settings.style.container);
        this.setStyle(image, this.settings.style.image);

        setTimeout(function() {
            self.setStyle(image, self.settings.style.transition);

            if(image.offsetWidth > 0 && image.offsetWidth === container.offsetWidth)
                self.setPosition(container, image);

            image.onload = function() {
                self.setPosition(container, image);
            };
        });
    };

    ImgFit.prototype.init = function(target) {
        this.prefix = this.getPrefix();

        var img = document.getElementsByClassName(target),
            i = 0, length = img.length;

        for( ; i < length; i++)
            this.fit(img[i]);
    };

    window.imgFit = new ImgFit();
})();
<|endoftext|>


<commit_before>var MapModule = require("./map_module");
var indoors = require("../public/indoors/indoors");
var IndoorWatermarkController = require("./indoor_watermark_controller");

var IndoorsModule = function(emscriptenApi, mapController, mapId, indoorId, floorIndex) {

    var _emscriptenApi = emscriptenApi;
    var _mapController = mapController;

    var _activeIndoorMap = null;
    var _entrances = {};

    var _ready = false;
    var _pendingEnterTransition = null;
    var _transitioningToIndoorMap = false;

    var _indoorWatermarkController = new IndoorWatermarkController(mapId);

    var _startingIndoorId = indoorId;
    var _startingFloorIndex = floorIndex;

    var _this = this;

    var _createIndoorMapObject = function() {
        var mapId = _emscriptenApi.indoorsApi.getActiveIndoorMapId();
        var mapName = _emscriptenApi.indoorsApi.getActiveIndoorMapName();
        var sourceVendor = _emscriptenApi.indoorsApi.getActiveIndoorMapSourceVendor();
        var floorCount = _emscriptenApi.indoorsApi.getActiveIndoorMapFloorCount();
        var floors = _createFloorsArray(floorCount);
        var searchTags = _createSearchTagsArray();
        var exitFunc = _this.exit;
        var indoorMap = new indoors.IndoorMap(mapId, mapName, sourceVendor, floorCount, floors, searchTags, exitFunc);
        return indoorMap;
    };

    var _createFloorsArray = function(floorCount) {
        var floors = [];
        for (var i=0; i<floorCount; ++i) {
            var floorIndex = i;
            var floorName = _emscriptenApi.indoorsApi.getFloorName(i);
            var floorShortName = _emscriptenApi.indoorsApi.getFloorShortName(i);
            var floorNumber = _emscriptenApi.indoorsApi.getFloorNumber(i);

            var floorId = floorNumber;

            var floor = new indoors.IndoorMapFloor(floorId, floorIndex, floorName, floorShortName);
            floors.push(floor);
        }
        return floors;
    };

    var _createSearchTagsArray = function() {
        var userData;
        try {
            userData = JSON.parse(_emscriptenApi.indoorsApi.getActiveIndoorMapUserData());
        }
        catch (e) {
            return [];
        }

        if (typeof userData.search_menu_items !== "object") { return []; }
        if (!(userData.search_menu_items.items instanceof Array)) { return []; }

        var searchTags = [];
        userData.search_menu_items.items.forEach(function(item) {
            searchTags.push({
                name: item.name,
                search_tag: item.search_tag,
                icon_key: item.icon_key
            });
        });
        return searchTags;
    };

    var _executeIndoorMapEnteredCallbacks = function() {
        _activeIndoorMap = _createIndoorMapObject();
        _this.fire("indoormapenter", {indoorMap: _activeIndoorMap});
    };

    var _executeIndoorMapExitedCallbacks = function() {
        var indoorMap = _activeIndoorMap;
        _activeIndoorMap = null;
        _this.fire("indoormapexit", {indoorMap: indoorMap});
    };

    var _executeIndoorMapFloorChangedCallbacks = function() {
        _this.fire("indoormapfloorchange", {floor: _this.getFloor()});
    };

    var _executeIndoorMapEntranceAddedCallbacks = function(indoorMapId, indoorMapName, indoorMapLatLng) {
        // discard the altitude, as we're going to use the SDK IPointOnMap positioning to snap it to the terrain (this is now default)
        // alternative is to use the altitude, but use "elevationMode: heightAboveSeaLevel" when creating the indoor entrance marker
        var entrance = new indoors.IndoorMapEntrance(indoorMapId, indoorMapName, L.latLng([indoorMapLatLng.lat, indoorMapLatLng.lng]));
        _entrances[entrance.getIndoorMapId()] = entrance;
        _this.fire("indoorentranceadd", {entrance: entrance});
    };

    var _executeIndoorMapEntranceRemovedCallbacks = function(indoorMapId, indoorMapName, indoorMapLatLng) {
        var entrance = new indoors.IndoorMapEntrance(indoorMapId, indoorMapName, indoorMapLatLng);
        delete _entrances[entrance.getIndoorMapId()];
        _this.fire("indoorentranceremove", {entrance: entrance});
    };

    var _executeEntityClickedCallbacks = function(ids) {
        var idArray = ids.split("|");
        _this.fire("indoorentityclick", {ids: idArray});
    };

    var _onCollapseStart = function() {
        _this.fire("collapsestart");
    };

    var _onCollapse = function() {
        _this.fire("collapse");
    };

    var _onCollapseEnd = function() {
        _this.fire("collapseend");
    };

    var _onExpandStart = function() {
        _this.fire("expandstart");
    };

    var _onExpand = function() {
        _this.fire("expand");
    };

    var _onExpandEnd = function() {
        _this.fire("expandend");
    };

    var _enterIndoorMap = function(indoorMapId) {
        _emscriptenApi.indoorsApi.enterIndoorMap(indoorMapId);
    };

    var _transitionToIndoorMap = function(config) {

        _transitioningToIndoorMap = true;

        if (!_ready) {
            _pendingEnterTransition = config;
            return;
        }

        _emscriptenApi.cameraApi.setView({location: config.latLng, distance: config.distance, allowInterruption: false, headingDegrees: 0});
        _mapController._setIndoorTransitionCompleteEventListener(function() { _enterIndoorMap(config.indoorMapId); });

        _this.once("indoormapenter", function() {
            _transitioningToIndoorMap = false;
            var vendorKey = _activeIndoorMap.getIndoorMapSourceVendor();
            _indoorWatermarkController.showWatermarkForVendor(vendorKey);
        });
    };

    this.onInitialized = function() {
        _emscriptenApi.indoorsApi.registerIndoorMapEnteredCallback(_executeIndoorMapEnteredCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapExitedCallback(_executeIndoorMapExitedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapFloorChangedCallback(_executeIndoorMapFloorChangedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapMarkerAddedCallback(_executeIndoorMapEntranceAddedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapMarkerRemovedCallback(_executeIndoorMapEntranceRemovedCallbacks);
        _emscriptenApi.highlightApi.registerEntityClickedCallback(_executeEntityClickedCallbacks);

        _emscriptenApi.expandFloorsApi.setCollapseStartCallback(_onCollapseStart);
        _emscriptenApi.expandFloorsApi.setCollapseCallback(_onCollapse);
        _emscriptenApi.expandFloorsApi.setCollapseEndCallback(_onCollapseEnd);
        _emscriptenApi.expandFloorsApi.setExpandStartCallback(_onExpandStart);
        _emscriptenApi.expandFloorsApi.setExpandCallback(_onExpand);
        _emscriptenApi.expandFloorsApi.setExpandEndCallback(_onExpandEnd);
    };

    this.onInitialStreamingCompleted = function() {
        _ready = true;

        if(_startingIndoorId)
        {
            var foundIndoorMap = this.enter(_startingIndoorId);

            if(foundIndoorMap === false)
            {
                console.error('Failed to enter indoor map. Please check your indoor Id is correct and the starting location is the same as your indoor map.');
            }

            if(_startingFloorIndex)
            {
                this.once("indoormapenter", function() { this.setFloor(_startingFloorIndex); });
            }
        }

        if (_pendingEnterTransition !== null) {
            _transitionToIndoorMap(_pendingEnterTransition);
            _pendingEnterTransition = null;
        }
    };

    this.exit = function() {
        if (_emscriptenApi.ready()) {
            _emscriptenApi.indoorsApi.exitIndoorMap();
            _indoorWatermarkController.hideWatermark();
        }
        _pendingEnterTransition = null;
        return this;
    };

    this.isIndoors = function() {
        return _activeIndoorMap !== null;
    };

    this.getActiveIndoorMap = function() {
        return _activeIndoorMap;
    };

    this.getFloor = function() {
        if (this.isIndoors()) {
            var index = _emscriptenApi.indoorsApi.getSelectedFloorIndex();
            return _activeIndoorMap.getFloors()[index];
        }
        return null;
    };

    this.setFloor = function(floor) {
        if (!this.isIndoors()) {
            return false;
        }

        var index = null;
        var floors = _activeIndoorMap.getFloors();

        if (typeof floor === "number") {
            index = floor;
        }
        else if (typeof floor === "object") {
            var floorIndex = floors.indexOf(floor);
            index = (floorIndex >= 0) ? floorIndex : null;
        }
        else if (typeof floor === "string") {
            for (var i=0; i<floors.length; ++i) {
                if (floors[i].getFloorShortName() === floor) {
                    index = i;
                    break;
                }
            }
        }

        if (index !== null) {
            return _emscriptenApi.indoorsApi.setSelectedFloorIndex(index);
        }

        return false;
    };

    this.moveUp = function(numberOfFloors) {
        var delta = (typeof numberOfFloors === "undefined") ? 1 : numberOfFloors;
        var thisFloor = this.getFloor();
        if (thisFloor === null) {
            return false;
        }
        return this.setFloor(thisFloor.getFloorIndex() + delta);
    };

    this.moveDown = function(numberOfFloors) {
        var delta = (typeof numberOfFloors === "undefined") ? -1 : -numberOfFloors;
        return this.moveUp(delta);
    };

    this.enter = function(indoorMap) {
        if (this.isIndoors() || _transitioningToIndoorMap) {
            return false;
        }

        var indoorMapId = null;
        if (typeof indoorMap === "object" && "getIndoorMapId" in indoorMap && typeof indoorMap["getIndoorMapId"] === "function") {
            indoorMapId = indoorMap.getIndoorMapId();
        }
        else if (typeof indoorMap === "string") {
            indoorMapId = indoorMap;
        }

        var entrance = _entrances[indoorMapId] || null;
        if (entrance === null) {
            return false;
        }

        var latLng = entrance.getLatLng();
        var distance = 400;

        var enterConfig = {
            latLng: latLng,
            distance: distance,
            indoorMapId: indoorMapId
        };

        _transitionToIndoorMap(enterConfig);

        return true;
    };

    this.getFloorInterpolation = function() {
        if (_activeIndoorMap !== null) {
            var floorParam = _emscriptenApi.expandFloorsApi.getFloorParam();
            var normalizedValue = floorParam / _activeIndoorMap.getFloorCount();
            return normalizedValue;
        }
        return 0;
    };

    this.getFloorHeightAboveSeaLevel = function(floorIndex) {
        if (this.isIndoors() &&
            floorIndex >= 0 &&
            floorIndex < _activeIndoorMap.getFloorCount())
        {
            return _emscriptenApi.indoorsApi.getFloorHeightAboveSeaLevel(floorIndex);
        }

        return null;
    };

    this.setFloorInterpolation = function(value) {
        if (_activeIndoorMap !== null) {
            var floorParam = value * _activeIndoorMap.getFloorCount();
            _emscriptenApi.expandFloorsApi.setFloorParam(floorParam);
        }
        return this;
    };

    this.setFloorFromInterpolation = function(interpolationParam) {
        if (_activeIndoorMap === null) {
            return false;
        }

        var t = (typeof interpolationParam === "undefined") ? this.getFloorInterpolation() : interpolationParam;
        var floorIndex = Math.round(t * _activeIndoorMap.getFloorCount());
        return this.setFloor(floorIndex);
    };

    this.expand = function() {
        _emscriptenApi.expandFloorsApi.expandIndoorMap();
        return this;
    };

    this.collapse = function() {
        _emscriptenApi.expandFloorsApi.collapseIndoorMap();
        return this;
    };

    this.setEntityHighlights = function(ids, color) {
        if (!_ready) return;
        _emscriptenApi.highlightApi.setEntityHighlights(ids, color);
    };

    this.clearEntityHighlights = function(ids) {
        if (!_ready) return;
        _emscriptenApi.highlightApi.clearEntityHighlights(ids);
    };
};

var IndoorsPrototype = L.extend({}, MapModule, L.Mixin.Events);

IndoorsModule.prototype = IndoorsPrototype;

module.exports = IndoorsModule;<commit_msg>temp fix red build - failing linting Buddy: Malcolm<commit_after>var MapModule = require("./map_module");
var indoors = require("../public/indoors/indoors");
var IndoorWatermarkController = require("./indoor_watermark_controller");

var IndoorsModule = function(emscriptenApi, mapController, mapId, indoorId, floorIndex) {

    var _emscriptenApi = emscriptenApi;
    var _mapController = mapController;

    var _activeIndoorMap = null;
    var _entrances = {};

    var _ready = false;
    var _pendingEnterTransition = null;
    var _transitioningToIndoorMap = false;

    var _indoorWatermarkController = new IndoorWatermarkController(mapId);

    var _startingIndoorId = indoorId;
    var _startingFloorIndex = floorIndex;

    var _this = this;

    var _createIndoorMapObject = function() {
        var mapId = _emscriptenApi.indoorsApi.getActiveIndoorMapId();
        var mapName = _emscriptenApi.indoorsApi.getActiveIndoorMapName();
        var sourceVendor = _emscriptenApi.indoorsApi.getActiveIndoorMapSourceVendor();
        var floorCount = _emscriptenApi.indoorsApi.getActiveIndoorMapFloorCount();
        var floors = _createFloorsArray(floorCount);
        var searchTags = _createSearchTagsArray();
        var exitFunc = _this.exit;
        var indoorMap = new indoors.IndoorMap(mapId, mapName, sourceVendor, floorCount, floors, searchTags, exitFunc);
        return indoorMap;
    };

    var _createFloorsArray = function(floorCount) {
        var floors = [];
        for (var i=0; i<floorCount; ++i) {
            var floorIndex = i;
            var floorName = _emscriptenApi.indoorsApi.getFloorName(i);
            var floorShortName = _emscriptenApi.indoorsApi.getFloorShortName(i);
            var floorNumber = _emscriptenApi.indoorsApi.getFloorNumber(i);

            var floorId = floorNumber;

            var floor = new indoors.IndoorMapFloor(floorId, floorIndex, floorName, floorShortName);
            floors.push(floor);
        }
        return floors;
    };

    var _createSearchTagsArray = function() {
        var userData;
        try {
            userData = JSON.parse(_emscriptenApi.indoorsApi.getActiveIndoorMapUserData());
        }
        catch (e) {
            return [];
        }

        if (typeof userData.search_menu_items !== "object") { return []; }
        if (!(userData.search_menu_items.items instanceof Array)) { return []; }

        var searchTags = [];
        userData.search_menu_items.items.forEach(function(item) {
            searchTags.push({
                name: item.name,
                search_tag: item.search_tag,
                icon_key: item.icon_key
            });
        });
        return searchTags;
    };

    var _executeIndoorMapEnteredCallbacks = function() {
        _activeIndoorMap = _createIndoorMapObject();
        _this.fire("indoormapenter", {indoorMap: _activeIndoorMap});
    };

    var _executeIndoorMapExitedCallbacks = function() {
        var indoorMap = _activeIndoorMap;
        _activeIndoorMap = null;
        _this.fire("indoormapexit", {indoorMap: indoorMap});
    };

    var _executeIndoorMapFloorChangedCallbacks = function() {
        _this.fire("indoormapfloorchange", {floor: _this.getFloor()});
    };

    var _executeIndoorMapEntranceAddedCallbacks = function(indoorMapId, indoorMapName, indoorMapLatLng) {
        // discard the altitude, as we're going to use the SDK IPointOnMap positioning to snap it to the terrain (this is now default)
        // alternative is to use the altitude, but use "elevationMode: heightAboveSeaLevel" when creating the indoor entrance marker
        var entrance = new indoors.IndoorMapEntrance(indoorMapId, indoorMapName, L.latLng([indoorMapLatLng.lat, indoorMapLatLng.lng]));
        _entrances[entrance.getIndoorMapId()] = entrance;
        _this.fire("indoorentranceadd", {entrance: entrance});
    };

    var _executeIndoorMapEntranceRemovedCallbacks = function(indoorMapId, indoorMapName, indoorMapLatLng) {
        var entrance = new indoors.IndoorMapEntrance(indoorMapId, indoorMapName, indoorMapLatLng);
        delete _entrances[entrance.getIndoorMapId()];
        _this.fire("indoorentranceremove", {entrance: entrance});
    };

    var _executeEntityClickedCallbacks = function(ids) {
        var idArray = ids.split("|");
        _this.fire("indoorentityclick", {ids: idArray});
    };

    var _onCollapseStart = function() {
        _this.fire("collapsestart");
    };

    var _onCollapse = function() {
        _this.fire("collapse");
    };

    var _onCollapseEnd = function() {
        _this.fire("collapseend");
    };

    var _onExpandStart = function() {
        _this.fire("expandstart");
    };

    var _onExpand = function() {
        _this.fire("expand");
    };

    var _onExpandEnd = function() {
        _this.fire("expandend");
    };

    var _enterIndoorMap = function(indoorMapId) {
        _emscriptenApi.indoorsApi.enterIndoorMap(indoorMapId);
    };

    var _transitionToIndoorMap = function(config) {

        _transitioningToIndoorMap = true;

        if (!_ready) {
            _pendingEnterTransition = config;
            return;
        }

        _emscriptenApi.cameraApi.setView({location: config.latLng, distance: config.distance, allowInterruption: false, headingDegrees: 0});
        _mapController._setIndoorTransitionCompleteEventListener(function() { _enterIndoorMap(config.indoorMapId); });

        _this.once("indoormapenter", function() {
            _transitioningToIndoorMap = false;
            var vendorKey = _activeIndoorMap.getIndoorMapSourceVendor();
            _indoorWatermarkController.showWatermarkForVendor(vendorKey);
        });
    };

    this.onInitialized = function() {
        _emscriptenApi.indoorsApi.registerIndoorMapEnteredCallback(_executeIndoorMapEnteredCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapExitedCallback(_executeIndoorMapExitedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapFloorChangedCallback(_executeIndoorMapFloorChangedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapMarkerAddedCallback(_executeIndoorMapEntranceAddedCallbacks);
        _emscriptenApi.indoorsApi.registerIndoorMapMarkerRemovedCallback(_executeIndoorMapEntranceRemovedCallbacks);
        _emscriptenApi.highlightApi.registerEntityClickedCallback(_executeEntityClickedCallbacks);

        _emscriptenApi.expandFloorsApi.setCollapseStartCallback(_onCollapseStart);
        _emscriptenApi.expandFloorsApi.setCollapseCallback(_onCollapse);
        _emscriptenApi.expandFloorsApi.setCollapseEndCallback(_onCollapseEnd);
        _emscriptenApi.expandFloorsApi.setExpandStartCallback(_onExpandStart);
        _emscriptenApi.expandFloorsApi.setExpandCallback(_onExpand);
        _emscriptenApi.expandFloorsApi.setExpandEndCallback(_onExpandEnd);
    };

    this.onInitialStreamingCompleted = function() {
        _ready = true;

        if(_startingIndoorId)
        {
            var foundIndoorMap = this.enter(_startingIndoorId);

            if(foundIndoorMap === false)
            {
                // todo - this failing lint
                //console.error('Failed to enter indoor map. Please check your indoor Id is correct and the starting location is the same as your indoor map.');
            }

            if(_startingFloorIndex)
            {
                this.once("indoormapenter", function() { this.setFloor(_startingFloorIndex); });
            }
        }

        if (_pendingEnterTransition !== null) {
            _transitionToIndoorMap(_pendingEnterTransition);
            _pendingEnterTransition = null;
        }
    };

    this.exit = function() {
        if (_emscriptenApi.ready()) {
            _emscriptenApi.indoorsApi.exitIndoorMap();
            _indoorWatermarkController.hideWatermark();
        }
        _pendingEnterTransition = null;
        return this;
    };

    this.isIndoors = function() {
        return _activeIndoorMap !== null;
    };

    this.getActiveIndoorMap = function() {
        return _activeIndoorMap;
    };

    this.getFloor = function() {
        if (this.isIndoors()) {
            var index = _emscriptenApi.indoorsApi.getSelectedFloorIndex();
            return _activeIndoorMap.getFloors()[index];
        }
        return null;
    };

    this.setFloor = function(floor) {
        if (!this.isIndoors()) {
            return false;
        }

        var index = null;
        var floors = _activeIndoorMap.getFloors();

        if (typeof floor === "number") {
            index = floor;
        }
        else if (typeof floor === "object") {
            var floorIndex = floors.indexOf(floor);
            index = (floorIndex >= 0) ? floorIndex : null;
        }
        else if (typeof floor === "string") {
            for (var i=0; i<floors.length; ++i) {
                if (floors[i].getFloorShortName() === floor) {
                    index = i;
                    break;
                }
            }
        }

        if (index !== null) {
            return _emscriptenApi.indoorsApi.setSelectedFloorIndex(index);
        }

        return false;
    };

    this.moveUp = function(numberOfFloors) {
        var delta = (typeof numberOfFloors === "undefined") ? 1 : numberOfFloors;
        var thisFloor = this.getFloor();
        if (thisFloor === null) {
            return false;
        }
        return this.setFloor(thisFloor.getFloorIndex() + delta);
    };

    this.moveDown = function(numberOfFloors) {
        var delta = (typeof numberOfFloors === "undefined") ? -1 : -numberOfFloors;
        return this.moveUp(delta);
    };

    this.enter = function(indoorMap) {
        if (this.isIndoors() || _transitioningToIndoorMap) {
            return false;
        }

        var indoorMapId = null;
        if (typeof indoorMap === "object" && "getIndoorMapId" in indoorMap && typeof indoorMap["getIndoorMapId"] === "function") {
            indoorMapId = indoorMap.getIndoorMapId();
        }
        else if (typeof indoorMap === "string") {
            indoorMapId = indoorMap;
        }

        var entrance = _entrances[indoorMapId] || null;
        if (entrance === null) {
            return false;
        }

        var latLng = entrance.getLatLng();
        var distance = 400;

        var enterConfig = {
            latLng: latLng,
            distance: distance,
            indoorMapId: indoorMapId
        };

        _transitionToIndoorMap(enterConfig);

        return true;
    };

    this.getFloorInterpolation = function() {
        if (_activeIndoorMap !== null) {
            var floorParam = _emscriptenApi.expandFloorsApi.getFloorParam();
            var normalizedValue = floorParam / _activeIndoorMap.getFloorCount();
            return normalizedValue;
        }
        return 0;
    };

    this.getFloorHeightAboveSeaLevel = function(floorIndex) {
        if (this.isIndoors() &&
            floorIndex >= 0 &&
            floorIndex < _activeIndoorMap.getFloorCount())
        {
            return _emscriptenApi.indoorsApi.getFloorHeightAboveSeaLevel(floorIndex);
        }

        return null;
    };

    this.setFloorInterpolation = function(value) {
        if (_activeIndoorMap !== null) {
            var floorParam = value * _activeIndoorMap.getFloorCount();
            _emscriptenApi.expandFloorsApi.setFloorParam(floorParam);
        }
        return this;
    };

    this.setFloorFromInterpolation = function(interpolationParam) {
        if (_activeIndoorMap === null) {
            return false;
        }

        var t = (typeof interpolationParam === "undefined") ? this.getFloorInterpolation() : interpolationParam;
        var floorIndex = Math.round(t * _activeIndoorMap.getFloorCount());
        return this.setFloor(floorIndex);
    };

    this.expand = function() {
        _emscriptenApi.expandFloorsApi.expandIndoorMap();
        return this;
    };

    this.collapse = function() {
        _emscriptenApi.expandFloorsApi.collapseIndoorMap();
        return this;
    };

    this.setEntityHighlights = function(ids, color) {
        if (!_ready) return;
        _emscriptenApi.highlightApi.setEntityHighlights(ids, color);
    };

    this.clearEntityHighlights = function(ids) {
        if (!_ready) return;
        _emscriptenApi.highlightApi.clearEntityHighlights(ids);
    };
};

var IndoorsPrototype = L.extend({}, MapModule, L.Mixin.Events);

IndoorsModule.prototype = IndoorsPrototype;

module.exports = IndoorsModule;<|endoftext|>


<commit_before>var socket = io();

var gameCanvas = document.getElementById("c");
var gameContext = gameCanvas.getContext("2d");

var mouseX;
var mouseY;

var serverInfo;
var clientInfo = new ClientInfo();

var background = new Image();
background.src = "../assets/Background.png"

var clientNum;

var ball = new Ball(10);
var score1 = 0;
var score2 = 0;
var well1 = new Ball(20);
var well2 = new Ball(20);
var paddle1 = new Paddle(0)
var paddle2 = new Paddle(1)

var countdown = false;

//var game = new Game();

var main = function(){
	now = Date.now();
	delta = now - then;

	update(delta/1000);
	render();

	requestAnimationFrame(main);
}

var update = function(delta) {

}

var alreadyDone = false;

var render = function(){
	if(countdown == false){
		gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
		gameContext.drawImage(background, 0, 0)

		gameContext.font = "30px Arial";
		gameContext.fillStyle = "white";
		gameContext.fillText("Player 1: " + score1, 50, 60);
		gameContext.fillText("Player 2: " + score2, 1100, 60);

		paddle1.render();
		paddle2.render();

		if(typeof serverInfo !== "undefined"){
			ball.render();
			well1.render();
			well2.render();
		}
	}else{
		if(alreadyDone == false){
			alreadyDone = true;
			gameContext.font = "30px Arial"
			gameContext.fillText("3", 630, 360);
			setTimeout(function() {
				gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
				gameContext.drawImage(background, 0, 0)

				gameContext.font = "30px Arial";
				gameContext.fillStyle = "white";
				gameContext.fillText("Player 1: " + score1, 50, 60);
				gameContext.fillText("Player 2: " + score2, 1100, 60);

				paddle1.render();
				paddle2.render();

				if(typeof serverInfo !== "undefined"){
					ball.render();
					well1.render();
					well2.render();
				}
				gameContext.fillText("2", 630, 360);
				setTimeout(function() {
					gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
					gameContext.font = "30px Arial";
					gameContext.fillStyle = "white";
					gameContext.fillText("Player 1: " + score1, 50, 60);
					gameContext.fillText("Player 2: " + score2, 1100, 60);

					paddle1.render();
					paddle2.render();

					if(typeof serverInfo !== "undefined"){
						ball.render();
						well1.render();
						well2.render();
					}
					gameContext.fillText("1", 630, 360);
					setTimeout(function() {
						gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
						gameContext.font = "30px Arial";
						gameContext.fillStyle = "white";
						gameContext.fillText("Player 1: " + score1, 50, 60);
						gameContext.fillText("Player 2: " + score2, 1100, 60);

						paddle1.render();
						paddle2.render();

						if(typeof serverInfo !== "undefined"){
							ball.render();
							well1.render();
							well2.render();
						}
						countdown = false;
						alreadyDone = false;
					}, 1000);
				}, 1000);
			}, 1000);
		}
	}
}

then = Date.now();<commit_msg>Fixed adding the countdown<commit_after>var socket = io();

var gameCanvas = document.getElementById("c");
var gameContext = gameCanvas.getContext("2d");

var mouseX;
var mouseY;

var serverInfo;
var clientInfo = new ClientInfo();

var background = new Image();
background.src = "../assets/Background.png"

var clientNum;

var ball = new Ball(10);
var score1 = 0;
var score2 = 0;
var well1 = new Ball(20);
var well2 = new Ball(20);
var paddle1 = new Paddle(0)
var paddle2 = new Paddle(1)

var countdown = false;

//var game = new Game();

var main = function(){
	now = Date.now();
	delta = now - then;

	update(delta/1000);
	render();

	requestAnimationFrame(main);
}

var update = function(delta) {

}

var alreadyDone = false;

var render = function(){
	if(countdown == false){
		gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
		gameContext.drawImage(background, 0, 0)

		gameContext.font = "30px Arial";
		gameContext.fillStyle = "white";
		gameContext.fillText("Player 1: " + score1, 50, 60);
		gameContext.fillText("Player 2: " + score2, 1100, 60);

		paddle1.render();
		paddle2.render();

		if(typeof serverInfo !== "undefined"){
			ball.render();
			well1.render();
			well2.render();
		}
	}else{
		if(alreadyDone == false){
			alreadyDone = true;
			gameContext.font = "30px Arial"
			gameContext.fillText("3", 630, 360);
			setTimeout(function() {
				gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
				gameContext.drawImage(background, 0, 0)

				gameContext.font = "30px Arial";
				gameContext.fillStyle = "white";
				gameContext.fillText("Player 1: " + score1, 50, 60);
				gameContext.fillText("Player 2: " + score2, 1100, 60);

				paddle1.render();
				paddle2.render();

				if(typeof serverInfo !== "undefined"){
					ball.render();
					well1.render();
					well2.render();
				}
				gameContext.fillText("2", 630, 360);
				setTimeout(function() {
					gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
					gameContext.drawImage(background, 0, 0)
					gameContext.font = "30px Arial";
					gameContext.fillStyle = "white";
					gameContext.fillText("Player 1: " + score1, 50, 60);
					gameContext.fillText("Player 2: " + score2, 1100, 60);

					paddle1.render();
					paddle2.render();

					if(typeof serverInfo !== "undefined"){
						ball.render();
						well1.render();
						well2.render();
					}
					gameContext.fillText("1", 630, 360);
					setTimeout(function() {
						gameContext.clearRect(0,0,gameCanvas.width, gameCanvas.height);
						gameContext.drawImage(background, 0, 0)
						gameContext.font = "30px Arial";
						gameContext.fillStyle = "white";
						gameContext.fillText("Player 1: " + score1, 50, 60);
						gameContext.fillText("Player 2: " + score2, 1100, 60);

						paddle1.render();
						paddle2.render();

						if(typeof serverInfo !== "undefined"){
							ball.render();
							well1.render();
							well2.render();
						}
						countdown = false;
						alreadyDone = false;
					}, 1000);
				}, 1000);
			}, 1000);
		}
	}
}

then = Date.now();<|endoftext|>


<commit_before>jQuery(document).ready(function() {

    //if 'isAllDayEvent' is checked, hide datetime picker and show date picker, otherwise hide the datepicker
    jQuery('[id*="_noTime"]').each(function(event){
        var row = jQuery(this).attr('id').split('_')[2];
        if( jQuery(this).prop('checked')) {
            selectAllDayOption(row);
        }
    });
    addAllDayBehaviour();

    // mark changes as not coming from user, so confirm message on reload is not shown
    jQuery('.sonata-ba-form form').each(function () { jQuery(this).confirmExit(); });
    addEventDeleteListener();

    jQuery( document ).ajaxComplete(function() {
        addEventDeleteListener();
        hideAdvancedRecurrenceRuleSettings();
        advancedOptionsHint();
    });

    hideAdvancedRecurrenceRuleSettings();
});

/**
 * Apply recurrence fields behaviour to all event rows.
 */
function addRecurrenceRuleBehaviour() {
    // toggle visibility of recurrence fields
    var recurrenceRuleSelectElements = jQuery("select[id*='recurrenceRule_freq']");

    recurrenceRuleSelectElements.change(function() {
        toggleRecurrenceRuleFields(jQuery(this));
    });
    recurrenceRuleSelectElements.each(function() {
        toggleRecurrenceRuleFields(jQuery(this));
    });

}

/**
 * Show recurrence rule fields if a frequency is selected.
 *
 * @param selectElement
 */
function toggleRecurrenceRuleFields(selectElement) {

    var followingSiblings = selectElement.parent().parent().nextAll().children().andSelf();

    if (selectElement.val()) {
        followingSiblings.show();
    } else {
        followingSiblings.hide();
    }
}

/**
 * Apply all day behaviour to all event rows.
 */
function addAllDayBehaviour() {
    jQuery('[id*="_noTime"]').on('ifChecked', function(event){
        var row = jQuery(this).attr('id').split('_')[2];
        selectAllDayOption(row);
    });
    jQuery('[id*="_noTime"]').on('ifUnchecked', function(e, aux){
        var row = jQuery(this).attr('id').split('_')[2];
        deselectAllDayOption(row);
    });
}

/*
 * Change date format to date only.
 *
 * @param row The event's table row.
 */
function selectAllDayOption(row) {
    var $time = ['12:00 am','11:59 pm'];

    var $inputStart = jQuery("input[id*='_events_" + row + "_timeFrom']");
    var $inputEnd = jQuery("input[id*='_events_" + row + "_timeTo']");

    jQuery.each([$inputStart, $inputEnd], function(index, $input) {
        var $dp = $input.parent().data("DateTimePicker");
        $input.val($time[index]);
        $dp.disable();
    });
}

/*
 * Change date format to date and time.
 *
 * @param row The event's table row.
 */
function deselectAllDayOption(row) {
    var $inputStart = jQuery("input[id*='_events_" + row + "_timeFrom']");
    var $inputEnd = jQuery("input[id*='_events_" + row + "_timeTo']");

    jQuery.each([$inputStart, $inputEnd], function(index, $input) {
        var $dp = $input.parent().data("DateTimePicker");

        $dp.enable();
    });
}

function hideAdvancedRecurrenceRuleSettings() {
    jQuery("div[id*='_events'] .sonata-ba-tbody tr").each(function(key, value) {
        if (!jQuery(this).find("#collapseRecurrenceRule_" + key).length > 0) {
            if (jQuery("div[id*='" + key + "_recurrenceRule_interval']").css('display') == 'none') {
                jQuery("div[id*='" + key + "_recurrenceRule_interval']").before('

 Advanced options

');
            } else {
                jQuery("div[id*='" + key + "_recurrenceRule_interval']").before('

 Advanced options

');
            }
            jQuery("div[id*='" + key + "_recurrenceRule_interval']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byMonth']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byWeekNo']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byYearDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byMonthDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none, script').css('display', 'block');
        }
    });
    advancedOptionsHint();
}

/*
 * Add hint for hidden advanced options
 */
function advancedOptionsHint() {
    console.log('hello');
    jQuery("div[id*='events'] tbody.sonata-ba-tbody tr").each(function (row) {
        var interval = jQuery("input[id*='" + row + "_recurrenceRule_interval']").val();
        var byMonth = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byMonth'] .select2-search-choice").length;
        var byWeekNo = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byWeekNo'] .select2-search-choice").length;
        var byYearDay = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byYearDay'] .select2-search-choice").length;
        var byMonthDay = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byMonthDay'] .select2-search-choice").length;
        var byDays = jQuery("div[id*='" + row + "_recurrenceRule_'][id*=_delete]").length;
        console.log(byDays);
        var count = 0;
        count += interval ? 1 : 0;
        count += byMonth ? byMonth : 0;
        count += byWeekNo ? byWeekNo : 0;
        count += byYearDay ? byYearDay : 0;
        count += byMonthDay ? byMonthDay : 0;
        count += byDays ? byDays : 0;

        var heading = jQuery("a[href='#collapseRecurrenceRule_" + row + "']");
        if (count) {
            heading.html(heading.html() + " (" + count + ")");
        }
    });
}

/*
 * Add event listener for deletion of events and nthOccurrence
 */
function addEventDeleteListener() {
    jQuery('[id*="_delete"][id*="_events"]:not([id*="recurrenceRule"])').on('ifChecked', function (event) {
        if (jQuery('[id*="_events"][id*="sonata-ba-field-container"] tbody tr').length > 1) {
            jQuery(this).parent().parent().parent().parent().parent().remove();
        }
    });
    jQuery('[id*="_delete"][id*="_events"][id*="recurrenceRule"]').on('ifChecked', function (event) {
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().remove();
    });
}<commit_msg>removing logs<commit_after>jQuery(document).ready(function() {

    //if 'isAllDayEvent' is checked, hide datetime picker and show date picker, otherwise hide the datepicker
    jQuery('[id*="_noTime"]').each(function(event){
        var row = jQuery(this).attr('id').split('_')[2];
        if( jQuery(this).prop('checked')) {
            selectAllDayOption(row);
        }
    });
    addAllDayBehaviour();

    // mark changes as not coming from user, so confirm message on reload is not shown
    jQuery('.sonata-ba-form form').each(function () { jQuery(this).confirmExit(); });
    addEventDeleteListener();

    jQuery( document ).ajaxComplete(function() {
        addEventDeleteListener();
        hideAdvancedRecurrenceRuleSettings();
        advancedOptionsHint();
    });

    hideAdvancedRecurrenceRuleSettings();
});

/**
 * Apply recurrence fields behaviour to all event rows.
 */
function addRecurrenceRuleBehaviour() {
    // toggle visibility of recurrence fields
    var recurrenceRuleSelectElements = jQuery("select[id*='recurrenceRule_freq']");

    recurrenceRuleSelectElements.change(function() {
        toggleRecurrenceRuleFields(jQuery(this));
    });
    recurrenceRuleSelectElements.each(function() {
        toggleRecurrenceRuleFields(jQuery(this));
    });

}

/**
 * Show recurrence rule fields if a frequency is selected.
 *
 * @param selectElement
 */
function toggleRecurrenceRuleFields(selectElement) {

    var followingSiblings = selectElement.parent().parent().nextAll().children().andSelf();

    if (selectElement.val()) {
        followingSiblings.show();
    } else {
        followingSiblings.hide();
    }
}

/**
 * Apply all day behaviour to all event rows.
 */
function addAllDayBehaviour() {
    jQuery('[id*="_noTime"]').on('ifChecked', function(event){
        var row = jQuery(this).attr('id').split('_')[2];
        selectAllDayOption(row);
    });
    jQuery('[id*="_noTime"]').on('ifUnchecked', function(e, aux){
        var row = jQuery(this).attr('id').split('_')[2];
        deselectAllDayOption(row);
    });
}

/*
 * Change date format to date only.
 *
 * @param row The event's table row.
 */
function selectAllDayOption(row) {
    var $time = ['12:00 am','11:59 pm'];

    var $inputStart = jQuery("input[id*='_events_" + row + "_timeFrom']");
    var $inputEnd = jQuery("input[id*='_events_" + row + "_timeTo']");

    jQuery.each([$inputStart, $inputEnd], function(index, $input) {
        var $dp = $input.parent().data("DateTimePicker");
        $input.val($time[index]);
        $dp.disable();
    });
}

/*
 * Change date format to date and time.
 *
 * @param row The event's table row.
 */
function deselectAllDayOption(row) {
    var $inputStart = jQuery("input[id*='_events_" + row + "_timeFrom']");
    var $inputEnd = jQuery("input[id*='_events_" + row + "_timeTo']");

    jQuery.each([$inputStart, $inputEnd], function(index, $input) {
        var $dp = $input.parent().data("DateTimePicker");

        $dp.enable();
    });
}

function hideAdvancedRecurrenceRuleSettings() {
    jQuery("div[id*='_events'] .sonata-ba-tbody tr").each(function(key, value) {
        if (!jQuery(this).find("#collapseRecurrenceRule_" + key).length > 0) {
            if (jQuery("div[id*='" + key + "_recurrenceRule_interval']").css('display') == 'none') {
                jQuery("div[id*='" + key + "_recurrenceRule_interval']").before('

 Advanced options

');
            } else {
                jQuery("div[id*='" + key + "_recurrenceRule_interval']").before('

 Advanced options

');
            }
            jQuery("div[id*='" + key + "_recurrenceRule_interval']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byMonth']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byWeekNo']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byYearDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byMonthDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none').css('display', 'block');
            jQuery("div[id*='" + key + "_recurrenceRule_byDay']").appendTo("#collapseRecurrenceRule_" + key).children().andSelf().not('.select2-display-none, script').css('display', 'block');
        }
    });
    advancedOptionsHint();
}

/*
 * Add hint for hidden advanced options
 */
function advancedOptionsHint() {
    jQuery("div[id*='events'] tbody.sonata-ba-tbody tr").each(function (row) {
        var interval = jQuery("input[id*='" + row + "_recurrenceRule_interval']").val();
        var byMonth = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byMonth'] .select2-search-choice").length;
        var byWeekNo = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byWeekNo'] .select2-search-choice").length;
        var byYearDay = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byYearDay'] .select2-search-choice").length;
        var byMonthDay = jQuery("div.select2-container[id*='" + row + "_recurrenceRule_byMonthDay'] .select2-search-choice").length;
        var byDays = jQuery("div[id*='" + row + "_recurrenceRule_'][id*=_delete]").length;
        var count = 0;
        count += interval ? 1 : 0;
        count += byMonth ? byMonth : 0;
        count += byWeekNo ? byWeekNo : 0;
        count += byYearDay ? byYearDay : 0;
        count += byMonthDay ? byMonthDay : 0;
        count += byDays ? byDays : 0;

        var heading = jQuery("a[href='#collapseRecurrenceRule_" + row + "']");
        if (count) {
            heading.html(heading.html() + " (" + count + ")");
        }
    });
}

/*
 * Add event listener for deletion of events and nthOccurrence
 */
function addEventDeleteListener() {
    jQuery('[id*="_delete"][id*="_events"]:not([id*="recurrenceRule"])').on('ifChecked', function (event) {
        if (jQuery('[id*="_events"][id*="sonata-ba-field-container"] tbody tr').length > 1) {
            jQuery(this).parent().parent().parent().parent().parent().remove();
        }
    });
    jQuery('[id*="_delete"][id*="_events"][id*="recurrenceRule"]').on('ifChecked', function (event) {
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().next().remove();
        jQuery(this).parent().parent().parent().parent().parent().remove();
    });
}<|endoftext|>