<commit_before>/*
The files in this directory are part of node-ansible-test, a javascript-based library.
Copyright (C) 2016 Daniel Bush
This program is distributed under the terms of the BSD-2-Clause License.
*/
'use strict';

const chai = require('chai');
const expect = chai.expect;
const chaiAsPromised = require("chai-as-promised");
const wd = require('wd');
chai.use(chaiAsPromised);
var browser;
var username  = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;

describe('something', function () {

  before(function () {
    //browser = wd.promiseChainRemote('localhost');
    //browser = wd.promiseChainRemote('ondemand.saucelabs.com', 80, username, accessKey);
    browser = wd.promiseChainRemote('localhost', 4445, username, accessKey);
    return browser.init({browserName:'chrome'});
  });

  beforeEach(function() {
    //return browser.get('https://www.google.com');
    return browser.get('http://localhost:8000');
  });

  after(function () {
    return browser.quit();
  });

  it('should retrieve the page title', function() {
    return expect(browser.title()).to.eventually.equal('Google');
  });

});
<commit_msg>Trying to add saucelabs.<commit_after>/*
The files in this directory are part of node-ansible-test, a javascript-based library.
Copyright (C) 2016 Daniel Bush
This program is distributed under the terms of the BSD-2-Clause License.
*/
'use strict';

const chai = require('chai');
const expect = chai.expect;
const chaiAsPromised = require("chai-as-promised");
const wd = require('wd');
chai.use(chaiAsPromised);
var browser;
var username  = process.env.SAUCE_USERNAME;
var accessKey = process.env.SAUCE_ACCESS_KEY;

describe('something', function () {

  before(function () {
    //browser = wd.promiseChainRemote('localhost');
    browser = wd.promiseChainRemote('ondemand.saucelabs.com', 80, username, accessKey);
    //browser = wd.promiseChainRemote('localhost', 4445, username, accessKey);
    return browser.init({browserName:'chrome'});
  });

  beforeEach(function() {
    //return browser.get('https://www.google.com');
    return browser.get('http://localhost:8000');
  });

  after(function () {
    return browser.quit();
  });

  it('should retrieve the page title', function() {
    return expect(browser.title()).to.eventually.equal('Google');
  });

});
<|endoftext|>


<commit_before>'use strict';
var test = require('tape');
var Vinyl = require('vinyl');
var minifer = require('../minifier');
var cmem = require('cmem');

var testContentsOutput = 'function abs(a, b) {\n  return a > b; }';
var testContentsInput = 'function testInput() {}';
var testFile = new Vinyl({
  cwd: '/home/terin/broken-promises/',
  base: '/home/terin/broken-promises/test',
  path: '/home/terin/broken-promises/test/test1.js',
  contents: new Buffer(testContentsInput)
});
var uglifyjs = {
  minify: cmem(function() {
    return {
      code: testContentsOutput
    };
  })
};

test('should minify files', function(t) {
  t.plan(10);

  var stream = minifer({injecting: true}, uglifyjs);

  stream.on('data', function(newFile) {
    t.ok(newFile, 'emits a file');
    t.ok(newFile.path, 'file has a path');
    t.ok(newFile.relative, 'file has relative path information');
    t.ok(newFile.contents, 'file has contents');

    t.ok(newFile instanceof Vinyl, 'file is Vinyl');
    t.ok(newFile.contents instanceof Buffer, 'file contents are a buffer');

    t.equals(String(newFile.contents), testContentsOutput);

    t.equals(uglifyjs.minify.$count, 1, 'minify stub was called only once');
    t.equals(uglifyjs.minify.$args[0], testContentsInput, 'stub argument 0 was the expected input');
    t.deepEqual(uglifyjs.minify.$args[1], {
      fromString: true,
      output: {},
      injecting: true
    }, 'stub argument 1 was the expected options');
  });

  stream.write(testFile);
  stream.end();
});
<commit_msg>test injectable option.banner<commit_after>'use strict';
var test = require('tape');
var Vinyl = require('vinyl');
var minifer = require('../minifier');
var cmem = require('cmem');

var testContentsOutput = 'function abs(a, b) {\n  return a > b; }';
var testContentsInput = 'function testInput() {}';
var testFile = new Vinyl({
  cwd: '/home/terin/broken-promises/',
  base: '/home/terin/broken-promises/test',
  path: '/home/terin/broken-promises/test/test1.js',
  contents: new Buffer(testContentsInput)
});
var uglifyjs = {
  minify: cmem(function() {
    return {
      code: testContentsOutput
    };
  })
};

test('should minify files', function(t) {
  t.plan(10);

  var stream = minifer({injecting: true}, uglifyjs);

  stream.on('data', function(newFile) {
    t.ok(newFile, 'emits a file');
    t.ok(newFile.path, 'file has a path');
    t.ok(newFile.relative, 'file has relative path information');
    t.ok(newFile.contents, 'file has contents');

    t.ok(newFile instanceof Vinyl, 'file is Vinyl');
    t.ok(newFile.contents instanceof Buffer, 'file contents are a buffer');

    t.equals(String(newFile.contents), testContentsOutput);

    t.equals(uglifyjs.minify.$count, 1, 'minify stub was called only once');
    t.equals(uglifyjs.minify.$args[0], testContentsInput, 'stub argument 0 was the expected input');
    t.deepEqual(uglifyjs.minify.$args[1], {
      fromString: true,
			banner:'',
      output: {},
      injecting: true
    }, 'stub argument 1 was the expected options');
  });

  stream.write(testFile);
  stream.end();
});
<|endoftext|>


<commit_before>module.exports = function (config) {

    // if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    //  console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    //  process.exit(1);
    // }

    var customLaunchers = {
        sl_chrome: {
         base: 'SauceLabs',
         browserName: 'chrome',
         platform: 'Windows 7',
         version: '38'
        },
        sl_firefox: {
         base: 'SauceLabs',
         browserName: 'firefox',
         version: '33',
         platform: 'Windows 7'
        },
        sl_ios_safari: {
         base: 'SauceLabs',
         browserName: 'iphone',
         platform: 'OS X 10.9',
         version: '7.1'
        },
        sl_mac_safari: {
         base: 'SauceLabs',
         browserName: 'safari',
         platform: 'OS X 10.10',
         version: '8'
        },
        sl_ie_11: {
         base: 'SauceLabs',
         browserName: 'internet explorer',
         platform: 'Windows 8.1',
         version: '11'
        },
        sl_ie_9: {
         base: 'SauceLabs',
         browserName: 'internet explorer',
         platform: 'Windows 7',
         version: '9'
        },
        sl_opera_12: {
         base: 'SauceLabs',
         browserName: 'opera',
         platform: 'Windows 7',
         version: '12'
        }
    };

    config.set({
        basePath: '',
        autoWatch: true,
        frameworks: ['jasmine'],
        // logLevel: config.LOG_DEBUG,
        preprocessors: {
            '../src/*.js': ['coverage'],
            '../test/**/*.js': ['babel']
        },

        sauceLabs: {
            testName: 'angular-locker',
            recordScreenshots: false,
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
        },
        customLaunchers: customLaunchers,
        browsers: ['PhantomJS'].concat(Object.keys(customLaunchers)),
        reporters: ['spec', 'coverage', 'notify', 'saucelabs'],
        singleRun: true,
        captureTimeout: 120000,

        coverageReporter: {
            type: 'lcov',
            dir: 'coverage/',
            subdir: function(browser) {
                return 'lcov';
            }
        }
    });
};<commit_msg>removing saucelabs again<commit_after>module.exports = function (config) {

    // if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    //  console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    //  process.exit(1);
    // }

    var customLaunchers = {
        // sl_chrome: {
        //  base: 'SauceLabs',
        //  browserName: 'chrome',
        //  platform: 'Windows 7',
        //  version: '38'
        // },
        // sl_firefox: {
        //  base: 'SauceLabs',
        //  browserName: 'firefox',
        //  version: '33',
        //  platform: 'Windows 7'
        // },
        // sl_ios_safari: {
        //  base: 'SauceLabs',
        //  browserName: 'iphone',
        //  platform: 'OS X 10.9',
        //  version: '7.1'
        // },
        // sl_mac_safari: {
        //  base: 'SauceLabs',
        //  browserName: 'safari',
        //  platform: 'OS X 10.10',
        //  version: '8'
        // },
        // sl_ie_11: {
        //  base: 'SauceLabs',
        //  browserName: 'internet explorer',
        //  platform: 'Windows 8.1',
        //  version: '11'
        // },
        // sl_ie_9: {
        //  base: 'SauceLabs',
        //  browserName: 'internet explorer',
        //  platform: 'Windows 7',
        //  version: '9'
        // },
        // sl_opera_12: {
        //  base: 'SauceLabs',
        //  browserName: 'opera',
        //  platform: 'Windows 7',
        //  version: '12'
        // }
    };

    config.set({
        basePath: '',
        autoWatch: true,
        frameworks: ['jasmine'],
        // logLevel: config.LOG_DEBUG,
        preprocessors: {
            '../src/*.js': ['coverage'],
            '../test/**/*.js': ['babel']
        },
        sauceLabs: {
            testName: 'angular-locker',
            recordScreenshots: false,
            tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
        },
        customLaunchers: customLaunchers,
        browsers: ['PhantomJS'].concat(Object.keys(customLaunchers)),
        reporters: ['spec', 'coverage', 'notify', 'saucelabs'],
        singleRun: true,
        captureTimeout: 120000,
        coverageReporter: {
            type: 'lcov',
            dir: 'coverage/',
            subdir: function(browser) {
                return 'lcov';
            }
        }
    });
};<|endoftext|>


<commit_before>const bin = require('../bin');
const pkg = bin.common.res('package');
const webpack = bin({ run: 'test' });

/*!
|* This is a karma config file. For more details
|* @see https://www.browserstack.com/screenshots
|* @see https://www.browserstack.com/list-of-browsers-and-platforms?product=automate
|* @see https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
|* @see http://karma-runner.github.io/0.13/config/configuration-file.html
|* @see http://karma-runner.github.io/0.13/config/browsers.html
|* @see https://github.com/webpack/karma-webpack
`*/
module.exports = (config) => {
	const customLaunchers = {
		bs_mobile_chrome: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.3',
			browser: 'chrome',
			browser_version: '5.5.372',
			real_mobile: false,
		},
		bs_mobile_safari_8: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '8.3',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_mobile_safari_9: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.1',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_win_chrome: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_win_firefox: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'firefox',
			browser_version: '43.0',
		},
		bs_win_ie9: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: 'XP',
			browser: 'ie',
			browser_version: '9.0',
		},
		bs_win_ie10: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '8',
			browser: 'ie',
			browser_version: '10.0',
		},
		bs_win_ie11: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'ie',
			browser_version: '11.0',
		},
		bs_mac_chrome: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_mac_firefox: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'firefox',
			browser_version: '21.0',
		},
		bs_mac_safari: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'safari',
			browser_version: '9.0',
		},
	};

	const settings = {
		webpack,
		customLaunchers,
		logLevel: config.LOG_INFO,
		basePath: '../',
		port: 9876,
		colors: true,
		concurrency: 2,
		browserNoActivityTimeout: 240000,
		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 3,
		browsers: ['PhantomJS'],
		frameworks: ['mocha', 'sinon-chai', 'fixture', 'phantomjs-shim'],
		reporters: ['spec', 'coverage'],
		files: [{
			pattern: 'test/fixtures/**/*.fixture.*',
			watched: true,
		}, {
			pattern: 'test/specs/**/*.spec.js',
			watched: true,
		}, {
			pattern: 'source/**/*.js',
			watched: true,
		}],
		preprocessors: {
			'source/**/*.js': ['webpack', 'sourcemap', 'coverage'],
			'test/specs/**/*.spec.js': ['webpack', 'sourcemap'],
			'test/fixtures/**/*.html': ['html2js'],
			'test/fixtures/**/*.json': ['json_fixtures'],
		},
		jsonFixturesPreprocessor: {
			variableName: '__json__',
		},
		webpackServer: {
			noInfo: true,
		},
		browserStack: {
			project: pkg.name,
			username: process.env.BROWSERSTACK_USERNAME,
			accessKey: process.env.BROWSERSTACK_KEY,
			captureTimeout: 120,
			retryLimit: 3,
			timeout: 300,
		},
		client: {
			mocha: {
				reporter: 'html',
			},
		},
		coverageReporter: {
			dir: 'test/coverage',
			reporters: [
				{ type: 'lcovonly', subdir: '.' },
				{ type: 'json', subdir: '.' },
			],
		},
	};

	if (process.env.TRAVIS) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.TRAVIS_BUILD_NUMBER;
		settings.browserStack.name = process.env.TRAVIS_JOB_NUMBER;
	} else if (process.env.APPVEYOR) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.APPVEYOR_BUILD_NUMBER;
		settings.browserStack.name = process.env.APPVEYOR_JOB_NUMBER;
	} else if (process.env.CIRCLECI) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.CIRCLE_BUILD_NUM;
		settings.browserStack.name = process.env.CIRCLE_BUILD_URL;
	}

	config.set(settings);
};
<commit_msg>ci: circle<commit_after>const bin = require('../bin');
const pkg = bin.common.res('package');
const webpack = bin({ run: 'test' });

/*!
|* This is a karma config file. For more details
|* @see https://www.browserstack.com/screenshots
|* @see https://www.browserstack.com/list-of-browsers-and-platforms?product=automate
|* @see https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md
|* @see http://karma-runner.github.io/0.13/config/configuration-file.html
|* @see http://karma-runner.github.io/0.13/config/browsers.html
|* @see https://github.com/webpack/karma-webpack
`*/
module.exports = function (config) {
	const customLaunchers = {
		bs_mobile_chrome: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.3',
			browser: 'chrome',
			browser_version: '5.5.372',
			real_mobile: false,
		},
		bs_mobile_safari_8: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '8.3',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_mobile_safari_9: {
			base: 'BrowserStack',
			os: 'ios',
			os_version: '9.1',
			browser: 'iphone',
			real_mobile: false,
		},
		bs_win_chrome: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_win_firefox: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'firefox',
			browser_version: '43.0',
		},
		bs_win_ie9: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: 'XP',
			browser: 'ie',
			browser_version: '9.0',
		},
		bs_win_ie10: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '8',
			browser: 'ie',
			browser_version: '10.0',
		},
		bs_win_ie11: {
			base: 'BrowserStack',
			os: 'Windows',
			os_version: '10',
			browser: 'ie',
			browser_version: '11.0',
		},
		bs_mac_chrome: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'chrome',
			browser_version: '47.0',
			flags: ['--no-sandbox'],
		},
		bs_mac_firefox: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'firefox',
			browser_version: '21.0',
		},
		bs_mac_safari: {
			base: 'BrowserStack',
			os: 'OS X',
			os_version: 'Sierra',
			browser: 'safari',
			browser_version: '9.0',
		},
	};

	const settings = {
		webpack,
		customLaunchers,
		logLevel: config.LOG_INFO,
		basePath: '../',
		port: 9876,
		colors: true,
		concurrency: 2,
		browserNoActivityTimeout: 240000,
		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 3,
		browsers: ['PhantomJS'],
		frameworks: ['mocha', 'sinon-chai', 'fixture', 'phantomjs-shim'],
		reporters: ['spec', 'coverage'],
		files: [{
			pattern: 'test/fixtures/**/*.fixture.*',
			watched: true,
		}, {
			pattern: 'test/specs/**/*.spec.js',
			watched: true,
		}, {
			pattern: 'source/**/*.js',
			watched: true,
		}],
		preprocessors: {
			'source/**/*.js': ['webpack', 'sourcemap', 'coverage'],
			'test/specs/**/*.spec.js': ['webpack', 'sourcemap'],
			'test/fixtures/**/*.html': ['html2js'],
			'test/fixtures/**/*.json': ['json_fixtures'],
		},
		jsonFixturesPreprocessor: {
			variableName: '__json__',
		},
		webpackServer: {
			noInfo: true,
		},
		browserStack: {
			project: pkg.name,
			username: process.env.BROWSERSTACK_USERNAME,
			accessKey: process.env.BROWSERSTACK_KEY,
			captureTimeout: 120,
			retryLimit: 3,
			timeout: 300,
		},
		client: {
			mocha: {
				reporter: 'html',
			},
		},
		coverageReporter: {
			dir: 'test/coverage',
			reporters: [
				{ type: 'lcovonly', subdir: '.' },
				{ type: 'json', subdir: '.' },
			],
		},
	};

	if (process.env.TRAVIS) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.TRAVIS_BUILD_NUMBER;
		settings.browserStack.name = process.env.TRAVIS_JOB_NUMBER;
	} else if (process.env.APPVEYOR) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.APPVEYOR_BUILD_NUMBER;
		settings.browserStack.name = process.env.APPVEYOR_JOB_NUMBER;
	} else if (process.env.CIRCLECI) {
		settings.browserStack.captureTimeout = 240000;
		settings.browserStack.browsers = Object.keys(customLaunchers);
		settings.browserStack.build = process.env.CIRCLE_BUILD_NUM;
		settings.browserStack.name = process.env.CIRCLE_BUILD_URL;
	}

	config.set(settings);
};
<|endoftext|>


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

  var stage = new Kinetic.Stage({
    container: 'game',
    width: window.innerWidth,
    height: window.innerHeight
  });

  var layers = {'bg':new Kinetic.Layer(), 'loading':new Kinetic.Layer({x: (stage.getWidth()/2)-(320/2),
    y: (stage.getHeight()/2)-(285/2),
    width: 320,
    height: 285})};

  //Haces un rectangulo sobre lo que quieras centrar y luego calculas:
  // x: (stage.getWidth()/2)-(rect.getWidth()/2)
  // y: (stage.getHeight()/2)-(rect.getHeight()/2)

  var rect = new Kinetic.Rect({

    'width': stage.attrs.width,
    'height': stage.attrs.height,
    'fillLinearGradientStartPoint':{x:0,y:0},
    'fillLinearGradientEndPoint':{x:stage.attrs.width,y:stage.attrs.height},
    'fillLinearGradientColorStops':[0, '#D7D7E2', 1, '#B7CBCF']
  });

  // add the shape to the layer
  layers['bg'].add(rect);

  var circlesList = new CircleList();

  circlesList.circles = [
      // x, y, radius, color
      new Circle(150, 160, 90, "rgba(197, 171, 224,.9)"),
      new Circle(67, 136, 34,  "rgba(177, 190, 229,.9)"),
      new Circle(106, 74, 22,  "rgba(137, 150, 224,.8)"),
      new Circle(114, 52, 10,  "rgba(177, 125, 221,.75)"),
      new Circle(220, 82, 56,  "rgba(177, 165, 224,.6)"),
      new Circle(250, 138, 43, "rgba(157, 170, 223,.9)"),
      new Circle(232, 232, 25, "rgba(157, 181, 224,.9)"),
      new Circle(256, 222, 10, "rgba(107, 212, 225,.7)"),
      new Circle(128, 244, 36, "rgba(107, 190, 225,.9)"),
      new Circle(64, 188, 10,  "rgba(107, 205, 226,.9)")
  ];

  for(var i=0;i<circlesList['circles'].length;i++)
  {
    layers['loading'].add(circlesList['circles'][i].kcircle);
  }

  var ebury_logo = new Image();

  // variables accessible from within function(frame)
  var frameCount = 0;
  var currentSecond = 0;
  var frameRate = 0;

  ebury_logo.onload = function() {

    var image = new Kinetic.Image({
      x: 100,
      y: 145,
      image: ebury_logo,
      width: 113,
      height: 40,
      opacity: 1
    });

    layers['loading'].add(image);
    layers['loading'].draw();

    var anim = new Kinetic.Animation(function(frame) {

      // within function(frame), called with current time on each new frame
      function updateFrameRate(time) {
          var second = Math.floor(time / 1000); // ms to integer seconds
          if (second != currentSecond) {
             frameRate = frameCount;
             frameCount = 0;
             currentSecond = second;
          }
          frameCount ++;
      }

      //updateFrameRate(frame.time);
      //console.log(frameRate);
      layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
      circlesList.update();

    }, layers['loading']);

    anim.start();

  };

  ebury_logo.src = './snake/images/ebury_logo.png';

  for(var layer in layers)
  {
    stage.add(layers[layer]);
  }

  // data structures
   function CircleList()
   {
      this.circles = [];

      this.update = function()
      {
         // special case for first blob - which is the main magenta disc
         var circle = this.circles[0];
         if (Math.random() > 0.99)
         {
            circle.velocity.z += (Math.random()*0.10 - 0.05);
            circle.spring = 0.0125;
         }
         circle.update();

         // all the other blobs can animate based on mouse interaction
         for (var i = 1,dx,dy,d; i < this.circles.length; i++)
         {
            circle = this.circles[i];

            // else based on a random chance, pulse the blob
            if (Math.random() > 0.995)
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.velocity[2] += (Math.random()*0.30 - 0.15);
               circle.spring = 0.0125;
            }
            // else just animate towards the original position
            else
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.spring = 0.05;
            }

            circle.update();
         }
      };
   };

   function Circle(x, y, radius, colour)
   {
      this.kcircle = new Kinetic.Circle({x:x, y:y, radius: radius, fill:colour, stroke: 'rgb(191, 191, 191)', strokeWidth: 1});
      this.origin = [x,y, 0];
      this.position = [x,y, 0];
      this.targetPos = [x,y, 0];
      this.originradius = radius;
      this.radius = radius;
      this.velocity = [0,0, 0];
      this.friction = 0.75;
      this.spring = 0.05;

      this.update = function()
      {
         this.velocity[0] += (this.targetPos[0] - this.kcircle.x()) * this.spring;
         this.velocity[0] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[0]);

         this.velocity[1] += (this.targetPos[1] - this.kcircle.y()) * this.spring;
         this.velocity[1] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[1]);

         var dox = this.origin[0] - this.kcircle.x(),
             doy = this.origin[1] - this.kcircle.y(),
             d = Math.sqrt(dox * dox + doy * doy);

         this.targetPos[2] = d/150 + 1;
         this.velocity[2] += (this.targetPos[2] - this.position[2]) * this.spring;
         this.velocity[2] *= this.friction;
         this.position[2] += this.velocity[2];

         this.kcircle.radius(this.originradius * this.position[2]);
         if (this.kcircle.radius() < 1) this.kcircle.radius(1);
      };
   };

});

<commit_msg>moving circle<commit_after>
jQuery(document).ready(function(){

  var stage = new Kinetic.Stage({
    container: 'game',
    width: window.innerWidth,
    height: window.innerHeight
  });

  var layers = {'bg':new Kinetic.Layer(), 'loading':new Kinetic.Layer({x: (stage.getWidth()/2)-(320/2),
    y: (stage.getHeight()/2)-(285/2),
    width: 320,
    height: 285}), 'game':new Kinetic.Layer()};

  //Haces un rectangulo sobre lo que quieras centrar y luego calculas:
  // x: (stage.getWidth()/2)-(rect.getWidth()/2)
  // y: (stage.getHeight()/2)-(rect.getHeight()/2)

  var rect = new Kinetic.Rect({

    'width': stage.attrs.width,
    'height': stage.attrs.height,
    'fillLinearGradientStartPoint':{x:0,y:0},
    'fillLinearGradientEndPoint':{x:stage.attrs.width,y:stage.attrs.height},
    'fillLinearGradientColorStops':[0, '#D7D7E2', 1, '#B7CBCF']
  });

  // add the shape to the layer
  layers['bg'].add(rect);

  var circlesList = new CircleList();

  circlesList.circles = [
      // x, y, radius, color
      new Circle(150, 160, 90, "rgba(197, 171, 224,.9)"),
      new Circle(67, 136, 34,  "rgba(177, 190, 229,.9)"),
      new Circle(106, 74, 22,  "rgba(137, 150, 224,.8)"),
      new Circle(114, 52, 10,  "rgba(177, 125, 221,.75)"),
      new Circle(220, 82, 56,  "rgba(177, 165, 224,.6)"),
      new Circle(250, 138, 43, "rgba(157, 170, 223,.9)"),
      new Circle(232, 232, 25, "rgba(157, 181, 224,.9)"),
      new Circle(256, 222, 10, "rgba(107, 212, 225,.7)"),
      new Circle(128, 244, 36, "rgba(107, 190, 225,.9)"),
      new Circle(64, 188, 10,  "rgba(107, 205, 226,.9)")
  ];

  for(var i=0;i<circlesList['circles'].length;i++)
  {
    layers['loading'].add(circlesList['circles'][i].kcircle);
  }

  var ebury_logo = new Image();

  // variables accessible from within function(frame)
  var frameCount = 0;
  var currentSecond = 0;
  var frameRate = 0;

  ebury_logo.onload = function() {

    var image = new Kinetic.Image({
      x: 100,
      y: 145,
      image: ebury_logo,
      width: 113,
      height: 40,
      opacity: 1
    });

    layers['loading'].add(image);
    layers['loading'].draw();

    function updateFrameRate(time) {
          var second = Math.floor(time / 1000); // ms to integer seconds
          console.log(second, currentSecond)
          if (second != currentSecond) {
             frameRate = frameCount;
             frameCount = 0;
             currentSecond = second;
          }
          frameCount ++;
      }

    var anim = new Kinetic.Animation(function(frame) {

      // within function(frame), called with current time on each new frame

      //updateFrameRate(frame.time);

      wait(500, frame.time, function(){
          layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
          circlesList.update();
      });
      //console.log(frameRate);

      // layers['loading'].getCanvas().getContext().globalCompositeOperation = 'darker';
      // circlesList.update();

    }, layers['loading']);

    anim.start();

    stage.on('click.start touchstart.start', function(e){

        stage.off('click.start touchstart.start');
        anim.stop();

        var tween = new Kinetic.Tween({
            node: layers['loading'],
            opacity: 0,
            duration: 1,
            onFinish: function(){
                console.log('done!');
                tween.destroy();
                layers['loading'].destroy();
                //Startgame
                startGame();
            }
        }).play();
    });

  };

  ebury_logo.src = './snake/images/ebury_logo.png';

  stage.add(layers['bg']);
  stage.add(layers['loading']);
  // for(var layer in layers)
  // {
  //   stage.add(layers[layer]);
  // }

  function wait(seconds, time, callback) {
      seconds = seconds || 1000;
      var second = Math.floor(time / seconds);
      if (second != currentSecond)
      {
         callback();
      }
  }

  function startGame()
  {

    var snake = new Player();

    layers['game'].add(snake.actor);
    stage.add(layers['game']);

    stage.on('mousemove.game', function(data){

        snake.targetPos.x = data.evt.clientX;
        snake.targetPos.y = data.evt.clientY;
    });

    var anim = new Kinetic.Animation(function(frame) {

       wait(500, frame.time, function(){
          snake.update();
      });

    }, layers['game']);

    anim.start();
  }

  function Player()
  {
    this.actor = new Kinetic.Circle({x:stage.getWidth()/2, y:stage.getHeight()/2, radius: 10, fill:'#000', stroke: 'rgb(191, 191, 191)', strokeWidth: 3});

    this.targetPos = {x:stage.getWidth()/2, y:stage.getHeight()/2};
    this.sprint = 0.05;
    this.update = function()
    {
      var y = this.actor.y() + (this.targetPos.y - this.actor.y())*this.sprint;
      var x = this.actor.x() + (this.targetPos.x - this.actor.x())*this.sprint;

      this.actor.x(x);
      this.actor.y(y);

    }
  };

  // data structures
  function CircleList()
  {
      this.circles = [];

      this.update = function()
      {
         // special case for first blob - which is the main magenta disc
         var circle = this.circles[0];
         if (Math.random() > 0.69)
         {
            circle.velocity.z += (Math.random()*0.10 - 0.05);
            circle.spring = 0.0125;
         }
         circle.update();

         // all the other blobs can animate based on mouse interaction
         for (var i = 1,dx,dy,d; i < this.circles.length; i++)
         {
            circle = this.circles[i];

            // else based on a random chance, pulse the blob
            if (Math.random() > 0.995)
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.velocity[2] += (Math.random()*0.30 - 0.15);
               circle.spring = 0.0125;
            }
            // else just animate towards the original position
            else
            {
               circle.targetPos[0] = circle.origin[0];
               circle.targetPos[1] = circle.origin[1];
               circle.spring = 0.05;
            }

            circle.update();
         }
      };
   };

   function Circle(x, y, radius, colour)
   {
      this.kcircle = new Kinetic.Circle({x:x, y:y, radius: radius, fill:colour, stroke: 'rgb(191, 191, 191)', strokeWidth: 1});
      this.origin = [x,y, 0];
      this.position = [x,y, 0];
      this.targetPos = [x,y, 0];
      this.originradius = radius;
      this.radius = radius;
      this.velocity = [0,0, 0];
      this.friction = 0.75;
      this.spring = 0.05;

      this.update = function()
      {
         this.velocity[0] += (this.targetPos[0] - this.kcircle.x()) * this.spring;
         this.velocity[0] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[0]);

         this.velocity[1] += (this.targetPos[1] - this.kcircle.y()) * this.spring;
         this.velocity[1] *= this.friction;
         this.kcircle.x(this.kcircle.x() + this.velocity[1]);

         var dox = this.origin[0] - this.kcircle.x(),
             doy = this.origin[1] - this.kcircle.y(),
             d = Math.sqrt(dox * dox + doy * doy);

         this.targetPos[2] = d/150 + 1;
         this.velocity[2] += (this.targetPos[2] - this.position[2]) * this.spring;
         this.velocity[2] *= this.friction;
         this.position[2] += this.velocity[2];

         this.kcircle.radius(this.originradius * this.position[2]);
         if (this.kcircle.radius() < 1) this.kcircle.radius(1);
      };
   };

});

<|endoftext|>


<commit_before>(function () {
	var board = document.getElementById('board');
	var maxX;
	var maxY;
	var step = 0;
	var speed = 20;
	var time;

	window.onresize = function () {
		maxX = board.clientWidth / 5;
		maxY = board.clientHeight / 5;
	};
	window.onresize();

	function createSnake(x, y, angle, keyLeft, keyRight, keyBoost, className) {
		return {
			x: x,
			y: y,
			angle: angle,
			speed: 1,
			keyLeft: keyLeft,
			keyRight: keyRight,
			keyBoost: keyBoost,
			className: className,
			points: createPoints(x, y, className),
			invincible: 0,
		};
	}

	function createPoints(x, y, className) {
		var points = [];
		var length = 30;
		for (var i = 0; i < length; i++) {
			points.push(createPoint(x - length + i + 1, y, 'point ' + className));
		}
		updateScore(className, points.length);
		return points;
	}

	function randomX() {
		return Math.round(Math.random() * maxX);
	}

	function randomY() {
		return Math.round(Math.random() * maxY);
	}

	var Keys = {
		LEFT: 37,
		RIGHT: 39,
		UP: 38,
		A: 65,
		B: 66,
		M: 77,
		N: 78,
		X: 88,
		Z: 90,
	};

	var snakes = [
		createSnake(40, 40, 0, Keys.LEFT, Keys.RIGHT, Keys.UP, ''),
		createSnake(40, 60, 0, Keys.Z, Keys.X, Keys.A, 'snake2'),
		createSnake(40, 80, 0, Keys.N, Keys.M, Keys.B, 'snake3'),
	];

	var foods = [];
	for (var i = 0; i < 10; i++) {
		var point = createPoint(randomX(), randomY(), 'food');
		foods.push(point);
	}

	function createPoint(x, y, className) {
		var point = {point: document.createElement('div')};
		point.point.className = className;
		putPoint(point, x, y);
		board.appendChild(point.point);
		return point;
	}

	var pressedKeys = {};

	document.body.onkeyup = function(event) {
		delete pressedKeys[event.keyCode];
	};

	document.body.onkeydown = function(event) {
		pressedKeys[event.keyCode] = true;
	}

	function changeAngle(snake, delta) {
		snake.angle = (snake.angle + 10 * delta + 360) % 360;
	}

	function collides(point, x, y, delta) {
		return Math.abs(x - getX(point)) < delta && Math.abs(y - getY(point)) < delta;
	}

	function putPoint(point, x, y) {
		point.x = x;
		point.y = y;
		point.point.style.marginLeft = 5 * x + 'px';
		point.point.style.marginTop = 5 * y + 'px';
	}

	function removePoint(point, x, y) {
		if (point.point.parentElement) {
			point.point.parentElement.removeChild(point.point);
		}
	}

	function getX(point) {
		return point.x;
	}

	function getY(point) {
		return point.y;
	}

	function die(snake) {
		for (var i = 0, point; point = snake.points[i]; i++) {
			if (i % 10 == 0) {
				point.fromDead = true;
				point.point.className = 'food fromDead';
				foods.push(point);
			} else {
				removePoint(point);
			}
		}
		snake.x = randomX();
		snake.y = randomY();
		snake.angle = 0;
		snake.invincible = 10;
		snake.points = createPoints(snake.x, snake.y, snake.className);
	}

	function moveSnake(snake) {
		snake.speed = 1;
		for (var keyCode in pressedKeys) {
			if (keyCode == snake.keyLeft) {
				changeAngle(snake, -1);
			} else if (keyCode == snake.keyRight) {
				changeAngle(snake, 1);
			}
			if (keyCode == snake.keyBoost) {
				snake.speed = 2;
			}
		}
		snake.x = (snake.x + Math.cos(snake.angle / 180 * Math.PI) * snake.speed + maxX) % maxX;
		snake.y = (snake.y + Math.sin(snake.angle / 180 * Math.PI) * snake.speed + maxY) % maxY;
		if (snake.invincible) {
			snake.invincible--;
		}

		if (!snake.invincible) {
			for (var i = 0; i < snakes.length; i++) {
				if (snake != snakes[i] && !snakes[i].invincible) {
					for (var j = 0; j < snakes[i].points.length; j++) {
						if (collides(snakes[i].points[j], snake.x, snake.y, 1)) {
							die(snake);
							return;
						}
					}
				}
			}
		}

		if (snake.speed > 1 && snake.points.length > 1 && step % 10 == 0) {
			var food = snake.points.shift();
			food.fromDead = true;
			food.point.className = 'food fromDead';
			foods.push(food);
		}

		var ate = 0;
		for (var i = 0; i < foods.length; i++) {
			var food = foods[i];
			if (food && collides(food, snake.x, snake.y, 2)) {
				if (!food.fromDead) {
					putPoint(food, randomX(), randomY());
					ate += 2;
				} else {
					removePoint(food);
					foods[i] = undefined;
					ate++;
				}
			}
		}
		var point = snake.points.shift();
		if (!point) {
			return;
		}
		for (var i = 0; i < ate; i++) {
			snake.points.unshift(createPoint(getX(point), getY(point), 'point ' + snake.className));
		}
		putPoint(point, snake.x, snake.y);
		snake.points.push(point);
		updateScore(snake.className, snake.points.length);
	}

	function updateScore(className, score) {
		document.querySelector('.score' + (className ? '.' + className : '')).textContent = score;
	}

	var timeout;
	function loop() {
		for (var i = 0, snake; snake = snakes[i]; i++) {
			moveSnake(snake);
		}
		step++;
		var oldTime = time;
		time = Date.now();
		timeout = window.setTimeout(loop, 2000 / speed + oldTime - time);
	}

	window.onblur = function () {
		window.clearTimeout(timeout);
	};

	window.onfocus = function () {
		time = Date.now() - 1000 / speed;
		loop();
	};

	if (document.hasFocus()) {
		window.onfocus();
	}
})();
<commit_msg>Don't use bottom and right edge<commit_after>(function () {
	var board = document.getElementById('board');
	var maxX;
	var maxY;
	var step = 0;
	var speed = 20;
	var time;

	window.onresize = function () {
		maxX = board.clientWidth / 5;
		maxY = board.clientHeight / 5;
	};
	window.onresize();

	function createSnake(x, y, angle, keyLeft, keyRight, keyBoost, className) {
		return {
			x: x,
			y: y,
			angle: angle,
			speed: 1,
			keyLeft: keyLeft,
			keyRight: keyRight,
			keyBoost: keyBoost,
			className: className,
			points: createPoints(x, y, className),
			invincible: 0,
		};
	}

	function createPoints(x, y, className) {
		var points = [];
		var length = 30;
		for (var i = 0; i < length; i++) {
			points.push(createPoint(x - length + i + 1, y, 'point ' + className));
		}
		updateScore(className, points.length);
		return points;
	}

	function randomX() {
		return Math.floor(Math.random() * maxX);
	}

	function randomY() {
		return Math.floor(Math.random() * maxY);
	}

	var Keys = {
		LEFT: 37,
		RIGHT: 39,
		UP: 38,
		A: 65,
		B: 66,
		M: 77,
		N: 78,
		X: 88,
		Z: 90,
	};

	var snakes = [
		createSnake(40, 40, 0, Keys.LEFT, Keys.RIGHT, Keys.UP, ''),
		createSnake(40, 60, 0, Keys.Z, Keys.X, Keys.A, 'snake2'),
		createSnake(40, 80, 0, Keys.N, Keys.M, Keys.B, 'snake3'),
	];

	var foods = [];
	for (var i = 0; i < 10; i++) {
		var point = createPoint(randomX(), randomY(), 'food');
		foods.push(point);
	}

	function createPoint(x, y, className) {
		var point = {point: document.createElement('div')};
		point.point.className = className;
		putPoint(point, x, y);
		board.appendChild(point.point);
		return point;
	}

	var pressedKeys = {};

	document.body.onkeyup = function(event) {
		delete pressedKeys[event.keyCode];
	};

	document.body.onkeydown = function(event) {
		pressedKeys[event.keyCode] = true;
	}

	function changeAngle(snake, delta) {
		snake.angle = (snake.angle + 10 * delta + 360) % 360;
	}

	function collides(point, x, y, delta) {
		return Math.abs(x - getX(point)) < delta && Math.abs(y - getY(point)) < delta;
	}

	function putPoint(point, x, y) {
		point.x = x;
		point.y = y;
		point.point.style.marginLeft = 5 * x + 'px';
		point.point.style.marginTop = 5 * y + 'px';
	}

	function removePoint(point, x, y) {
		if (point.point.parentElement) {
			point.point.parentElement.removeChild(point.point);
		}
	}

	function getX(point) {
		return point.x;
	}

	function getY(point) {
		return point.y;
	}

	function die(snake) {
		for (var i = 0, point; point = snake.points[i]; i++) {
			if (i % 10 == 0) {
				point.fromDead = true;
				point.point.className = 'food fromDead';
				foods.push(point);
			} else {
				removePoint(point);
			}
		}
		snake.x = randomX();
		snake.y = randomY();
		snake.angle = 0;
		snake.invincible = 10;
		snake.points = createPoints(snake.x, snake.y, snake.className);
	}

	function moveSnake(snake) {
		snake.speed = 1;
		for (var keyCode in pressedKeys) {
			if (keyCode == snake.keyLeft) {
				changeAngle(snake, -1);
			} else if (keyCode == snake.keyRight) {
				changeAngle(snake, 1);
			}
			if (keyCode == snake.keyBoost) {
				snake.speed = 2;
			}
		}
		snake.x = (snake.x + Math.cos(snake.angle / 180 * Math.PI) * snake.speed + maxX) % maxX;
		snake.y = (snake.y + Math.sin(snake.angle / 180 * Math.PI) * snake.speed + maxY) % maxY;
		if (snake.invincible) {
			snake.invincible--;
		}

		if (!snake.invincible) {
			for (var i = 0; i < snakes.length; i++) {
				if (snake != snakes[i] && !snakes[i].invincible) {
					for (var j = 0; j < snakes[i].points.length; j++) {
						if (collides(snakes[i].points[j], snake.x, snake.y, 1)) {
							die(snake);
							return;
						}
					}
				}
			}
		}

		if (snake.speed > 1 && snake.points.length > 1 && step % 10 == 0) {
			var food = snake.points.shift();
			food.fromDead = true;
			food.point.className = 'food fromDead';
			foods.push(food);
		}

		var ate = 0;
		for (var i = 0; i < foods.length; i++) {
			var food = foods[i];
			if (food && collides(food, snake.x, snake.y, 2)) {
				if (!food.fromDead) {
					putPoint(food, randomX(), randomY());
					ate += 2;
				} else {
					removePoint(food);
					foods[i] = undefined;
					ate++;
				}
			}
		}
		var point = snake.points.shift();
		if (!point) {
			return;
		}
		for (var i = 0; i < ate; i++) {
			snake.points.unshift(createPoint(getX(point), getY(point), 'point ' + snake.className));
		}
		putPoint(point, snake.x, snake.y);
		snake.points.push(point);
		updateScore(snake.className, snake.points.length);
	}

	function updateScore(className, score) {
		document.querySelector('.score' + (className ? '.' + className : '')).textContent = score;
	}

	var timeout;
	function loop() {
		for (var i = 0, snake; snake = snakes[i]; i++) {
			moveSnake(snake);
		}
		step++;
		var oldTime = time;
		time = Date.now();
		timeout = window.setTimeout(loop, 2000 / speed + oldTime - time);
	}

	window.onblur = function () {
		window.clearTimeout(timeout);
	};

	window.onfocus = function () {
		time = Date.now() - 1000 / speed;
		loop();
	};

	if (document.hasFocus()) {
		window.onfocus();
	}
})();
<|endoftext|>


<commit_before>/* @flow */

// Simple state of the overall proof result
export type SimpleProofState = 'normal' | 'warning' | 'error' | 'pending'

// Constants
export const normal: SimpleProofState = 'normal'
export const warning: SimpleProofState = 'warning'
export const error: SimpleProofState = 'error'
export const pending: SimpleProofState = 'pending'

// Actions
export const registerIdentifyUi = 'tracker:registerIdentifyUi'
export const markActiveIdentifyUi = 'tracker:markActive'

export const updateUsername = 'tracker:updateUsername'
export const updateUserInfo = 'tracker:updateUserInfo'

export const setProofs = 'tracker:setProofs'
export const updateProof = 'tracker:updateProof'

export const updateProofState = 'tracker:udpateProofState'

export const onCloseFromActionBar = 'tracker:onCloseFromActionBar'
export const onCloseFromHeader = 'tracker:onCloseFromHeader'

export const onRefollow = 'tracker:onRefollow'
export const onUnfollow = 'tracker:onUnfollow'
export const onFollowHelp = 'tracker:onFollowHelp'
export const onFollowChecked = 'tracker:onFollowChecked'
<commit_msg>Fix typo<commit_after>/* @flow */

// Simple state of the overall proof result
export type SimpleProofState = 'normal' | 'warning' | 'error' | 'pending'

// Constants
export const normal: SimpleProofState = 'normal'
export const warning: SimpleProofState = 'warning'
export const error: SimpleProofState = 'error'
export const pending: SimpleProofState = 'pending'

// Actions
export const registerIdentifyUi = 'tracker:registerIdentifyUi'
export const markActiveIdentifyUi = 'tracker:markActive'

export const updateUsername = 'tracker:updateUsername'
export const updateUserInfo = 'tracker:updateUserInfo'

export const setProofs = 'tracker:setProofs'
export const updateProof = 'tracker:updateProof'

export const updateProofState = 'tracker:updateProofState'

export const onCloseFromActionBar = 'tracker:onCloseFromActionBar'
export const onCloseFromHeader = 'tracker:onCloseFromHeader'

export const onRefollow = 'tracker:onRefollow'
export const onUnfollow = 'tracker:onUnfollow'
export const onFollowHelp = 'tracker:onFollowHelp'
export const onFollowChecked = 'tracker:onFollowChecked'
<|endoftext|>


<commit_before>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

(
function(thiz){

    console.log("========>");
    console.log("========> RJS bootstrap ...");
    console.log("========>");

    //console.log(thiz);
    console.log(process.cwd());
    //console.log(process.env);

    var fs = nodeRequire("fs");
    var path = nodeRequire("path");

    var args = process.argv.slice(3);
    console.log(args);

    // relative to process.cwd(), folder that contains this config file
    var configDir = args[0];
    var i = configDir.lastIndexOf("/");
    configDir = configDir.substr(0, i).replace(/\.\//g, '');
    console.log(configDir);
    process._RJS_Path_RelCwd__ConfigDir = configDir;

    process._RJS_Path_RelCwd__ConfigDir_nSlashes
        = process._RJS_Path_RelCwd__ConfigDir.split('/').length - 1;

    var configCustomTarget = undefined;
    var configOverrideTarget = undefined;
    process._RJS_isSingleBundle = false;

    for (var k = 1; k < args.length; k++) {
        var parameter = args[k];

        var token = "--rjs_bundle=";
        if (parameter.indexOf(token) == 0) {

             // single or multiple bundle target
            var configBundleType = parameter;
            configBundleType = configBundleType.substr(token.length);
            console.log(configBundleType);
            process._RJS_isSingleBundle = (configBundleType === "single" ? true : false);
        }

        token = "--rjs_configCustomTarget=";
        if (parameter.indexOf(token) == 0) {

            configCustomTarget = parameter;
            configCustomTarget = configCustomTarget.substr(token.length);
            console.log(configCustomTarget);
        }

        token = "--rjs_configOverrideTarget=";
        if (parameter.indexOf(token) == 0) {

            configOverrideTarget = parameter;
            configOverrideTarget = configOverrideTarget.substr(token.length);
            console.log(configOverrideTarget);
        }

        // token = "--rjs_mainConfigFile=";
        // if (parameter.indexOf(token) == 0) {

            // // relative to this config file, array of mainConfigFile(s)
            // mainConfigFile = parameter;
            // mainConfigFile = mainConfigFile.substr(token.length);
            // mainConfigFile = mainConfigFile.split(',');
            // console.log(mainConfigFile);
            // process._RJS_mainConfigFile = mainConfigFile;
        // }

        // token = "--rjs_sources=";
        // if (parameter.indexOf(token) == 0) {

            // // relative to process.cwd(), array of source folders
            // sources = parameter;
            // sources = sources.substr(token.length);
            // sources = sources.split(',');
            // console.log(sources);
        // }
    }

    // if (!process._RJS_isSingleBundle)
    // {
    //     // relative to process.cwd()
    //     var copiedSourcesDir = "/build-output/_SOURCES";
    //
    //     var fs = nodeRequire("fs");
    //
    //     var req = requirejs({
    //         context: 'build'
    //     });
    //     var nodeFile = req('node/file');
    //
    //     var regExpFilter= /\w/;
    //     var onlyCopyNew = false;
    //
    //     var destDir = process.cwd() + copiedSourcesDir;
    //     console.log("===> Destination source folder: " + destDir);
    // }

    // relative to this config file, points into the above sources folder,
    // which is located at the topmost level (where the build process is invoked from)
    process._RJS_baseUrl = function(level) {
        var n = process._RJS_Path_RelCwd__ConfigDir_nSlashes - level;

        var back = "..";
        for (var i = 0; i < n; i++) {
            back = back + "/..";
        }
        // console.log(level);
        // console.log(n);
        // console.log(back);

        return process._RJS_isSingleBundle ? back : (back + "/build-output/XXX"); //copiedSourcesDir
    };

    function rootDir(level) {
      var n = process._RJS_Path_RelCwd__ConfigDir_nSlashes - level;

      var folderPath = process._RJS_Path_RelCwd__ConfigDir.split('/');

      var forward = "";
      for (var i = 0; i < n; i++) {
          forward = forward + '/' + folderPath[i];
      }
      // console.log(level);
      // console.log(n);
      // console.log(forward);

      return forward;
    }

    // relative to the above baseUrl,
    // which is located at the topmost level (where the build process is invoked from)
    process._RJS_rootDir = function(level) {
        return (process._RJS_isSingleBundle ? "./" : "../..") + rootDir(level);
    };

    var mainConfigFile = [];

    var N = process._RJS_Path_RelCwd__ConfigDir_nSlashes + 1;
    for (var i = 0; i < N; i++) {
        var pathPrefix = "";

        for (var j = 0; j < i; j++) {
            pathPrefix = pathPrefix + "../";
        }
        pathPrefix = pathPrefix + "../build-config/";

        if (i == N-1 && !process._RJS_isSingleBundle)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_multiple-bundles_external-libs.js");
        }

        if (!configOverrideTarget)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_" + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + ((i == N-1) && configCustomTarget ? configCustomTarget : "") + ".js");

            var configPluginsPath = path.join(process.cwd(), rootDir(i), "build-config", "RequireJS_config_plugins.js");
            var hasPluginsConfig = false;
            try {
                fs.accessSync(configPluginsPath);
                hasPluginsConfig = true;
            } catch (e) {
                // ignored
            }

            if (hasPluginsConfig) {

                var pluginsConfig = pathPrefix + "RequireJS_config_plugins.js";
                mainConfigFile.push(pluginsConfig);
                console.log("Plugins config:");
                console.log(configPluginsPath);
                console.log(pluginsConfig);

                var pluginsBundleConfig = pathPrefix + "RequireJS_config_plugins_"+ (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + ".js";
                mainConfigFile.push(pluginsBundleConfig);
                console.log("Plugins bundle config:");
                console.log(pluginsBundleConfig);
            }
        }
        else if (i == N-1)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_" + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + configOverrideTarget + ".js");
        }

        mainConfigFile.push(pathPrefix + "RequireJS_config_common.js");

        // if (!process._RJS_isSingleBundle)
        // {
        //     var sourcesJsonPath = process.cwd() + "/" + process._RJS_Path_RelCwd__ConfigDir + "/" + pathPrefix + "RequireJS_sources.json";
        //     console.log(sourcesJsonPath);
        //
        //     var sourcesJson = fs.readFileSync(
        //         sourcesJsonPath,
        //         {encoding: 'utf-8'});
        //     var sources = JSON.parse(sourcesJson).sourceDirsToCopy;
        //     for (var k = 0; k < sources.length; k++) {
        //         var srcDir = sources[k];
        //         srcDir = process.cwd() + "/" + process._RJS_Path_RelCwd__ConfigDir + "/" + pathPrefix + srcDir;
        //         console.log("... Copying directory contents: " + srcDir);
        //
        //         nodeFile.copyDir(srcDir, destDir, regExpFilter, onlyCopyNew);
        //     }
        // }
    }

    console.log(mainConfigFile);
    process._RJS_mainConfigFile = mainConfigFile;

    //process.exit(1);
    //throw new Error("HALT");

    return true;
}(this)
?
{
    mainConfigFile: process._RJS_mainConfigFile,

    optimize: "none",
    generateSourceMaps: true,
    preserveLicenseComments: true,

        // generateSourceMaps: true,
        // preserveLicenseComments: false,
        //
        // optimize: "uglify2",
        //
        // uglify2: {
        //   mangle: true,
        //   compress: true,
        //   'screw-ie8': true
        // },

    inlineText: true,

    //xhtml: true, //document.createElementNS()

    /* http://requirejs.org/docs/api.html#config-waitSeconds */
    waitSeconds: 1,

    removeCombined: true,

    //findNestedDependencies: true,

    wrap: false,

    wrapShim: false,

    normalizeDirDefines: 'all',

    onBuildRead: function (moduleName, path, contents) {
        //console.log("onBuildRead: " + moduleName + " -- " + path);

        return contents;
    },

    onBuildWrite: function (moduleName, path, contents) {
        //console.log("onBuildWrite: " + moduleName + " -- " + path);

        return contents;
    },

    // MUST be in root config file because of access to context-dependent 'config'
    onModuleBundleComplete: function(data) {

        var filePath = process.cwd()
            + "/"
            + process._RJS_Path_RelCwd__ConfigDir
            + "/RequireJS_function_"
            + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles")
            + "_complete.js";

        var fs = nodeRequire("fs");
        fs.readFile(
            filePath,
            {encoding: 'utf-8'},
            function(err, fileContents) {
                if (!err) {
                    var func = eval("("+fileContents+")");
                    return func(data);
                } else {
                    console.log(err);
                }
            }
        );
    }
}
:
function(){console.log("NOOP");return {};}()
)
<commit_msg>uglify on/off toggle from command line or ENV var (RequireJS build is by default uglify-ed)<commit_after>//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.

(
function(thiz){

    console.log("========>");
    console.log("========> RJS bootstrap ...");
    console.log("========>");

    //console.log(thiz);
    console.log(process.cwd());
    //console.log(process.env);

    var fs = nodeRequire("fs");
    var path = nodeRequire("path");

    var args = process.argv.slice(3);
    console.log(args);

    // relative to process.cwd(), folder that contains this config file
    var configDir = args[0];
    var i = configDir.lastIndexOf("/");
    configDir = configDir.substr(0, i).replace(/\.\//g, '');
    console.log(configDir);
    process._RJS_Path_RelCwd__ConfigDir = configDir;

    process._RJS_Path_RelCwd__ConfigDir_nSlashes
        = process._RJS_Path_RelCwd__ConfigDir.split('/').length - 1;

    var configCustomTarget = undefined;
    var configOverrideTarget = undefined;
    process._RJS_isSingleBundle = false;

    process._RJS_isUgly = true;

    // For example, command line parameter after "npm run SCRIPT_NAME":
    //--readium-js-viewer:RJS_UGLY=no
    // or:
    //--readium-shared-js:RJS_UGLY=false
    // or:
    //--readium-cfi-js:RJS_UGLY=FALSE
    //
    // ... or ENV shell variable, e.g. PowerShell:
    //Set-Item Env:RJS_UGLY no
    console.log('process.env.npm_package_config_RJS_UGLY:');
    console.log(process.env.npm_package_config_RJS_UGLY);
    console.log('process.env[RJS_UGLY]:');
    console.log(process.env['RJS_UGLY']);
    if (process.env.npm_package_config_RJS_UGLY)
    		process.env['RJS_UGLY'] = process.env.npm_package_config_RJS_UGLY;

    if (typeof process.env['RJS_UGLY'] !== "undefined") {
        var ugly = process.env['RJS_UGLY'];
        ugly = ugly.toLowerCase();
        if (ugly === "false" || ugly === "no") {
            process._RJS_isUgly = false;
        } else {
            process._RJS_isUgly = true;
        }
    }

    for (var k = 1; k < args.length; k++) {
        var parameter = args[k];

        var token = "--rjs_bundle=";
        if (parameter.indexOf(token) == 0) {

             // single or multiple bundle target
            var configBundleType = parameter;
            configBundleType = configBundleType.substr(token.length);
            console.log(configBundleType);
            process._RJS_isSingleBundle = (configBundleType === "single" ? true : false);
        }

        token = "--rjs_configCustomTarget=";
        if (parameter.indexOf(token) == 0) {

            configCustomTarget = parameter;
            configCustomTarget = configCustomTarget.substr(token.length);
            console.log(configCustomTarget);
        }

        token = "--rjs_configOverrideTarget=";
        if (parameter.indexOf(token) == 0) {

            configOverrideTarget = parameter;
            configOverrideTarget = configOverrideTarget.substr(token.length);
            console.log(configOverrideTarget);
        }

        token = "--rjs_isUgly=";
        if (parameter.indexOf(token) == 0) {

            process._RJS_isUgly = parameter;
            process._RJS_isUgly = process._RJS_isUgly.substr(token.length);
            process._RJS_isUgly = process._RJS_isUgly.toLowerCase();
            if (process._RJS_isUgly === "false" || process._RJS_isUgly === "no") {
                process._RJS_isUgly = false;
            } else {
                process._RJS_isUgly = true;
            }
            console.log("Uglify: " + process._RJS_isUgly);
        }

        // token = "--rjs_mainConfigFile=";
        // if (parameter.indexOf(token) == 0) {

            // // relative to this config file, array of mainConfigFile(s)
            // mainConfigFile = parameter;
            // mainConfigFile = mainConfigFile.substr(token.length);
            // mainConfigFile = mainConfigFile.split(',');
            // console.log(mainConfigFile);
            // process._RJS_mainConfigFile = mainConfigFile;
        // }

        // token = "--rjs_sources=";
        // if (parameter.indexOf(token) == 0) {

            // // relative to process.cwd(), array of source folders
            // sources = parameter;
            // sources = sources.substr(token.length);
            // sources = sources.split(',');
            // console.log(sources);
        // }
    }

    // if (!process._RJS_isSingleBundle)
    // {
    //     // relative to process.cwd()
    //     var copiedSourcesDir = "/build-output/_SOURCES";
    //
    //     var fs = nodeRequire("fs");
    //
    //     var req = requirejs({
    //         context: 'build'
    //     });
    //     var nodeFile = req('node/file');
    //
    //     var regExpFilter= /\w/;
    //     var onlyCopyNew = false;
    //
    //     var destDir = process.cwd() + copiedSourcesDir;
    //     console.log("===> Destination source folder: " + destDir);
    // }

    // relative to this config file, points into the above sources folder,
    // which is located at the topmost level (where the build process is invoked from)
    process._RJS_baseUrl = function(level) {
        var n = process._RJS_Path_RelCwd__ConfigDir_nSlashes - level;

        var back = "..";
        for (var i = 0; i < n; i++) {
            back = back + "/..";
        }
        // console.log(level);
        // console.log(n);
        // console.log(back);

        return process._RJS_isSingleBundle ? back : (back + "/build-output/XXX"); //copiedSourcesDir
    };

    function rootDir(level) {
      var n = process._RJS_Path_RelCwd__ConfigDir_nSlashes - level;

      var folderPath = process._RJS_Path_RelCwd__ConfigDir.split('/');

      var forward = "";
      for (var i = 0; i < n; i++) {
          forward = forward + '/' + folderPath[i];
      }
      // console.log(level);
      // console.log(n);
      // console.log(forward);

      return forward;
    }

    // relative to the above baseUrl,
    // which is located at the topmost level (where the build process is invoked from)
    process._RJS_rootDir = function(level) {
        return (process._RJS_isSingleBundle ? "./" : "../..") + rootDir(level);
    };

    var mainConfigFile = [];

    var N = process._RJS_Path_RelCwd__ConfigDir_nSlashes + 1;
    for (var i = 0; i < N; i++) {
        var pathPrefix = "";

        for (var j = 0; j < i; j++) {
            pathPrefix = pathPrefix + "../";
        }
        pathPrefix = pathPrefix + "../build-config/";

        if (i == N-1 && !process._RJS_isSingleBundle)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_multiple-bundles_external-libs.js");
        }

        if (!configOverrideTarget)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_" + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + ((i == N-1) && configCustomTarget ? configCustomTarget : "") + ".js");

            var configPluginsPath = path.join(process.cwd(), rootDir(i), "build-config", "RequireJS_config_plugins.js");
            var hasPluginsConfig = false;
            try {
                fs.accessSync(configPluginsPath);
                hasPluginsConfig = true;
            } catch (e) {
                // ignored
            }

            if (hasPluginsConfig) {

                var pluginsConfig = pathPrefix + "RequireJS_config_plugins.js";
                mainConfigFile.push(pluginsConfig);
                console.log("Plugins config:");
                console.log(configPluginsPath);
                console.log(pluginsConfig);

                var pluginsBundleConfig = pathPrefix + "RequireJS_config_plugins_"+ (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + ".js";
                mainConfigFile.push(pluginsBundleConfig);
                console.log("Plugins bundle config:");
                console.log(pluginsBundleConfig);
            }
        }
        else if (i == N-1)
        {
            mainConfigFile.push(pathPrefix + "RequireJS_config_" + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles") + configOverrideTarget + ".js");
        }

        mainConfigFile.push(pathPrefix + "RequireJS_config_common.js");

        // if (!process._RJS_isSingleBundle)
        // {
        //     var sourcesJsonPath = process.cwd() + "/" + process._RJS_Path_RelCwd__ConfigDir + "/" + pathPrefix + "RequireJS_sources.json";
        //     console.log(sourcesJsonPath);
        //
        //     var sourcesJson = fs.readFileSync(
        //         sourcesJsonPath,
        //         {encoding: 'utf-8'});
        //     var sources = JSON.parse(sourcesJson).sourceDirsToCopy;
        //     for (var k = 0; k < sources.length; k++) {
        //         var srcDir = sources[k];
        //         srcDir = process.cwd() + "/" + process._RJS_Path_RelCwd__ConfigDir + "/" + pathPrefix + srcDir;
        //         console.log("... Copying directory contents: " + srcDir);
        //
        //         nodeFile.copyDir(srcDir, destDir, regExpFilter, onlyCopyNew);
        //     }
        // }
    }

    console.log(mainConfigFile);
    process._RJS_mainConfigFile = mainConfigFile;

    //process.exit(1);
    //throw new Error("HALT");

    return true;
}(this)
?
{
    mainConfigFile: process._RJS_mainConfigFile,

    optimize: process._RJS_isUgly ? "uglify2" : "none",
    generateSourceMaps: true,
    preserveLicenseComments: process._RJS_isUgly ? false : true,

    uglify2: process._RJS_isUgly ? {
      mangle: true,
      compress: true,
      'screw-ie8': true
    } : undefined,

    inlineText: true,

    //xhtml: true, //document.createElementNS()

    /* http://requirejs.org/docs/api.html#config-waitSeconds */
    waitSeconds: 1,

    removeCombined: true,

    //findNestedDependencies: true,

    wrap: false,

    wrapShim: false,

    normalizeDirDefines: 'all',

    onBuildRead: function (moduleName, path, contents) {
        //console.log("onBuildRead: " + moduleName + " -- " + path);

        return contents;
    },

    onBuildWrite: function (moduleName, path, contents) {
        //console.log("onBuildWrite: " + moduleName + " -- " + path);

        return contents;
    },

    // MUST be in root config file because of access to context-dependent 'config'
    onModuleBundleComplete: function(data) {

        var filePath = process.cwd()
            + "/"
            + process._RJS_Path_RelCwd__ConfigDir
            + "/RequireJS_function_"
            + (process._RJS_isSingleBundle ? "single-bundle" : "multiple-bundles")
            + "_complete.js";

        var fs = nodeRequire("fs");
        fs.readFile(
            filePath,
            {encoding: 'utf-8'},
            function(err, fileContents) {
                if (!err) {
                    var func = eval("("+fileContents+")");
                    return func(data);
                } else {
                    console.log(err);
                }
            }
        );
    }
}
:
function(){console.log("NOOP");return {};}()
)
<|endoftext|>


<commit_before>; // semi-colon is a safety net against concatenated scripts and/or other modules which may not be closed properly.
(function ($) {
    var _defaults = {
        loader: ' ',
        statisticsInitialized: false
    };

    /**
     *
     * @type {{init: Function, foo: Function, _foo2: Function}}
     */
    var TrackwayCalendar = {
        /**
         * initial method to set up module
         */
        init: function () {
            var self = this;

            $(self.element).fullCalendar({
                header: {
                    left: 'agendaDay,agendaWeek,month',
                    center: 'title'

                },
                defaultView: 'agendaWeek',
                height: self._getCalendarHeight(),
                allDaySlot: false,
                events: Routing.generate('calendar_events'),
                editable: true,
                minTime: '06:00:00',
                maxTime: '21:00:00',
                weekends: false,
                loading: function (view, element) {
                    self._updateStatistics();
                },
                dayClick: function (date, jsEvent, view, resourceObj) {
                    $('#entryModal').EntryModal('setDate', date);
                    $('#entryModal').EntryModal('newEntry');
                },
                eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
                    if (key.command || key.control) {
                        self.copyEvent(event);
                    } else {
                        self.editEventTime(event);
                    }
                },
                eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {
                    self.editEventTime(event);
                },
                eventRender: function (event, element) {
                    element.find('.fc-title').html(event.title);
                },
                eventClick: function (event, jsEvent, view) {
                    self.editEvent(event);
                }
            });

            $(window).resize(function () {
                $(self.element).fullCalendar('option', 'height', self._getCalendarHeight());
            });

            $(window).keydown(function() {
                if (key.command || key.control) {
                    $('.fc-event.fc-draggable').addClass('copy');
                }
            });
            $(window).keyup(function() {
                if (!key.command && !key.control) {
                    $('.fc-event.fc-draggable.copy').removeClass('copy');
                }
            });
        },

        editEvent: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type == 'entry') {
                $('#entryModal').EntryModal('editEntry', idObj.id);
            } else if (idObj.type == 'absence') {
                $('#entryModal').EntryModal('editAbsence', idObj.id);
            }
        },

        editEventTime: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type != 'undefined') {
                var path = idObj.type == 'entry'
                    ? Routing.generate('timeentry_calendar_edit', {id: idObj.id})
                    : Routing.generate('absence_calendar_edit', {id: idObj.id});
                var start = event.start;
                var end = event.end;
                var oldTitle = event.title;
                event.title = oldTitle + self.settings.loader;
                $(self.element).fullCalendar('updateEvent', event);
                $.getJSON(
                    path,
                    {
                        id: idObj.id,
                        start: start.format(),
                        end: end.format()
                    },
                    function (response) {
                        event.title = oldTitle;
                        $(self.element).fullCalendar('updateEvent', event);
                        if (response.status != 'success') {
                            alert("Update failed! Reload the page and try again.");
                        } else {
                            $(self.element).fullCalendar('refetchEvents');

                            // refresh notifications in background
                            $('.notifications-menu').Notifications('refresh');
                        }
                    }
                );
            }
        },

        copyEvent: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type != 'undefined') {
                var path = idObj.type == 'entry'
                    ? Routing.generate('timeentry_calendar_copy', {id: idObj.id})
                    : Routing.generate('absence_calendar_copy', {id: idObj.id});
                var start = event.start;
                var end = event.end;
                var oldTitle = event.title;
                event.title = oldTitle + self.settings.loader;
                $(self.element).fullCalendar('updateEvent', event);
                $.getJSON(
                    path,
                    {
                        start: start.format(),
                        end: end.format()
                    },
                    function (response) {
                        $(self.element).fullCalendar('refetchEvents');

                        // refresh notifications in background
                        $('.notifications-menu').Notifications('refresh');
                    }
                );
            }
        },

        _splitEventIdString: function (idString) {
            var returnVal = {
                type: 'undefined',
                id: 0
            };
            if (idString.indexOf('entry_') > -1) {
                returnVal.type = 'entry';
            }
            if (idString.indexOf('absence_') > -1) {
                returnVal.type = 'absence';
            }
            if (returnVal.type != 'undefined') {
                returnVal.id = idString.substr(idString.indexOf('_') + 1);
            }
            return returnVal;
        },

        _getCalendarHeight: function () {
            return $(window).height() - 310;
        },

        _updateStatistics: function () {
            var self = this;
            if (!self.settings.statisticsInitialized) {
                $('#statistics').StatisticsLoader({
                    startDate: $(self.element).fullCalendar('getView').start.format(),
                    endDate: $(self.element).fullCalendar('getView').end.format()
                });
                self.settings.statisticsInitialized = true;
            } else {
                $('#statistics').StatisticsLoader(
                    'updateDates',
                    $(self.element).fullCalendar('getView').start.format(),
                    $(self.element).fullCalendar('getView').end.format()
                );
            }
        }
    };

    /**
     * [auto-generated code]
     * The actual module constructor
     *
     * @param element
     * @param options
     * @constructor
     */
    function TrackwayCalendarConstructor(element, options) {
        this.element = element;
        this.settings = $.extend({}, _defaults, options);
        this.init();
    }

    /**
     * [auto-generated code]
     * Avoid Module.prototype conflicts
     */
    $.extend(TrackwayCalendarConstructor.prototype, TrackwayCalendar);

    /**
     * [auto-generated code]
     * A module wrapper
     * - preventing against multiple instantiations and
     * - handling method calls and
     * - magic getter & setter
     *
     * @returns {*}
     * @constructor
     */
    $.fn.TrackwayCalendar = function () {
        window.uiModuleWrapper = window.uiModuleWrapper || new UIModuleWrapper({});
        return window.uiModuleWrapper.handle("TrackwayCalendar", TrackwayCalendarConstructor, this, arguments);
    };

})(jQuery, window, document);<commit_msg>Changed viewable time scale in the calendar<commit_after>; // semi-colon is a safety net against concatenated scripts and/or other modules which may not be closed properly.
(function ($) {
    var _defaults = {
        loader: ' ',
        statisticsInitialized: false
    };

    /**
     *
     * @type {{init: Function, foo: Function, _foo2: Function}}
     */
    var TrackwayCalendar = {
        /**
         * initial method to set up module
         */
        init: function () {
            var self = this;

            $(self.element).fullCalendar({
                header: {
                    left: 'agendaDay,agendaWeek,month',
                    center: 'title'

                },
                defaultView: 'agendaWeek',
                height: self._getCalendarHeight(),
                allDaySlot: false,
                events: Routing.generate('calendar_events'),
                editable: true,
                scrollTime: '06:00:00',
                weekends: false,
                loading: function (view, element) {
                    self._updateStatistics();
                },
                dayClick: function (date, jsEvent, view, resourceObj) {
                    $('#entryModal').EntryModal('setDate', date);
                    $('#entryModal').EntryModal('newEntry');
                },
                eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {
                    if (key.command || key.control) {
                        self.copyEvent(event);
                    } else {
                        self.editEventTime(event);
                    }
                },
                eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {
                    self.editEventTime(event);
                },
                eventRender: function (event, element) {
                    element.find('.fc-title').html(event.title);
                },
                eventClick: function (event, jsEvent, view) {
                    self.editEvent(event);
                }
            });

            $(window).resize(function () {
                $(self.element).fullCalendar('option', 'height', self._getCalendarHeight());
            });

            $(window).keydown(function() {
                if (key.command || key.control) {
                    $('.fc-event.fc-draggable').addClass('copy');
                }
            });
            $(window).keyup(function() {
                if (!key.command && !key.control) {
                    $('.fc-event.fc-draggable.copy').removeClass('copy');
                }
            });
        },

        editEvent: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type == 'entry') {
                $('#entryModal').EntryModal('editEntry', idObj.id);
            } else if (idObj.type == 'absence') {
                $('#entryModal').EntryModal('editAbsence', idObj.id);
            }
        },

        editEventTime: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type != 'undefined') {
                var path = idObj.type == 'entry'
                    ? Routing.generate('timeentry_calendar_edit', {id: idObj.id})
                    : Routing.generate('absence_calendar_edit', {id: idObj.id});
                var start = event.start;
                var end = event.end;
                var oldTitle = event.title;
                event.title = oldTitle + self.settings.loader;
                $(self.element).fullCalendar('updateEvent', event);
                $.getJSON(
                    path,
                    {
                        id: idObj.id,
                        start: start.format(),
                        end: end.format()
                    },
                    function (response) {
                        event.title = oldTitle;
                        $(self.element).fullCalendar('updateEvent', event);
                        if (response.status != 'success') {
                            alert("Update failed! Reload the page and try again.");
                        } else {
                            $(self.element).fullCalendar('refetchEvents');

                            // refresh notifications in background
                            $('.notifications-menu').Notifications('refresh');
                        }
                    }
                );
            }
        },

        copyEvent: function (event) {
            var self = this;
            var idObj = self._splitEventIdString(event.id);
            if (idObj.type != 'undefined') {
                var path = idObj.type == 'entry'
                    ? Routing.generate('timeentry_calendar_copy', {id: idObj.id})
                    : Routing.generate('absence_calendar_copy', {id: idObj.id});
                var start = event.start;
                var end = event.end;
                var oldTitle = event.title;
                event.title = oldTitle + self.settings.loader;
                $(self.element).fullCalendar('updateEvent', event);
                $.getJSON(
                    path,
                    {
                        start: start.format(),
                        end: end.format()
                    },
                    function (response) {
                        $(self.element).fullCalendar('refetchEvents');

                        // refresh notifications in background
                        $('.notifications-menu').Notifications('refresh');
                    }
                );
            }
        },

        _splitEventIdString: function (idString) {
            var returnVal = {
                type: 'undefined',
                id: 0
            };
            if (idString.indexOf('entry_') > -1) {
                returnVal.type = 'entry';
            }
            if (idString.indexOf('absence_') > -1) {
                returnVal.type = 'absence';
            }
            if (returnVal.type != 'undefined') {
                returnVal.id = idString.substr(idString.indexOf('_') + 1);
            }
            return returnVal;
        },

        _getCalendarHeight: function () {
            return $(window).height() - 310;
        },

        _updateStatistics: function () {
            var self = this;
            if (!self.settings.statisticsInitialized) {
                $('#statistics').StatisticsLoader({
                    startDate: $(self.element).fullCalendar('getView').start.format(),
                    endDate: $(self.element).fullCalendar('getView').end.format()
                });
                self.settings.statisticsInitialized = true;
            } else {
                $('#statistics').StatisticsLoader(
                    'updateDates',
                    $(self.element).fullCalendar('getView').start.format(),
                    $(self.element).fullCalendar('getView').end.format()
                );
            }
        }
    };

    /**
     * [auto-generated code]
     * The actual module constructor
     *
     * @param element
     * @param options
     * @constructor
     */
    function TrackwayCalendarConstructor(element, options) {
        this.element = element;
        this.settings = $.extend({}, _defaults, options);
        this.init();
    }

    /**
     * [auto-generated code]
     * Avoid Module.prototype conflicts
     */
    $.extend(TrackwayCalendarConstructor.prototype, TrackwayCalendar);

    /**
     * [auto-generated code]
     * A module wrapper
     * - preventing against multiple instantiations and
     * - handling method calls and
     * - magic getter & setter
     *
     * @returns {*}
     * @constructor
     */
    $.fn.TrackwayCalendar = function () {
        window.uiModuleWrapper = window.uiModuleWrapper || new UIModuleWrapper({});
        return window.uiModuleWrapper.handle("TrackwayCalendar", TrackwayCalendarConstructor, this, arguments);
    };

})(jQuery, window, document);<|endoftext|>


<commit_before>/*

    Name: angular-gsapify-router
    Description: Angular UI-Router animation directive allowing configuration of state transitions using [GSAP](http://www.greensock.com/gsap-js/)
    Author: jameshomer85@gmail.com
    Licence: MIT
    Usage: http://github.com/homerjam/angular-gsapify-router

*/
(function() {
    'use strict';

    angular.module('hj.gsapifyRouter', ['ui.router', 'ngAnimate'])

    .constant('TweenMax', TweenMax)

    .provider('gsapifyRouter', function() {
        var self = this;

        self.transitions = {};

        self.transitions.above = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '-100%'
            }
        };

        self.transitions.below = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '100%'
            }
        };

        self.transitions.left = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '-100%'
            }
        };

        self.transitions.right = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '100%'
            }
        };

        self.transitions.fade = {
            duration: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.fadeDelayed = {
            duration: 0.5,
            delay: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.none = {
            duration: 0,
            css: {}
        };

        self.defaults = {
            enter: 'none',
            leave: 'none'
        };

        self.transition = function(transitionName, transitionOptions) {
            self.transitions[transitionName] = transitionOptions;
        };

        self.$get = ['$rootScope', '$state', '$document', '$timeout', '$q', '$log', 'TweenMax',
            function($rootScope, $state, $document, $timeout, $q, $log, TweenMax) {
                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                    $state.previous = fromState;
                    $state.previousParams = fromParams;
                });

                var getOpts = function(state, view, enterLeave, inOut) {
                    var opts = {
                        transition: self.defaults[inOut === 'in' ? 'enter' : 'leave'],
                        priority: 0
                    };

                    if (state.data) {
                        if (state.data['gsapifyRouter.' + view] && state.data['gsapifyRouter.' + view][enterLeave]) {
                            switch (typeof state.data['gsapifyRouter.' + view][enterLeave][inOut]) {
                                case 'object':
                                    opts = angular.extend(opts, state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                    break;
                                case 'string':
                                    opts.transition = state.data['gsapifyRouter.' + view][enterLeave][inOut];
                                    break;
                            }
                        }
                    }

                    return opts;
                };

                var enter = function(element) {
                    var deferred = $q.defer();

                    element.css('visibility', 'hidden');
                    element[0].classList.add('gsapify-router-in');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        currentOpts = getOpts(current, view, 'enter', 'in'),
                        previousOpts = getOpts(previous, view, 'leave', 'in'),

                        from;

                    element[0].setAttribute('data-state', current.name);

                    if (previousOpts.priority > currentOpts.priority) {
                        from = self.transitions[previousOpts.transition];

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }

                    } else {
                        from = self.transitions[currentOpts.transition];

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }
                    }

                    var duration = from.duration,
                        vars = angular.copy(from);

                    vars.onStart = function() {
                        element.css('visibility', 'visible');
                    };

                    vars.onComplete = function() {
                        deferred.resolve();
                    };

                    if (!vars.css || Object.keys(vars.css).length === 0) {
                        vars.onStart();
                    }

                    TweenMax.from(element, duration, vars);

                    return deferred.promise;
                };

                var leave = function(element) {
                    var deferred = $q.defer();

                    element[0].classList.remove('gsapify-router-in');
                    element[0].classList.add('gsapify-router-out');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        previousOpts = getOpts(previous, view, 'leave', 'out'),
                        currentOpts = getOpts(current, view, 'enter', 'out'),

                        to;

                    if (currentOpts.priority > previousOpts.priority) {
                        to = self.transitions[currentOpts.transition];

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }

                    } else {
                        to = self.transitions[previousOpts.transition];

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }
                    }

                    var duration = to.duration,
                        vars = angular.copy(to);

                    vars.onComplete = function() {
                        deferred.resolve();
                    };

                    TweenMax.to(element, duration, vars);

                    return deferred.promise;
                };

                return {
                    enter: enter,
                    leave: leave,
                    transitions: self.transitions,
                    defaults: self.defaults
                };
            }
        ];
    })

    .animation('.gsapify-router', ['gsapifyRouter',
        function(gsapifyRouter) {
            return {
                enter: function(element, done) {
                    gsapifyRouter.enter(element).then(function() {
                        done();
                    });

                    return function(cancelled) {
                        if (cancelled) {
                            element.remove();
                        }
                    };
                },
                leave: function(element, done) {
                    gsapifyRouter.leave(element).then(function() {
                        done();
                    });
                }
            };
        }
    ]);

})();
<commit_msg>Basic events (fixes #1)<commit_after>/*

    Name: angular-gsapify-router
    Description: Angular UI-Router animation directive allowing configuration of state transitions using [GSAP](http://www.greensock.com/gsap-js/)
    Author: jameshomer85@gmail.com
    Licence: MIT
    Usage: http://github.com/homerjam/angular-gsapify-router

*/
(function() {
    'use strict';

    angular.module('hj.gsapifyRouter', ['ui.router', 'ngAnimate'])

    .constant('TweenMax', TweenMax)

    .provider('gsapifyRouter', function() {
        var self = this;

        self.transitions = {};

        self.transitions.above = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '-100%'
            }
        };

        self.transitions.below = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '100%'
            }
        };

        self.transitions.left = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '-100%'
            }
        };

        self.transitions.right = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '100%'
            }
        };

        self.transitions.fade = {
            duration: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.fadeDelayed = {
            duration: 0.5,
            delay: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.none = {
            duration: 0,
            css: {}
        };

        self.defaults = {
            enter: 'none',
            leave: 'none'
        };

        self.transition = function(transitionName, transitionOptions) {
            self.transitions[transitionName] = transitionOptions;
        };

        self.$get = ['$rootScope', '$state', '$document', '$timeout', '$q', '$log', 'TweenMax',
            function($rootScope, $state, $document, $timeout, $q, $log, TweenMax) {
                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                    $state.previous = fromState;
                    $state.previousParams = fromParams;
                });

                var getOpts = function(state, view, enterLeave, inOut) {
                    var opts = {
                        transition: self.defaults[inOut === 'in' ? 'enter' : 'leave'],
                        priority: 0
                    };

                    if (state.data) {
                        if (state.data['gsapifyRouter.' + view] && state.data['gsapifyRouter.' + view][enterLeave]) {
                            switch (typeof state.data['gsapifyRouter.' + view][enterLeave][inOut]) {
                                case 'object':
                                    opts = angular.extend(opts, state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                    break;
                                case 'string':
                                    opts.transition = state.data['gsapifyRouter.' + view][enterLeave][inOut];
                                    break;
                            }
                        }
                    }

                    return opts;
                };

                var enter = function(element) {
                    var deferred = $q.defer();

                    element.css('visibility', 'hidden');
                    element[0].classList.add('gsapify-router-in');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        currentOpts = getOpts(current, view, 'enter', 'in'),
                        previousOpts = getOpts(previous, view, 'leave', 'in'),

                        from;

                    element[0].setAttribute('data-state', current.name);

                    if (previousOpts.priority > currentOpts.priority) {
                        from = self.transitions[previousOpts.transition];

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }

                    } else {
                        from = self.transitions[currentOpts.transition];

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }
                    }

                    var duration = from.duration,
                        vars = angular.copy(from);

                    vars.onStart = function() {
                        element.css('visibility', 'visible');
                    };

                    vars.onComplete = function() {
                        deferred.resolve();
                    };

                    if (!vars.css || Object.keys(vars.css).length === 0) {
                        vars.onStart();
                    }

                    TweenMax.from(element, duration, vars);

                    return deferred.promise;
                };

                var leave = function(element) {
                    var deferred = $q.defer();

                    element[0].classList.remove('gsapify-router-in');
                    element[0].classList.add('gsapify-router-out');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        previousOpts = getOpts(previous, view, 'leave', 'out'),
                        currentOpts = getOpts(current, view, 'enter', 'out'),

                        to;

                    if (currentOpts.priority > previousOpts.priority) {
                        to = self.transitions[currentOpts.transition];

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }

                    } else {
                        to = self.transitions[previousOpts.transition];

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }
                    }

                    var duration = to.duration,
                        vars = angular.copy(to);

                    vars.onComplete = function() {
                        deferred.resolve();
                    };

                    TweenMax.to(element, duration, vars);

                    return deferred.promise;
                };

                return {
                    enter: enter,
                    leave: leave,
                    transitions: self.transitions,
                    defaults: self.defaults
                };
            }
        ];
    })

    .animation('.gsapify-router', ['$rootScope', 'gsapifyRouter',
        function($rootScope, gsapifyRouter) {
            return {
                enter: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:enterStart', element);

                    gsapifyRouter.enter(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:enterSuccess', element);

                        done();
                    });

                    return function(cancelled) {
                        if (cancelled) {
                            element.remove();
                        }
                    };
                },
                leave: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:leaveStart', element);

                    gsapifyRouter.leave(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:leaveSuccess', element);

                        done();
                    });
                }
            };
        }
    ]);

})();
<|endoftext|>


<commit_before>if(!Draw.loadImage) {
  Draw.loadImage = function(imageName, onLoad) {
    if(!Canvas.configured) {
      console.warn("KAPhy Warning - You must use Canvas.configure(); before you can draw!");
      return;
    }

    if(arguments.length === 0 || arguments.length > 2) {
      console.warn("KAPhy Warning - Draw.loadImage() takes 1 or 2 arguments.");
      return;
    }

    if(!Images[imageName]) {
      console.warn("KAPhy Warning - Tried to load invalid image.");
      return;
    }

    var imageToLoad = new Image();
    imageToLoad.onload = onLoad;
    imageToLoad.src = Images[imageName];
  };
}
<commit_msg>Update loadimage.js<commit_after>if(!Draw.loadImage) {
  Draw.loadImage = function(imageName, onLoad) {
    if(arguments.length === 0 || arguments.length > 2) {
      console.warn("KAPhy Warning - Draw.loadImage() takes 1 or 2 arguments.");
      return;
    }

    if(!Images[imageName]) {
      console.warn("KAPhy Warning - Tried to load invalid image.");
      return;
    }

    var imageToLoad = new Image();
    imageToLoad.onload = onLoad;
    imageToLoad.src = Images[imageName];
  };
}
<|endoftext|>