<commit_before>(function() {
    angular.module("TodoApp").factory("todoService", TodoService);

    function TodoService($http, $rootScope, $interval, $localStorage, methodToAction){
        var service = {
            createTodo : createTodo,
            getTodoList: getTodoList,
            updateTodo: updateTodo,
            deleteTodo: deleteTodo,
            updateOrder: updateOrder
        };
        var checksum = "notAChecksum";
        var items = [];

        $interval(pollTodoList, 1000);
        pollTodoList();
        return service;

        ///////////////////////

        function createTodo(title) {
            return $http.post("/api/todo", {
                title: title
            }).success(pollTodoList).error(broadcastError);
        }

        function updateOrder(newOrder){
            var updates = [];
            for(var i = 0; i < newOrder.length; i++){
                if(newOrder[i] !== items[i]){
                    updates.push({index: i, newTodo: newOrder[i]});
                }
            }

            $http.put("/api/order/",updates).error(broadcastError);
        }

        function getTodoList(){
            return items;
        }

        function pollTodoList() {
            return $http.get("/api/todo?checksum=" + checksum).success(function (data, status, headers) {
                if(status === 200){
                    items = data;
                    checksum = headers("checksum");
                    $localStorage.items = items;
                    $localStorage.checksum = checksum;
                    broadcastChange(items);
                }
            }).error(broadcastError);
        }

        function updateTodo(todo) {
            return $http.put("/api/todo/" + todo.id, todo).success(pollTodoList).error(broadcastError);
        }

        function deleteTodo(todoId) {
            return $http.delete("/api/todo/" + todoId).success(pollTodoList).error(broadcastError);
        }

        function broadcastChange(data) {
            $rootScope.$broadcast("todosChanged");
            return data;
        }

        function broadcastError(text, status, x,req) {
            var reqAction = methodToAction.convert(req.method);

            var reqOb;
            if(req.url.indexOf("?") > 0){
                reqOb = req.url.substring(req.url.lastIndexOf("/") + 1,req.url.indexOf("?"));
            }else{
                reqOb = req.url.substring(req.url.lastIndexOf("/") + 1);
            }

            reqOb = reqOb === "todo"? "todos": "todo " + reqOb;

            $rootScope.$broadcast("errorResponse", text, status, reqAction, reqOb);
        }

    }

})();
<commit_msg>Removed localStorage<commit_after>(function() {
    angular.module("TodoApp").factory("todoService", TodoService);

    function TodoService($http, $rootScope, $interval, methodToAction){
        var service = {
            createTodo : createTodo,
            getTodoList: getTodoList,
            updateTodo: updateTodo,
            deleteTodo: deleteTodo,
            updateOrder: updateOrder
        };
        var checksum = "notAChecksum";
        var items = [];

        $interval(pollTodoList, 1000);
        pollTodoList();
        return service;

        ///////////////////////

        function createTodo(title) {
            return $http.post("/api/todo", {
                title: title
            }).success(pollTodoList).error(broadcastError);
        }

        function updateOrder(newOrder){
            var updates = [];
            for(var i = 0; i < newOrder.length; i++){
                if(newOrder[i] !== items[i]){
                    updates.push({index: i, newTodo: newOrder[i]});
                }
            }

            $http.put("/api/order/",updates).error(broadcastError);
        }

        function getTodoList(){
            return items;
        }

        function pollTodoList() {
            return $http.get("/api/todo?checksum=" + checksum).success(function (data, status, headers) {
                if(status === 200){
                    items = data;
                    checksum = headers("checksum");
                    broadcastChange(items);
                }
            }).error(broadcastError);
        }

        function updateTodo(todo) {
            return $http.put("/api/todo/" + todo.id, todo).success(pollTodoList).error(broadcastError);
        }

        function deleteTodo(todoId) {
            return $http.delete("/api/todo/" + todoId).success(pollTodoList).error(broadcastError);
        }

        function broadcastChange(data) {
            $rootScope.$broadcast("todosChanged");
            return data;
        }

        function broadcastError(text, status, x,req) {
            var reqAction = methodToAction.convert(req.method);

            var reqOb;
            if(req.url.indexOf("?") > 0){
                reqOb = req.url.substring(req.url.lastIndexOf("/") + 1,req.url.indexOf("?"));
            }else{
                reqOb = req.url.substring(req.url.lastIndexOf("/") + 1);
            }

            reqOb = reqOb === "todo"? "todos": "todo " + reqOb;

            $rootScope.$broadcast("errorResponse", text, status, reqAction, reqOb);
        }

    }

})();
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Jul 03 2015 10:56:54 GMT-0300 (BRT)
var webpack = require('webpack');

module.exports = function(config) {
  config.set({
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'sinon', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
    './app/scripts/tests/globals.js',
      'webpack.test.config.js'
    ],

    webpack: {
      devtool: 'inline-source-map',

      resolve: {
        extensions: [ '', '.js', '.jsx' ]
      },

      module: {
        loaders: [
          { test: /\.jsx?$/, loader: 'babel-loader' }
        ]
      },

      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            'API_URL': '"http://localhost:3000"',
            'NODE_ENV': '"test"'
          }
        }),
        new webpack.DefinePlugin({
          __CLIENT__: true,
          __SERVER__: false,
          __DEVELOPMENT__: true,
          __DEVTOOLS__: false  // <-------- DISABLE redux-devtools HERE
        })
      ]
    },

    webpackServer: {
      noInfo: true
    },

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'webpack.test.config.js': [ 'webpack', 'sourcemap' ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  })
}
<commit_msg>Adds config to babel-loader to avoid Object.assign error on Travis<commit_after>// Karma configuration
// Generated on Fri Jul 03 2015 10:56:54 GMT-0300 (BRT)
var webpack = require('webpack');

module.exports = function(config) {
  config.set({
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'sinon', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
    './app/scripts/tests/globals.js',
      'webpack.test.config.js'
    ],

    webpack: {
      devtool: 'inline-source-map',

      resolve: {
        extensions: [ '', '.js', '.jsx' ]
      },

      module: {
        loaders: [
          { test: /\.jsx?$/, loader: 'babel-loader?optional=runtime' }
        ]
      },

      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            'API_URL': '"http://localhost:3000"',
            'NODE_ENV': '"test"'
          }
        }),
        new webpack.DefinePlugin({
          __CLIENT__: true,
          __SERVER__: false,
          __DEVELOPMENT__: true,
          __DEVTOOLS__: false  // <-------- DISABLE redux-devtools HERE
        })
      ]
    },

    webpackServer: {
      noInfo: true
    },

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'webpack.test.config.js': [ 'webpack', 'sourcemap' ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  })
}
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    firebase: `https://${process.env.FIREBASE_APP_NAME}.firebaseio.com`,
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      showIndex: true,
      useFireBase: false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.APP.showIndex = true;
    ENV.APP.useFireBase = true;
  }

  return ENV;
};
<commit_msg>this path doesn't get babel'd<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    firebase: 'https://' + process.env.FIREBASE_APP_NAME + '.firebaseio.com',
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {
      showIndex: true,
      useFireBase: false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {
    ENV.APP.showIndex = true;
    ENV.APP.useFireBase = true;
  }

  return ENV;
};
<|endoftext|>


<commit_before>var core = (function() {

	var public = module.parent.iosuite,
		private = {};

	private._return = 'success';

	private._response;

	private._requestFile = '';
	private._cacheFile = '';
	private._cacheFileFull = '';
	private._library = require('./library');

	public.init = function( file, parameters, response ) {

		private._response = response;

		if( file.indexOf('assets/') >= 0 ) {
			/*
			 * Request is for an image / script / style
			 */
			private._return = private._readAsset( file );
		} else {
			private._return = private._readFile( file );
		}

		return private._return;

	};

	private._readAsset = function( file ) {
		private._requestFile = './' + file.substr(0, file.lastIndexOf('.'));
		private._requestFileExt = '.' + file.split('.').pop();

		var asset;
		try {
			var textExtensions = '|.html|.htm|.css|.js|.txt|';
			if( textExtensions.indexOf( '|' + private._requestFileExt + '|' ) >= 0 ) {
				asset = private._library.format( public.module.fs.readFileSync( private._requestFile + private._requestFileExt, 'utf-8' ), {site_url: public.setting('server','url'), environment: public.setting('application','environment')} );
			} else {
				asset = public.module.fs.readFileSync( private._requestFile + private._requestFileExt );
			}

			var contentType = public.module.mime.lookup( private._requestFile + private._requestFileExt );
			private._response.writeHead( 200, { 'Content-Type': contentType } );
			private._response.end( asset, 'binary' );

		} catch(e) {
			if( e.code !== 'ENOENT' ) {
				private._response.writeHead( 404, { 'Content-Type': 'text/html', 'charset': 'utf-8' } );
				private._response.end( private._library.handleError( e, private._response ) );
			} else {
				private._writeResponse( 404, 'File does not exist', { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
			}
		}

	};

	private._readFile = function( file ) {

		var cacheHash = public.module.crypto.createHash('md5'),
			filePieces = file.split('/'),
			requestFolder = './';

		if( file.indexOf('.') >= 0 ) {
			private._requestFile = requestFolder + file.substr(0, file.lastIndexOf('.'));
			private._requestFileExt = '.' + file.split('.').pop();
		} else {
			private._requestFile = requestFolder + public.setting('application','directory') + '/' + file;
			private._requestFileExt = '.js';
		}

		console.log( private._requestFile );

		/*
		 * Generate MD5 hash cache name
		 */
		cacheHash.update( private._requestFile );
		private._cacheFile = cacheHash.digest('hex');
		private._cacheFileFull = './' + public.setting('application','directory') + '/cache/' + private._cacheFile + private._requestFileExt;

		switch( public.setting('application','environment') ) {
			case 'development':
				/*
				 * If the app is in development, create a cache file and send
				 */
				console.log( private._requestFile + private._requestFileExt );
				public.module.fs.readFile( private._requestFile + private._requestFileExt, 'utf8', private._createCacheFile );
				break;
			case 'production':
			case 'staging':
				/*
				 * If the app is in any other environment, read the cache if it exists otherwise create the file
				 * Note: The cache files shouldn't be saved to the repo, they will be created at first use
				 */
				public.module.fs.readFile( private._cacheFileFull, 'utf8', private._outputCacheFile );
				break;
		}

	};

	private._outputCacheFile = function( error, data ) {

		if( error === null ) {
			private._writeResponse( 200, data, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
		} else {
			public.module.fs.readFile( private._requestFile + private._requestFileExt, 'utf8', private._createCacheFile );
		}

	}

	private._createCacheFile = function( err, data ) {

		if( err == null ) {

			var lines, count,
				matches = data.match(/{{(.*)}}/g),
				tag = '',
				md5sum, newFile;

			for( var match in matches ) {

				var tag = matches[ match ].replace('{{','').replace('}}','').split(':'),
					call = '_setup' + tag[0].charAt(0).toUpperCase() + tag[0].slice(1);

				if( typeof private[ call ] == 'function' ) {
					data = private[ call ]( data, matches[ match ], tag[1] );
				}

			}

			data = data.replace(/[^'":]\/\/.*/g, function(match){
				return '/*' + match.replace('//','') + '*/';
			});

			newFile = public.setting('application','root') + public.setting('application','directory') + '/cache/' + private._cacheFile + private._requestFileExt;

			public.module.fs.writeFileSync( newFile, data );

			/*
			 * Run the file through the jshinter and show errors if needed
			 */
			if( public.setting('application','environment') == 'development' ) {
				//console.log( 'jshint --show-non-errors --reporter=' + public.setting('general','server_directory') + 'server/jshint_reporter.js ' + newFile );
				public.module.child_process.exec( 'jshint --show-non-errors --reporter=' + public.setting('application','root') + '/server/jshint_reporter.js' + newFile, function(error, stdout, stderr) {
					if( stdout.toString() == '' ) {
						console.log( error );
						//private._writeResponse( 200, stderr.toString(), { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
						public.module.fs.readFile( private._cacheFileFull, 'utf8', private._outputCacheFile );
					} else {
						private._writeResponse( 200, stdout, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
					}

				});
			}

		} else {
			var fourohfour = './server/404.js';
			public.module.fs.readFile( fourohfour, 'utf8', function( error, data ){
				if( error === null ) {
					private._writeResponse( 200, data, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
				} else {
					private._writeResponse( 404, error.toString() );
				}
			} );

		}

	};

	private._writeResponse = function( code, output, headers ) {

		if( headers == null ) {
			private._response.writeHead( code );
		} else {
			private._response.writeHead( code, headers );
		}
		private._response.write( output );
		private._response.end();
	}

	/*
	 * Convert template call to NetSuite getBody
	 */
	private._setupTemplate = function( data, match, file ) {

		var templateUrl = public.setting('server','url') + public.setting('application','assets') + '/templates/' + file + '.html',
			templateScript = 'nlapiRequestURL("' + templateUrl + '").getBody()';

		return data.replace( match, templateScript );

	};

	private._setupStyle = function( data, match, file ) {

		var styleUrl = public.setting('server','url') + public.setting('application','assets') + '/styles/' + file + '.css',
			styleHref = 'nlapiRequestURL("' + styleUrl + '").getBody()';

		return data.replace( match, styleHref );

	};

	private._setupClient = function( data, match, file ) {

		var scriptUrl = public.setting('server','url') + '/scripts/' + file + '.js',
			scriptSrc = 'nlapiRequestURL("' + scriptUrl + '").getBody()';

		return data.replace( match, scriptSrc );

	};

	private._setupLibrary = function( data, match, file ) {

		var scriptUrl = './' + public.setting('application','directory') + '/libraries/' + file + '.js',
			library = public.module.fs.readFileSync(scriptUrl);

		return data.replace( match, library );
	}

	return public;
})();

module.exports = core;<commit_msg>Added asset access control headers<commit_after>var core = (function() {

	var public = module.parent.iosuite,
		private = {};

	private._return = 'success';

	private._response;

	private._requestFile = '';
	private._cacheFile = '';
	private._cacheFileFull = '';
	private._library = require('./library');

	public.init = function( file, parameters, response ) {

		private._response = response;

		if( file.indexOf('assets/') >= 0 ) {
			/*
			 * Request is for an image / script / style
			 */
			private._return = private._readAsset( file );
		} else {
			private._return = private._readFile( file );
		}

		return private._return;

	};

	private._readAsset = function( file ) {
		private._requestFile = './' + file.substr(0, file.lastIndexOf('.'));
		private._requestFileExt = '.' + file.split('.').pop();

		var asset;
		try {
			var textExtensions = '|.html|.htm|.css|.js|.txt|';
			if( textExtensions.indexOf( '|' + private._requestFileExt + '|' ) >= 0 ) {
				asset = private._library.format( public.module.fs.readFileSync( private._requestFile + private._requestFileExt, 'utf-8' ), {site_url: public.setting('server','url'), environment: public.setting('application','environment')} );
			} else {
				asset = public.module.fs.readFileSync( private._requestFile + private._requestFileExt );
			}

			var contentType = public.module.mime.lookup( private._requestFile + private._requestFileExt ),
				headers = {};

			headers['Content-Type'] = contentType;
			headers["Access-Control-Allow-Headers"] = 'Origin, X-Requested-With, Content-Type, Accept';
			headers["Access-Control-Allow-Origin"] = ( public.setting('application','environment') == 'production' ) ? 'https://system.netsuite.com' : 'https://system.sandbox.netsuite.com';

			private._response.writeHead( 200, headers );
			private._response.end( asset, 'binary' );

		} catch(e) {
			if( e.code !== 'ENOENT' ) {
				private._response.writeHead( 404, { 'Content-Type': 'text/html', 'charset': 'utf-8' } );
				private._response.end( private._library.handleError( e, private._response ) );
			} else {
				private._writeResponse( 404, 'File does not exist', { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
			}
		}

	};

	private._readFile = function( file ) {

		var cacheHash = public.module.crypto.createHash('md5'),
			filePieces = file.split('/'),
			requestFolder = './';

		if( file.indexOf('.') >= 0 ) {
			private._requestFile = requestFolder + file.substr(0, file.lastIndexOf('.'));
			private._requestFileExt = '.' + file.split('.').pop();
		} else {
			private._requestFile = requestFolder + public.setting('application','directory') + '/' + file;
			private._requestFileExt = '.js';
		}

		console.log( private._requestFile );

		/*
		 * Generate MD5 hash cache name
		 */
		cacheHash.update( private._requestFile );
		private._cacheFile = cacheHash.digest('hex');
		private._cacheFileFull = './' + public.setting('application','directory') + '/cache/' + private._cacheFile + private._requestFileExt;

		switch( public.setting('application','environment') ) {
			case 'development':
				/*
				 * If the app is in development, create a cache file and send
				 */
				console.log( private._requestFile + private._requestFileExt );
				public.module.fs.readFile( private._requestFile + private._requestFileExt, 'utf8', private._createCacheFile );
				break;
			case 'production':
			case 'staging':
				/*
				 * If the app is in any other environment, read the cache if it exists otherwise create the file
				 * Note: The cache files shouldn't be saved to the repo, they will be created at first use
				 */
				public.module.fs.readFile( private._cacheFileFull, 'utf8', private._outputCacheFile );
				break;
		}

	};

	private._outputCacheFile = function( error, data ) {

		if( error === null ) {
			private._writeResponse( 200, data, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
		} else {
			public.module.fs.readFile( private._requestFile + private._requestFileExt, 'utf8', private._createCacheFile );
		}

	}

	private._createCacheFile = function( err, data ) {

		if( err == null ) {

			var lines, count,
				matches = data.match(/{{(.*)}}/g),
				tag = '',
				md5sum, newFile;

			for( var match in matches ) {

				var tag = matches[ match ].replace('{{','').replace('}}','').split(':'),
					call = '_setup' + tag[0].charAt(0).toUpperCase() + tag[0].slice(1);

				if( typeof private[ call ] == 'function' ) {
					data = private[ call ]( data, matches[ match ], tag[1] );
				}

			}

			data = data.replace(/[^'":]\/\/.*/g, function(match){
				return '/*' + match.replace('//','') + '*/';
			});

			newFile = public.setting('application','root') + public.setting('application','directory') + '/cache/' + private._cacheFile + private._requestFileExt;

			public.module.fs.writeFileSync( newFile, data );

			/*
			 * Run the file through the jshinter and show errors if needed
			 */
			if( public.setting('application','environment') == 'development' ) {
				//console.log( 'jshint --show-non-errors --reporter=' + public.setting('general','server_directory') + 'server/jshint_reporter.js ' + newFile );
				public.module.child_process.exec( 'jshint --show-non-errors --reporter=' + public.setting('application','root') + '/server/jshint_reporter.js' + newFile, function(error, stdout, stderr) {
					if( stdout.toString() == '' ) {
						console.log( error );
						//private._writeResponse( 200, stderr.toString(), { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
						public.module.fs.readFile( private._cacheFileFull, 'utf8', private._outputCacheFile );
					} else {
						private._writeResponse( 200, stdout, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
					}

				});
			}

		} else {
			var fourohfour = './server/404.js';
			public.module.fs.readFile( fourohfour, 'utf8', function( error, data ){
				if( error === null ) {
					private._writeResponse( 200, data, { 'Content-Type': 'text/plain', 'charset': 'utf-8' });
				} else {
					private._writeResponse( 404, error.toString() );
				}
			} );

		}

	};

	private._writeResponse = function( code, output, headers ) {

		if( headers == null ) {
			private._response.writeHead( code );
		} else {
			private._response.writeHead( code, headers );
		}
		private._response.write( output );
		private._response.end();
	}

	/*
	 * Convert template call to NetSuite getBody
	 */
	private._setupTemplate = function( data, match, file ) {

		var templateUrl = public.setting('server','url') + public.setting('application','assets') + '/templates/' + file + '.html',
			templateScript = 'nlapiRequestURL("' + templateUrl + '").getBody()';

		return data.replace( match, templateScript );

	};

	private._setupStyle = function( data, match, file ) {

		var styleUrl = public.setting('server','url') + public.setting('application','assets') + '/styles/' + file + '.css',
			styleHref = 'nlapiRequestURL("' + styleUrl + '").getBody()';

		return data.replace( match, styleHref );

	};

	private._setupClient = function( data, match, file ) {

		var scriptUrl = public.setting('server','url') + '/scripts/' + file + '.js',
			scriptSrc = 'nlapiRequestURL("' + scriptUrl + '").getBody()';

		return data.replace( match, scriptSrc );

	};

	private._setupLibrary = function( data, match, file ) {

		var scriptUrl = './' + public.setting('application','directory') + '/libraries/' + file + '.js',
			library = public.module.fs.readFileSync(scriptUrl);

		return data.replace( match, library );
	}

	return public;
})();

module.exports = core;<|endoftext|>


<commit_before>/**
 *
 * Crunchbutton
 *
 * @author: 	Devin Smith (http://devin.la)
 * @date: 		2012-06-20
 *
 */
var App = {
	tagline: '',
	service: '/api/',
	server: '/',
	imgServer: '/',
	cached: {},
	community: null,
	config: null,
	_init: false,
	_pageInit: false,
	_identified: false,
	touchX: null,
	touchY: null,
	touchOffset: null,
	localStorage: false,
	isPhoneGap: document.location.protocol == 'file:',
	useNativePrompt: false,
	ajaxTimeout: 5000,
	splashHidden: false
};

// enable localstorage on phonegap
App.localStorage = App.isPhoneGap;

App.NGinit = function() {
	$('body').attr('ng-controller', 'AppController');
	angular.bootstrap(document,['NGApp']);
	if (App.config.env == 'live') {
		$('.footer').addClass('footer-hide');
	}
};

var NGApp = angular.module('NGApp', []);

NGApp.config(function($compileProvider){
	$compileProvider.urlSanitizationWhitelist(/.*/);
});

NGApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider, RestaurantsService) {
	$routeProvider
		.when('/location', {
			action: 'location',
			controller: 'LocationCtrl',
			templateUrl: 'assets/view/location.html'
		})
		.when('/food-delivery', {
			action: 'restaurants',
			controller: 'RestaurantsCtrl',
			templateUrl: 'assets/view/restaurants.html'
		})
		.when('/food-delivery/:id', {
			action: 'restaurant',
			controller: 'RestaurantCtrl',
			templateUrl: 'assets/view/restaurant.html'
		})
		.when('/legal', {
			action: 'legal',
			controller: 'LegalCtrl',
			templateUrl: 'assets/view/legal.html'
		})
		.when('/help', {
			action: 'help',
			controller: 'HelpCtrl',
			templateUrl: 'assets/view/help.html'
		})
		.when('/orders', {
			action: 'orders',
			controller: 'OrdersCtrl',
			templateUrl: 'assets/view/orders.html'
		})
		.when('/order/:id', {
			action: 'order',
			controller: 'OrderCtrl',
			templateUrl: 'assets/view/order.html'
		})
		.when('/cities', {
			action: 'cities',
			controller: 'CitiesCtrl',
			templateUrl: 'assets/view/cities.html'
		})
		.when('/giftcard', {
			action: 'giftcard',
			controller: 'GiftcardCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/giftcard/:id', {
			action: 'giftcard',
			controller: 'GiftcardCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/reset', {
			action: 'reset',
			controller: 'ResetCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/reset/:id', {
			action: 'reset',
			controller: 'ResetCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/', {
			action: 'home',
			controller: 'HomeCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.otherwise({
			action: 'home',
			controller: 'DefaultCtrl',
			templateUrl: 'assets/view/home.html'
		})
	;
	// only use html5 enabled location stuff if its not in a phonegap container
	$locationProvider.html5Mode(!App.isPhoneGap);
}]);

// global route change items
NGApp.controller('AppController', function ($scope, $route, $routeParams, $rootScope, $location, AccountService, MainNavigationService, AccountSignOut) {

	// define external pointers
	App.rootScope = $rootScope;
	App.location = $location;

	// define global services
	$rootScope.account = AccountService;
	$rootScope.navigation = MainNavigationService;
	$rootScope.signout = AccountSignOut;

	$rootScope.$on('userAuth', function(e, data) {
		$rootScope.$safeApply(function($scope) {
			// @todo: remove double data
			if (data) {
				$rootScope.account.user = data;
				App.config.user = data;
			}
			// reload the actual controller
			$rootScope.reload();
		});
	});

	/* @info: this is how you watch an object rather than a property so i remeber
	$rootScope.$watch('account.user', function() {
		// indicates that the user object has changed
	}, true);
	*/

	$rootScope.reload = function() {
		$route.reload();
	};

	$rootScope.link = function(link) {
		App.go.apply(arguments);
	};

	$rootScope.back = function() {
		App.snap.close();
		history.back();
	};

	$rootScope.closePopup = function() {
		try {
			$.magnificPopup.close();
		} catch (e) {}
	};

	$rootScope.$safeApply = function(fn) {
		var phase = this.$root.$$phase;
		if (phase == '$apply' || phase == '$digest') {
			if (fn && (typeof(fn) === 'function')) {
				this.$eval(fn);
			}
		} else {
			this.$apply(fn);
		}
	};

	// @todo: we might need this in the future for when we update to angular 1.2 with animations
	/*
	// determine if we are going backwards
	$rootScope.$on('$locationChangeSuccess', function() {
		$rootScope.actualLocation = $location.path();
	});

	$rootScope.$watch(function() {
		return $location.path();
	}, function (newLocation, oldLocation) {
		if ($rootScope.actualLocation === newLocation) {
			// this is backwards
		}
	});
	*/

	$scope.$on('$routeChangeSuccess', function ($currentRoute, $previousRoute) {
		// Store the actual page
		MainNavigationService.page = $route.current.action;

		$('body').removeClass(function (index, css) {
			return (css.match (/\bpage-\S+/g) || []).join(' ');
		}).addClass('page-' + MainNavigationService.page);

		setTimeout(function() {
			App.scrollTop();
		},1);

		clearInterval($rootScope.updateOpen);

		if (App.isPhoneGap && !App.splashHidden && navigator.splashscreen) {
			App.splashHidden = true;
			setTimeout(function() {
				navigator.splashscreen.hide();
			},1);
		}
	});

	AccountService.checkUser();
});

App.alert = function(txt, title) {
	setTimeout(function() {
		// @todo: #1546
		if (App.useNativePrompt && App.isPhoneGap) {
			navigator.notification.alert(txt, null, title || 'Crunchbutton');
		} else {
			App.rootScope.$broadcast('notificationAlert', title || null, txt);
		}
	});
};

App.confirm = function(txt, title) {
	if (App.useNativePrompt && App.isPhoneGap) {
		return navigator.notification.confirm(txt, null, title || 'Crunchbutton');
	} else {
		return confirm(txt);
	}
};

App.connectionError = function() {
	App.rootScope.$broadcast('notificationAlert', 'Connection Error', 'Sorry! We could not reach the server right now. Try again when your internet is back!');
};

App.go = function(url) {
	// @todo: do some tests to figure out if we need this or not
	// App.location.path(!App.isPhoneGap ? url : 'index.html#' + url);
	App.location.path(url || '/');
	App.rootScope.$safeApply();

};

App.toggleMenu = function() {
	if (App.snap.state().state == 'left') {
		App.snap.close();
	} else {
		App.snap.open('left');
	}
};

/**
 * scroll to the top of the page
 */
App.scrollTop = function() {
	$('html, body, .snap-content-inner').scrollTop(0);
};

/**
 * Sends a tracking item to mixpanel, or to google ads if its an order
 */
App.track = function() {
	if (App.config.env != 'live') {
		return;
	}
	if (arguments[0] == 'Ordered') {
		$('img.conversion').remove();
		mixpanel.people.track_charge(arguments[1].total);
		var i = $('').appendTo($('body'));
	}
	if (arguments[1]) {
		mixpanel.track(arguments[0],arguments[1]);
	} else {
		mixpanel.track(arguments[0]);
	}
};

/**
 * Tracks a property to mixpanel
 */
App.trackProperty = function(prop, value) {
	//  || App.config.env != 'live'
	if (App.config.env != 'live') {
		return;
	}

	var params = {};
	params[prop] = value;

	mixpanel.register_once(params);
};

/**
 * Itendity the user to mixpanel
 */
App.identify = function() {
	if (App.config.env != 'live') {
		return;
	}
	if (App.config.user.uuid) {
		mixpanel.identify(App.config.user.uuid);
		mixpanel.people.set({
			$name: App.config.user.name,
			$ip: App.config.user.ip,
			$email: App.config.user.email
		});
	}
};

/**
 * controls the busy state of the app
 */
App.busy = {
	isBusy: function() {
		return $('.app-busy').length ? true : false;
	},
	makeBusy: function() {
		$('body').append($('

').append($('

')));
	},
	unBusy: function() {
		$('.app-busy').remove();
	}
};

/**
 * stuff for testing
 */
App.test = {
	card: function() {
		angular.element( 'html' ).injector().get( 'OrderService' )._test();
	},
	logout: function() {
		$.getJSON(App.service + 'logout',function(){ location.reload()});
	},
	cart: function() {
		App.alert(JSON.stringify(App.cart.items));
	},
	clearloc: function() {
		$.totalstorage('community',null);
		$.totalstorage('location_lat',null);
		$.totalstorage('location_lon',null);
		location.href = '/';
	},
	reload: function() {
		location.reload();
	}
};

App.processConfig = function(json, user) {
	if (user && !json) {
		App.config.user = user;
	} else {
		App.config = json;
	}
	App.AB.init();
	if (App.config.user) {
		App.identify();
	}
};

/**
 * global event binding and init
 */
App.init = function(config) {
	// ensure this function cant be called twice. can crash the browser if it does.
	if (App._init) {
		return;
	}
	App._init = true;

	// set a timeout for when ajax requests timeout
	$.ajaxSetup({
		timeout: App.ajaxTimeout
	});

	// replace normal click events for mobile browsers
	FastClick.attach(document.body);

	// add ios7 styles for nav bar and page height
	if (App.isPhoneGap && App.iOS7()) {
		$('body').addClass('ios7');
	}

	// add the side swipe menu for mobile view
	App.snap = new Snap({
		element: document.getElementById('snap-content'),
		disable: 'right'
	});

	var snapperCheck = function() {
		if ($(window).width() <= 768) {
			App.snap.enable();
		} else {
			App.snap.close();
			App.snap.disable();
		}
	};
	snapperCheck();

	$(window).resize(function() {
		snapperCheck();
	});

	// init the storage type. cookie, or localstorage if phonegap
	$.totalStorage.ls(App.localStorage);

	// phonegap
	if (typeof CB !== 'undefined' && CB.config) {
		App.config = CB.config;
		CB.config = null;
	}

	$(document).on('click', '.button-deliver-payment, .dp-display-item a, .dp-display-item .clickable', function() {
		$('.payment-form').show();
		$('.delivery-payment-info, .content-padder-before').hide();
	});

	$(document).on({
		mousedown: function() {
			$(this).addClass('button-bottom-click');
		},
		touchstart: function() {
			$(this).addClass('button-bottom-click');
		},
		mouseup: function() {
			$(this).removeClass('button-bottom-click');
		},
		touchend: function() {
			$(this).removeClass('button-bottom-click');
		}
	}, '.button-bottom');

	App.processConfig(config || App.config);
	App.AB.init();
	App.NGinit();
};

/**
 * dialog functions
 */
App.dialog = {
	show: function() {
		if (arguments[1]) {
			// its a title and message
			var src = '
' +
				'
' + arguments[0] + '
' +
				'
' + arguments[1] + '
' +
				'
';

		} else if ($(arguments[0]).length) {
			// its a dom element
			var src = $(arguments[0]);

		} else {
			console.log('ERROR WITH DIALOG');
			return;
		}

		$.magnificPopup.open({
			items: {
				src: src,
				type: 'inline'
			},
			fixedContentPos: true,
			fixedBgPos: true,
			closeBtnInside: true,
			preloader: false,
			midClick: true,
			removalDelay: 300,
			overflowY: 'auto',
			mainClass: 'my-mfp-zoom-in', //my-mfp-slide-bottom
			callbacks: {
				open: function() {
					setTimeout(function() {
						//$('.wrapper').addClass('dialog-open-effect-b');
					},1);
				},
				close: function() {
					$('.wrapper').removeClass('dialog-open-effect-a dialog-open-effect-b dialog-open-effect-c dialog-open-effect-d');
				}
			}
			//my-mfp-zoom-in
		});
	}
};

/**
 * play crunch audio sound
 */
App.playAudio = function(audio) {
	if (App.isPhoneGap) {
		try {
			navigator.notification.vibrate(100);
		} catch (e) {}
	}
	var audio = $('#' + audio).get(0);
	if (!audio) { return };
	try {
		audio.play();
	} catch(e){}
}
<commit_msg>added a more complex back button<commit_after>/**
 *
 * Crunchbutton
 *
 * @author: 	Devin Smith (http://devin.la)
 * @date: 		2012-06-20
 *
 */
var App = {
	tagline: '',
	service: '/api/',
	server: '/',
	imgServer: '/',
	cached: {},
	community: null,
	config: null,
	_init: false,
	_pageInit: false,
	_identified: false,
	touchX: null,
	touchY: null,
	touchOffset: null,
	localStorage: false,
	isPhoneGap: document.location.protocol == 'file:',
	useNativePrompt: false,
	ajaxTimeout: 5000,
	splashHidden: false
};

// enable localstorage on phonegap
App.localStorage = App.isPhoneGap;

App.NGinit = function() {
	$('body').attr('ng-controller', 'AppController');
	angular.bootstrap(document,['NGApp']);
	if (App.config.env == 'live') {
		$('.footer').addClass('footer-hide');
	}
};

var NGApp = angular.module('NGApp', []);

NGApp.config(function($compileProvider){
	$compileProvider.urlSanitizationWhitelist(/.*/);
});

NGApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider, RestaurantsService) {
	$routeProvider
		.when('/location', {
			action: 'location',
			controller: 'LocationCtrl',
			templateUrl: 'assets/view/location.html'
		})
		.when('/food-delivery', {
			action: 'restaurants',
			controller: 'RestaurantsCtrl',
			templateUrl: 'assets/view/restaurants.html'
		})
		.when('/food-delivery/:id', {
			action: 'restaurant',
			controller: 'RestaurantCtrl',
			templateUrl: 'assets/view/restaurant.html'
		})
		.when('/legal', {
			action: 'legal',
			controller: 'LegalCtrl',
			templateUrl: 'assets/view/legal.html'
		})
		.when('/help', {
			action: 'help',
			controller: 'HelpCtrl',
			templateUrl: 'assets/view/help.html'
		})
		.when('/orders', {
			action: 'orders',
			controller: 'OrdersCtrl',
			templateUrl: 'assets/view/orders.html'
		})
		.when('/order/:id', {
			action: 'order',
			controller: 'OrderCtrl',
			templateUrl: 'assets/view/order.html'
		})
		.when('/cities', {
			action: 'cities',
			controller: 'CitiesCtrl',
			templateUrl: 'assets/view/cities.html'
		})
		.when('/giftcard', {
			action: 'giftcard',
			controller: 'GiftcardCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/giftcard/:id', {
			action: 'giftcard',
			controller: 'GiftcardCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/reset', {
			action: 'reset',
			controller: 'ResetCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/reset/:id', {
			action: 'reset',
			controller: 'ResetCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.when('/', {
			action: 'home',
			controller: 'HomeCtrl',
			templateUrl: 'assets/view/home.html'
		})
		.otherwise({
			action: 'home',
			controller: 'DefaultCtrl',
			templateUrl: 'assets/view/home.html'
		})
	;
	// only use html5 enabled location stuff if its not in a phonegap container
	$locationProvider.html5Mode(!App.isPhoneGap);
}]);

// global route change items
NGApp.controller('AppController', function ($scope, $route, $routeParams, $rootScope, $location, AccountService, MainNavigationService, AccountSignOut) {

	// define external pointers
	App.rootScope = $rootScope;
	App.location = $location;

	// define global services
	$rootScope.account = AccountService;
	$rootScope.navigation = MainNavigationService;
	$rootScope.signout = AccountSignOut;

	$rootScope.$on('userAuth', function(e, data) {
		$rootScope.$safeApply(function($scope) {
			// @todo: remove double data
			if (data) {
				$rootScope.account.user = data;
				App.config.user = data;
			}
			// reload the actual controller
			$rootScope.reload();
		});
	});

	/* @info: this is how you watch an object rather than a property so i remeber
	$rootScope.$watch('account.user', function() {
		// indicates that the user object has changed
	}, true);
	*/

	$rootScope.reload = function() {
		$route.reload();
	};

	$rootScope.link = function(link) {
		App.go.apply(arguments);
	};

	$rootScope.back = function() {
		App.snap.close();
		var backwards = false;

		switch($route.current.action) {
			case 'order':
				backwards = '/orders';
				break;
			case 'restaurant':
				backwards = '/food-delivery';
				break;
			case 'restaurants':
				backwards = '/location';
				break;
		}

		if (backwards) {
			App.go(backwards);
		} else {
			history.back();
		}
	};

	$rootScope.closePopup = function() {
		try {
			$.magnificPopup.close();
		} catch (e) {}
	};

	$rootScope.$safeApply = function(fn) {
		var phase = this.$root.$$phase;
		if (phase == '$apply' || phase == '$digest') {
			if (fn && (typeof(fn) === 'function')) {
				this.$eval(fn);
			}
		} else {
			this.$apply(fn);
		}
	};

	// @todo: we might need this in the future for when we update to angular 1.2 with animations
	/*
	// determine if we are going backwards
	$rootScope.$on('$locationChangeSuccess', function() {
		$rootScope.actualLocation = $location.path();
	});

	$rootScope.$watch(function() {
		return $location.path();
	}, function (newLocation, oldLocation) {
		if ($rootScope.actualLocation === newLocation) {
			// this is backwards
		}
	});
	*/

	$scope.$on('$routeChangeSuccess', function ($currentRoute, $previousRoute) {
		// Store the actual page
		MainNavigationService.page = $route.current.action;

		$('body').removeClass(function (index, css) {
			return (css.match (/\bpage-\S+/g) || []).join(' ');
		}).addClass('page-' + MainNavigationService.page);

		setTimeout(function() {
			App.scrollTop();
		},1);

		clearInterval($rootScope.updateOpen);

		if (App.isPhoneGap && !App.splashHidden && navigator.splashscreen) {
			App.splashHidden = true;
			setTimeout(function() {
				navigator.splashscreen.hide();
			},1);
		}
	});

	AccountService.checkUser();
});

App.alert = function(txt, title) {
	setTimeout(function() {
		// @todo: #1546
		if (App.useNativePrompt && App.isPhoneGap) {
			navigator.notification.alert(txt, null, title || 'Crunchbutton');
		} else {
			App.rootScope.$broadcast('notificationAlert', title || null, txt);
		}
	});
};

App.confirm = function(txt, title) {
	if (App.useNativePrompt && App.isPhoneGap) {
		return navigator.notification.confirm(txt, null, title || 'Crunchbutton');
	} else {
		return confirm(txt);
	}
};

App.connectionError = function() {
	App.rootScope.$broadcast('notificationAlert', 'Connection Error', 'Sorry! We could not reach the server right now. Try again when your internet is back!');
};

App.go = function(url) {
	// @todo: do some tests to figure out if we need this or not
	// App.location.path(!App.isPhoneGap ? url : 'index.html#' + url);
	App.location.path(url || '/');
	App.rootScope.$safeApply();

};

App.toggleMenu = function() {
	if (App.snap.state().state == 'left') {
		App.snap.close();
	} else {
		App.snap.open('left');
	}
};

/**
 * scroll to the top of the page
 */
App.scrollTop = function() {
	$('html, body, .snap-content-inner').scrollTop(0);
};

/**
 * Sends a tracking item to mixpanel, or to google ads if its an order
 */
App.track = function() {
	if (App.config.env != 'live') {
		return;
	}
	if (arguments[0] == 'Ordered') {
		$('img.conversion').remove();
		mixpanel.people.track_charge(arguments[1].total);
		var i = $('').appendTo($('body'));
	}
	if (arguments[1]) {
		mixpanel.track(arguments[0],arguments[1]);
	} else {
		mixpanel.track(arguments[0]);
	}
};

/**
 * Tracks a property to mixpanel
 */
App.trackProperty = function(prop, value) {
	//  || App.config.env != 'live'
	if (App.config.env != 'live') {
		return;
	}

	var params = {};
	params[prop] = value;

	mixpanel.register_once(params);
};

/**
 * Itendity the user to mixpanel
 */
App.identify = function() {
	if (App.config.env != 'live') {
		return;
	}
	if (App.config.user.uuid) {
		mixpanel.identify(App.config.user.uuid);
		mixpanel.people.set({
			$name: App.config.user.name,
			$ip: App.config.user.ip,
			$email: App.config.user.email
		});
	}
};

/**
 * controls the busy state of the app
 */
App.busy = {
	isBusy: function() {
		return $('.app-busy').length ? true : false;
	},
	makeBusy: function() {
		$('body').append($('

').append($('

')));
	},
	unBusy: function() {
		$('.app-busy').remove();
	}
};

/**
 * stuff for testing
 */
App.test = {
	card: function() {
		angular.element( 'html' ).injector().get( 'OrderService' )._test();
	},
	logout: function() {
		$.getJSON(App.service + 'logout',function(){ location.reload()});
	},
	cart: function() {
		App.alert(JSON.stringify(App.cart.items));
	},
	clearloc: function() {
		$.totalstorage('community',null);
		$.totalstorage('location_lat',null);
		$.totalstorage('location_lon',null);
		location.href = '/';
	},
	reload: function() {
		location.reload();
	}
};

App.processConfig = function(json, user) {
	if (user && !json) {
		App.config.user = user;
	} else {
		App.config = json;
	}
	App.AB.init();
	if (App.config.user) {
		App.identify();
	}
};

/**
 * global event binding and init
 */
App.init = function(config) {
	// ensure this function cant be called twice. can crash the browser if it does.
	if (App._init) {
		return;
	}
	App._init = true;

	// set a timeout for when ajax requests timeout
	$.ajaxSetup({
		timeout: App.ajaxTimeout
	});

	// replace normal click events for mobile browsers
	FastClick.attach(document.body);

	// add ios7 styles for nav bar and page height
	if (App.isPhoneGap && App.iOS7()) {
		$('body').addClass('ios7');
	}

	// add the side swipe menu for mobile view
	App.snap = new Snap({
		element: document.getElementById('snap-content'),
		disable: 'right'
	});

	var snapperCheck = function() {
		if ($(window).width() <= 768) {
			App.snap.enable();
		} else {
			App.snap.close();
			App.snap.disable();
		}
	};
	snapperCheck();

	$(window).resize(function() {
		snapperCheck();
	});

	// init the storage type. cookie, or localstorage if phonegap
	$.totalStorage.ls(App.localStorage);

	// phonegap
	if (typeof CB !== 'undefined' && CB.config) {
		App.config = CB.config;
		CB.config = null;
	}

	$(document).on('click', '.button-deliver-payment, .dp-display-item a, .dp-display-item .clickable', function() {
		$('.payment-form').show();
		$('.delivery-payment-info, .content-padder-before').hide();
	});

	$(document).on({
		mousedown: function() {
			$(this).addClass('button-bottom-click');
		},
		touchstart: function() {
			$(this).addClass('button-bottom-click');
		},
		mouseup: function() {
			$(this).removeClass('button-bottom-click');
		},
		touchend: function() {
			$(this).removeClass('button-bottom-click');
		}
	}, '.button-bottom');

	App.processConfig(config || App.config);
	App.AB.init();
	App.NGinit();
};

/**
 * dialog functions
 */
App.dialog = {
	show: function() {
		if (arguments[1]) {
			// its a title and message
			var src = '
' +
				'
' + arguments[0] + '
' +
				'
' + arguments[1] + '
' +
				'
';

		} else if ($(arguments[0]).length) {
			// its a dom element
			var src = $(arguments[0]);

		} else {
			console.log('ERROR WITH DIALOG');
			return;
		}

		$.magnificPopup.open({
			items: {
				src: src,
				type: 'inline'
			},
			fixedContentPos: true,
			fixedBgPos: true,
			closeBtnInside: true,
			preloader: false,
			midClick: true,
			removalDelay: 300,
			overflowY: 'auto',
			mainClass: 'my-mfp-zoom-in', //my-mfp-slide-bottom
			callbacks: {
				open: function() {
					setTimeout(function() {
						//$('.wrapper').addClass('dialog-open-effect-b');
					},1);
				},
				close: function() {
					$('.wrapper').removeClass('dialog-open-effect-a dialog-open-effect-b dialog-open-effect-c dialog-open-effect-d');
				}
			}
			//my-mfp-zoom-in
		});
	}
};

/**
 * play crunch audio sound
 */
App.playAudio = function(audio) {
	if (App.isPhoneGap) {
		try {
			navigator.notification.vibrate(100);
		} catch (e) {}
	}
	var audio = $('#' + audio).get(0);
	if (!audio) { return };
	try {
		audio.play();
	} catch(e){}
}
<|endoftext|>


<commit_before>'use strict';

var AppDispatcher = require('../dispatcher/AppDispatcher');
var SettingsConstants = require('../constants/SettingsConstants');
var EventEmitter = require('events').EventEmitter;
var objectAssign = require('object-assign');

var SettingsStore = objectAssign({}, EventEmitter.prototype, {
  _defaults: { notify: false, autoplay: false },
  _settings: JSON.parse(localStorage.getItem('settings') || '{}'),

  get: function (setting) {
    return this._settings[setting] || this._defaults[setting];
  },

  getAll: function () {
    return Object.assign({}, this._defaults, this._settings);
  },

  _set: function (setting, value) {
    this._settings[setting] = value;
  },

  _setAll: function (settings) {
    Object.keys(settings).forEach(function (key) {
      this._set(key, settings[key]);
    }.bind(this));
  },

  emitChange: function () {
    this.emit('change');
  },

  addChangeListener: function(callback) {
    this.on('change', callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener('change', callback);
  }
});

SettingsStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;

  switch(action.actionType) {
    case SettingsConstants.SETTINGS_SET:
      SettingsStore._set(action.data.setting, action.data.value);
      break;

    case SettingsConstants.SETTINGS_SET_ALL:
      SettingsStore._setAll(action.data);
      break;

    default:
      return true;
  }

  SettingsStore.emitChange();
  localStorage.setItem('settings', JSON.stringify(SettingsStore.getAll()));

  return true;
});

module.exports = SettingsStore;
<commit_msg>Fixed: use ponyfill<commit_after>'use strict';

var AppDispatcher = require('../dispatcher/AppDispatcher');
var SettingsConstants = require('../constants/SettingsConstants');
var EventEmitter = require('events').EventEmitter;
var objectAssign = require('object-assign');

var SettingsStore = objectAssign({}, EventEmitter.prototype, {
  _defaults: { notify: false, autoplay: false },
  _settings: JSON.parse(localStorage.getItem('settings') || '{}'),

  get: function (setting) {
    return this._settings[setting] || this._defaults[setting];
  },

  getAll: function () {
    return objectAssign({}, this._defaults, this._settings);
  },

  _set: function (setting, value) {
    this._settings[setting] = value;
  },

  _setAll: function (settings) {
    Object.keys(settings).forEach(function (key) {
      this._set(key, settings[key]);
    }.bind(this));
  },

  emitChange: function () {
    this.emit('change');
  },

  addChangeListener: function(callback) {
    this.on('change', callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener('change', callback);
  }
});

SettingsStore.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;

  switch(action.actionType) {
    case SettingsConstants.SETTINGS_SET:
      SettingsStore._set(action.data.setting, action.data.value);
      break;

    case SettingsConstants.SETTINGS_SET_ALL:
      SettingsStore._setAll(action.data);
      break;

    default:
      return true;
  }

  SettingsStore.emitChange();
  localStorage.setItem('settings', JSON.stringify(SettingsStore.getAll()));

  return true;
});

module.exports = SettingsStore;
<|endoftext|>


<commit_before>module.exports = (config) => {
    config.set({
        browserConsoleLogOptions: {
            level: 'debug',
            format: '%b %T: %m',
            terminal: true
        },
        frameworks: ['mocha', 'chai', 'sinon'],
        files: [
            'test/*_test.js'
        ],
        preprocessors: {
            'lib/index.js': ['rollup', 'coverage'],
            'test/*_test.js': ['rollup']
        },
        rollupPreprocessor: {
            plugins: [
                require('rollup-plugin-babel')(),
                require('rollup-plugin-istanbul')({
                    exclude: ['test/*_test.js'],
                }),
            ],
            format: 'iife',
            sourceMap: 'inline'
        },
        customContextFile: 'test/context.html',
        customLaunchers: {
            'PhantomJS_Desktop': {
                base: 'PhantomJS',
                options: {
                    viewportSize: {
                        width: 800,
                        height: 600,
                    }
                }
            },
        },
        browsers: ['PhantomJS_Desktop'],
        reporters: ['mocha', 'coverage'],
        singleRun: true,
    });
};
<commit_msg>Change coverage format<commit_after>module.exports = (config) => {
    config.set({
        browserConsoleLogOptions: {
            level: 'debug',
            format: '%b %T: %m',
            terminal: true
        },
        frameworks: ['mocha', 'chai', 'sinon'],
        files: [
            'test/*_test.js'
        ],
        preprocessors: {
            'lib/index.js': ['rollup', 'coverage'],
            'test/*_test.js': ['rollup']
        },
        rollupPreprocessor: {
            plugins: [
                require('rollup-plugin-babel')(),
                require('rollup-plugin-istanbul')({
                    exclude: ['test/*_test.js'],
                }),
            ],
            format: 'iife',
            sourceMap: 'inline'
        },
        customContextFile: 'test/context.html',
        customLaunchers: {
            'PhantomJS_Desktop': {
                base: 'PhantomJS',
                options: {
                    viewportSize: {
                        width: 800,
                        height: 600,
                    }
                }
            },
        },
        browsers: ['PhantomJS_Desktop'],
        reporters: ['mocha', 'coverage'],
        coverageReporter: {
            reporters: [{type: 'lcov'}]
        },
        singleRun: true,
    });
};
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    pkgjson = require(path.resolve('./package.json'));

function getEnvValue(varName, fallback) {
    if (process.env[varName]) {
        return process.env[varName];
    }
    if (process.env[varName + '_VAR']) {
        return process.env[process.env[varName + '_VAR']];
    }
    return fallback;
}

module.exports = {
	app: {
		title: 'NXFC',
		description: 'NXFC Gateway',
		keywords: 'mongodb, express, angularjs, node.js, mongoose, passport',
		googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID',
		version: pkgjson.version || 'VERSION'
	},
	facebook: {
        clientID: process.env.FACEBOOK_ID || 'APP_ID',
        clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/facebook/callback'
    },
    twitter: {
        clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
        clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
        callbackURL: '/api/auth/twitter/callback'
    },
    google: {
        clientID: process.env.GOOGLE_ID || 'APP_ID',
        clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/google/callback'
    },
    linkedin: {
        clientID: process.env.LINKEDIN_ID || 'APP_ID',
        clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/linkedin/callback'
    },
    github: {
        clientID: process.env.GITHUB_ID || 'APP_ID',
        clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/github/callback'
    },
    mailer: {
        from: process.env.MAILER_FROM || 'MAILER_FROM',
        options: {
            service: process.env.MAILER_SERVICE_PROVIDER,
            host: process.env.MAILER_HOST,
            port: process.env.MAILER_PORT,
            secure: process.env.MAILER_SECURE,
            tls: (process.env.MAILER_REJECT_UNAUTHORISED ? {rejectUnauthorized: false} : {rejectUnauthorized: true}),
            auth: {
                user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
                pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
            }
        }
    },
    mongo: {
        host: getEnvValue('MONGO_HOST','localhost')
    },
    catalogue: {
        host: getEnvValue('CATALOGUE_HOST','localhost'),
        path: '/api',
        port: 3010
    },
    stock: {
        host: getEnvValue('STOCK_HOST','localhost'),
        path: '/api',
        port: 3040
    },
    checkout: {
        host: getEnvValue('CHECKOUT_HOST','localhost'),
        path: '/api',
        port: 3030
    },
    ghost: {
        host: getEnvValue('GHOST_HOST','localhost'),
        path: '',
        port: 3020
    },
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	ownerUsername: process.env.OWNER || 'OWNER',
	externalAddress: process.env.EXTERNAL_ADDRESS || 'localhost:' + (process.env.PORT || 3000)
};
<commit_msg>add mailchimp config<commit_after>'use strict';

var path = require('path'),
    pkgjson = require(path.resolve('./package.json'));

function getEnvValue(varName, fallback) {
    if (process.env[varName]) {
        return process.env[varName];
    }
    if (process.env[varName + '_VAR']) {
        return process.env[process.env[varName + '_VAR']];
    }
    return fallback;
}

module.exports = {
	app: {
		title: 'NXFC',
		description: 'NXFC Gateway',
		keywords: 'mongodb, express, angularjs, node.js, mongoose, passport',
		googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID',
		version: pkgjson.version || 'VERSION'
	},
	facebook: {
        clientID: process.env.FACEBOOK_ID || 'APP_ID',
        clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/facebook/callback'
    },
    twitter: {
        clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
        clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
        callbackURL: '/api/auth/twitter/callback'
    },
    google: {
        clientID: process.env.GOOGLE_ID || 'APP_ID',
        clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/google/callback'
    },
    linkedin: {
        clientID: process.env.LINKEDIN_ID || 'APP_ID',
        clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/linkedin/callback'
    },
    github: {
        clientID: process.env.GITHUB_ID || 'APP_ID',
        clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
        callbackURL: '/api/auth/github/callback'
    },
    mailer: {
        from: process.env.MAILER_FROM || 'MAILER_FROM',
        options: {
            service: process.env.MAILER_SERVICE_PROVIDER,
            host: process.env.MAILER_HOST,
            port: process.env.MAILER_PORT,
            secure: process.env.MAILER_SECURE,
            tls: (process.env.MAILER_REJECT_UNAUTHORISED ? {rejectUnauthorized: false} : {rejectUnauthorized: true}),
            auth: {
                user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
                pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
            }
        }
    },
    mongo: {
        host: getEnvValue('MONGO_HOST','localhost')
    },
    catalogue: {
        host: getEnvValue('CATALOGUE_HOST','localhost'),
        path: '/api',
        port: 3010
    },
    stock: {
        host: getEnvValue('STOCK_HOST','localhost'),
        path: '/api',
        port: 3040
    },
    checkout: {
        host: getEnvValue('CHECKOUT_HOST','localhost'),
        path: '/api',
        port: 3030
    },
    ghost: {
        host: getEnvValue('GHOST_HOST','localhost'),
        path: '',
        port: 3020
    },
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	ownerUsername: process.env.OWNER || 'OWNER',
	externalAddress: process.env.EXTERNAL_ADDRESS || 'localhost:' + (process.env.PORT || 3000),
	mailchimp: {
	    list: process.env.MAILCHIMP_LIST || 'MAILCHIMP_LIST',
	    key: process.env.MAILCHIMP_KEY || 'MAILCHIMP_KEY',
	    apiKey: process.env.MAILCHIMP_API_KEY || 'MAILCHIMP_API_KEY'
	}
};
<|endoftext|>


<commit_before>/**
 * Created by anonymous on 26/11/15 19:55.
 */

(function() {
    'use strict';

    angular
        .module('jwtAuth')
        .controller('JwtAuthHomeController', JwtAuthHomeController);

    JwtAuthHomeController.$inject = ['userData', '$log'];

    /* @ngInject */
    function JwtAuthHomeController(userData, $log) {
        var vm      = this;
        vm.getUsers = getUsers;

        activate();

        ////////////////

        function activate() {
            //
        }

        function getUsers() {
            return userData.get().then(function(response) {
                //$log.debug(response);
                vm.users = response;
                $log.debug(vm.users);
            }).catch(function(error) {
                vm.error = error;
                $log.debug('Error with status code', error.status);
                $log.debug(error);
            });
        }
    }

})();

<commit_msg>Modified home.controller<commit_after>/**
 * Created by anonymous on 26/11/15 19:55.
 */

(function() {
    'use strict';

    angular
        .module('jwtAuth')
        .controller('JwtAuthHomeController', JwtAuthHomeController);

    JwtAuthHomeController.$inject = ['userData', '$log'];

    /* @ngInject */
    function JwtAuthHomeController(userData, $log) {
        var vm      = this;
        vm.getUsers = getUsers;

        activate();

        ////////////////

        function activate() {
            //
        }

        function getUsers() {
            return userData.get().then(function(response) {
                vm.users = response;
                //$log.debug(vm.users);
            }).catch(function(error) {
                vm.error = error;
                $log.debug('Error with status code', error.status);
                $log.debug(error);
            });
        }
    }

})();

<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import { push } from 'react-router-redux';
import { batchActions } from 'redux-batched-actions';
import { List, Map, fromJS } from 'immutable';

import createReducer from '~/store/createReducer';

export const SCOPE = 'search';

// ******************************************************************
// ACTIONS
export const SEARCH = 'search/SEARCH';
export const SEARCHED = 'search/SEARCHED';
export const LOCAL_ONLY = 'search/filter/LOCAL_ONLY';
export const SELECT_PAGE = 'search/SELECT_PAGE';
export const LOADING = 'search/LOADING';

// ******************************************************************
// REDUCERS
export default createReducer(Map({
  loading: false,
  page: 1,
  pageSize: 20,
  query: '',
  results: List(),
  total: 0,
}), {
  [LOADING]: (state, { payload }) => state.set('loading', payload),
  [SEARCH]: (state, { payload = '' }) => state.set('query', payload),
  [SEARCHED]: (state, { payload: { results, total } }) => state.merge(Map({
    loading: false,
    results: fromJS(results || []),
    total: total || 0,
  })),
  [SELECT_PAGE]: (state, { payload = 1 }) => state.set('page', payload),
});

// ******************************************************************
// ACTION CREATORS
export const selectPage = (page = 1) => (dispatch, getState) => {
  const query = getState().getIn([SCOPE, 'query'], '');
  const pagePath = page > 1 ? `/${page}` : '';
  dispatch({ type: SELECT_PAGE, payload: page || 1 });
  dispatch(push(`/suche/${query}${pagePath}`));
};

export const search = (query = '') => (dispatch) => {
  dispatch(batchActions([
    { type: SEARCH, payload: query },
    { type: SEARCHED, payload: {} },
    { type: LOADING, payload: true },
    selectPage(1),
  ]));
  return dispatch({
    type: SEARCHED,
    meta: { debounce: { time: 500 } },
    promise: api => api.search(query),
  });
};

// ******************************************************************
// SELECTORS
export const getQuery = state => state.getIn([SCOPE, 'query'], '');

export const getPage = state => state.getIn([SCOPE, 'page'], 1);

export const getPageSize = state => state.getIn([SCOPE, 'pageSize'], 20);

export const getResults = state => state.getIn([SCOPE, 'results'], List());

export const getTotal = state => state.getIn([SCOPE, 'total'], 0);

export const isLoading = state => state.getIn([SCOPE, 'loading'], false);

export const getResultsByPage = createSelector(
  [getResults, getPage, getPageSize],
  (results, page, size) => results.slice(size * (page - 1), size * page)
);
<commit_msg>Fix for search not updating URL.<commit_after>import { createSelector } from 'reselect';
import { push } from 'react-router-redux';
import { batchActions } from 'redux-batched-actions';
import { List, Map, fromJS } from 'immutable';

import createReducer from '~/store/createReducer';

export const SCOPE = 'search';

// ******************************************************************
// ACTIONS
export const SEARCH = 'search/SEARCH';
export const SEARCHED = 'search/SEARCHED';
export const LOCAL_ONLY = 'search/filter/LOCAL_ONLY';
export const SELECT_PAGE = 'search/SELECT_PAGE';
export const LOADING = 'search/LOADING';

// ******************************************************************
// REDUCERS
export default createReducer(Map({
  loading: false,
  page: 1,
  pageSize: 20,
  query: '',
  results: List(),
  total: 0,
}), {
  [LOADING]: (state, { payload }) => state.set('loading', payload),
  [SEARCH]: (state, { payload = '' }) => state.set('query', payload),
  [SEARCHED]: (state, { payload: { results, total } }) => state.merge(Map({
    loading: false,
    results: fromJS(results || []),
    total: total || 0,
  })),
  [SELECT_PAGE]: (state, { payload = 1 }) => state.set('page', payload),
});

// ******************************************************************
// ACTION CREATORS
export const selectPage = (page = 1) => (dispatch, getState) => {
  const query = getState().getIn([SCOPE, 'query'], '');
  const pagePath = page > 1 ? `/${page}` : '';
  dispatch({ type: SELECT_PAGE, payload: page || 1 });
  dispatch(push(`/suche/${query}${pagePath}`));
};

export const search = (query = '') => (dispatch) => {
  dispatch(batchActions([
    { type: SEARCH, payload: query },
    { type: SEARCHED, payload: {} },
    { type: LOADING, payload: true },
  ]));
  dispatch(selectPage(1));
  return dispatch({
    type: SEARCHED,
    meta: { debounce: { time: 500 } },
    promise: api => api.search(query),
  });
};

// ******************************************************************
// SELECTORS
export const getQuery = state => state.getIn([SCOPE, 'query'], '');

export const getPage = state => state.getIn([SCOPE, 'page'], 1);

export const getPageSize = state => state.getIn([SCOPE, 'pageSize'], 20);

export const getResults = state => state.getIn([SCOPE, 'results'], List());

export const getTotal = state => state.getIn([SCOPE, 'total'], 0);

export const isLoading = state => state.getIn([SCOPE, 'loading'], false);

export const getResultsByPage = createSelector(
  [getResults, getPage, getPageSize],
  (results, page, size) => results.slice(size * (page - 1), size * page)
);
<|endoftext|>


<commit_before>import Alert from '/imports/ui/alert';
import OpeningScript from '/imports/api/openingScript/openingScript';
import './signaturePad.js';
import './preliminarySurvey.html';

const DV_HS_STEP = 0;
const ROI_STEP = 1;
const ENDED_STEP = 2;

function nextStep(currentStep) {
  switch (currentStep) {
    case DV_HS_STEP:
      return OpeningScript.skipReleaseOfInformation() ? ENDED_STEP : ROI_STEP;
    case ROI_STEP:
      return ENDED_STEP;
    case ENDED_STEP:
      return ENDED_STEP;
    default:
      if (!(OpeningScript.skipDvQuestion() && OpeningScript.skipHousingServiceQuestion())) {
        return DV_HS_STEP;
      }
      if (!OpeningScript.skipReleaseOfInformation()) return ROI_STEP;
      return ENDED_STEP;
  }
}

Template.preliminarySurvey.helpers({
  currentStep() {
    return Template.instance().activeStep.get();
  },
  skipDvQuestion() {
    return OpeningScript.skipDvQuestion();
  },
  dvQuestion() {
    return OpeningScript.dvQuestion();
  },
  skipHousingServiceQuestion() {
    return OpeningScript.skipHousingServiceQuestion();
  },
  housingServiceQuestion() {
    return OpeningScript.housingServiceQuestion();
  },
  hotlineInfo() {
    return OpeningScript.hotlineInfo();
  },
  releaseOfInformation() {
    return OpeningScript.releaseOfInformation();
  },
  showDvHsStep() {
    return Template.instance().activeStep.get() === 0;
  },
  showRoiStep() {
    return Template.instance().activeStep.get() === 1;
  },
});

Template.preliminarySurvey.events(
  {
    'click .close-cancel': (event) => {
      event.preventDefault();
      history.back();
    },
    'click .next-step': (event) => {
      event.preventDefault();
      const currentStep = Template.instance().activeStep.get();

      const signaturePad = Router.current().params.signaturePad;
      if (currentStep === ROI_STEP) {
        if (signaturePad.isEmpty()) {
          Alert.error('Please provide signature first');
          return;
        }
        if (!$('#roiCheckbox')[0].checked) {
          Alert.error('You must agree');
          return;
        }
      }

      Template.instance().activeStep.set(nextStep(currentStep));
    },
  }
);

Template.preliminarySurvey.onCreated(function onCreated() {
  this.activeStep = new ReactiveVar(nextStep());

  this.autorun(() => {
    if (this.activeStep.get() === ENDED_STEP) {
      $('#preliminarySurveyModal').modal('hide');

      const signaturePad = Router.current().params.signaturePad;
      if (signaturePad) {
        $('#create-client-form .signature').val(signaturePad.toDataURL());
        $('#create-client-form .signature-img').attr('src', signaturePad.toDataURL());
      }
    }
  });
});
<commit_msg>scroll-issue-fix<commit_after>import Alert from '/imports/ui/alert';
import OpeningScript from '/imports/api/openingScript/openingScript';
import './signaturePad.js';
import './preliminarySurvey.html';

const DV_HS_STEP = 0;
const ROI_STEP = 1;
const ENDED_STEP = 2;

function nextStep(currentStep) {
  switch (currentStep) {
    case DV_HS_STEP:
      return OpeningScript.skipReleaseOfInformation() ? ENDED_STEP : ROI_STEP;
    case ROI_STEP:
      return ENDED_STEP;
    case ENDED_STEP:
      return ENDED_STEP;
    default:
      if (!(OpeningScript.skipDvQuestion() && OpeningScript.skipHousingServiceQuestion())) {
        return DV_HS_STEP;
      }
      if (!OpeningScript.skipReleaseOfInformation()) return ROI_STEP;
      return ENDED_STEP;
  }
}

Template.preliminarySurvey.helpers({
  currentStep() {
    return Template.instance().activeStep.get();
  },
  skipDvQuestion() {
    return OpeningScript.skipDvQuestion();
  },
  dvQuestion() {
    return OpeningScript.dvQuestion();
  },
  skipHousingServiceQuestion() {
    return OpeningScript.skipHousingServiceQuestion();
  },
  housingServiceQuestion() {
    return OpeningScript.housingServiceQuestion();
  },
  hotlineInfo() {
    return OpeningScript.hotlineInfo();
  },
  releaseOfInformation() {
    return OpeningScript.releaseOfInformation();
  },
  showDvHsStep() {
    return Template.instance().activeStep.get() === 0;
  },
  showRoiStep() {
    return Template.instance().activeStep.get() === 1;
  },
});

Template.preliminarySurvey.events(
  {
    'click .close-cancel': (event) => {
      $('body').removeClass('modal-open');
      event.preventDefault();
      history.back();
    },
    'click .next-step': (event) => {
      event.preventDefault();
      const currentStep = Template.instance().activeStep.get();

      const signaturePad = Router.current().params.signaturePad;
      if (currentStep === ROI_STEP) {
        if (signaturePad.isEmpty()) {
          Alert.error('Please provide signature first');
          return;
        }
        if (!$('#roiCheckbox')[0].checked) {
          Alert.error('You must agree');
          return;
        }
      }

      Template.instance().activeStep.set(nextStep(currentStep));
    },
  }
);

Template.preliminarySurvey.onCreated(function onCreated() {
  this.activeStep = new ReactiveVar(nextStep());

  this.autorun(() => {
    if (this.activeStep.get() === ENDED_STEP) {
      $('#preliminarySurveyModal').modal('hide');

      const signaturePad = Router.current().params.signaturePad;
      if (signaturePad) {
        $('#create-client-form .signature').val(signaturePad.toDataURL());
        $('#create-client-form .signature-img').attr('src', signaturePad.toDataURL());
      }
    }
  });
});
<|endoftext|>


<commit_before>module.exports = function (config) {
  'use strict';
  var extendConfiguration = require('./karma-extend.js');
  config.set(extendConfiguration({
    browsers: []
  }));
};
<commit_msg>Using PhantomJS to test while watching for changes<commit_after>module.exports = function (config) {
  'use strict';
  var extendConfiguration = require('./karma-extend.js');
  config.set(extendConfiguration({
    browsers: ['PhantomJS']
  }));
};
<|endoftext|>


<commit_before><commit_msg>Better copy.<commit_after><|endoftext|>


<commit_before>
var wfStore = Ext.create('Ext.data.ArrayStore', {
    fields: [
       {name: 'name'},
       {name: 'status'},
       {name: 'date', type: 'date', dateFormat: 'Y-m-d'},
       {name: 'date2'}
    ],
    sortOnLoad: true,
    sorters: { property: 'date2', direction : 'DESC' },
    //data: wfList
    proxy: {
	         type: 'ajax',
	          url: getWorkflowListURL,
	          reader: {
		             root: 'list'
		          }
	},
	autoLoad: true
});

wfStore.load(function() {
		console.log(arguments);
});

var wfGrid = Ext.create('Ext.grid.Panel', {
    store: wfStore,
    id: 'wfGrid',
    columns: [
        {
            text     : 'Name',
            flex     : 1,
            sortable : true,
            dataIndex: 'name'
        },
        {
            text     : 'Status',
            width    : 75,
            sortable : true,
            renderer : statusRenderer,
            dataIndex: 'status'
        },
        {
            text     : 'Date',
            width    : 90,
            sortable : true,
            renderer : Ext.util.Format.dateRenderer('d - m - Y'),
            dataIndex: 'date'
        },
        {
            xtype: 'actioncolumn',
            width: 50,
            items: [
            {
                icon   : localResourcesPath+'/img/download-icon.png',
                tooltip: 'Download results',
                handler: function(grid, rowIndex, colIndex) {
                    var rec = wfStore.getAt(rowIndex);
                    alert("Download results " + rec.get('name'));
                }
            },
            {
                icon   : localResourcesPath+'/img/delete-icon.png',
                tooltip: 'Delete instance',
                handler: function(grid, rowIndex, colIndex) {
                    var rec = wfStore.getAt(rowIndex);
                    Ext.Msg.confirm('Alert!', 'Are you sure that you want to delete the workflow '+rec.get('name')+"?",
      	                  function(btn) {
      	                  	if(btn === 'yes')
      	                  	{
	      	                  	Ext.Ajax.request({
	      	      	    			url: deleteWorkflowURL,
	      	      	    			params: {
	      	      	    				"workflowId": rec.get('name')
	      	      	    			},
	      	      	    			success: function(response){
	      	      	    				wfStore.load();
	      	      	    			},
	      	      	    			failure: function(response) {
	      	      	    				Ext.Msg.alert("Error", "Delete failed!");
	      	      	                }
	      	                    });
      	                  	}
      	            });
                }
            }
            ]
        }
    ]
});

var refreshMenuControl = [
	{
       html: 'Submited workflows'
	},
	"->",
	{
		tooltip: 'Refresh list',
		handler: function() {
			  wfStore.load();
		},
		style: {
		    background:'none',
		    backgroundImage: 'url('+localResourcesPath+'/img/refresh-icon.png)',
		    backgroundSize: '90% 85%',
		    backgroundRepeat: 'no-repeat',
			height: 32,
			width: 45,
			margin: 1,
			marginRight: '10px'
		},
		height: 35,
		width: 35
	},
	{
		tooltip: 'Go to Document Library
(open in a new win)',
		height: 32,
		width: 32,
		handler: function() {
		    openInNewTab('file-manager');
		},
		style: {
		    background:'none',
		    backgroundImage: 'url('+localResourcesPath+'/img/folder-icon.png)',
		    backgroundSize: '90% 90%',
		    backgroundRepeat: 'no-repeat',
			height: 32,
			width: 32,
			top: 0,
			margin: 1,
			marginRight: '10px'
		},
		height: 32,
		width: 32
	}
	];

//TODO: the scroll in the list does not work
Ext.define('CF.view.Control', {
	  extend:'Ext.form.Panel',
		style:{
			cursor: 'default'
		},
	  dockedItems:
		  [{
		    xtype: 'toolbar',
		    dock: 'top',
			height: 35,
		    items: refreshMenuControl
		}],
	  items:
		    [
				{
			       xtype: 'panel',
			       items: [wfGrid]
				}
			]
	});

function statusRenderer(val) {
    if (val === 'INIT') {
        return '' + val + '';
    }
    else if (val === 'ERROR') {
        return '' + val + '';
    }
    return val;
}

function openInNewTab(url)
{
  var win=window.open(url, '_blank');
  win.focus();
}

<commit_msg>minor<commit_after>
var wfStore = Ext.create('Ext.data.ArrayStore', {
    fields: [
       {name: 'name'},
       {name: 'status'},
       {name: 'date', type: 'date', dateFormat: 'Y-m-d'},
       {name: 'date2'}
    ],
    sortOnLoad: true,
    sorters: { property: 'date2', direction : 'DESC' },
    //data: wfList
    proxy: {
	         type: 'ajax',
	          url: getWorkflowListURL,
	          reader: {
		             root: 'list'
		          }
	},
	autoLoad: true
});

wfStore.load(function() {
		console.log(arguments);
});

var wfGrid = Ext.create('Ext.grid.Panel', {
    store: wfStore,
    id: 'wfGrid',
    columns: [
        {
            text     : 'Name',
            flex     : 1,
            sortable : true,
            dataIndex: 'name'
        },
        {
            text     : 'Status',
            width    : 75,
            sortable : true,
            renderer : statusRenderer,
            dataIndex: 'status'
        },
        {
            text     : 'Date',
            width    : 90,
            sortable : true,
            renderer : Ext.util.Format.dateRenderer('d - m - Y'),
            dataIndex: 'date'
        },
        {
            xtype: 'actioncolumn',
            width: 50,
            items: [
            {
                icon   : localResourcesPath+'/img/download-icon.png',
                tooltip: 'Download results',
                handler: function(grid, rowIndex, colIndex) {
                    var rec = wfStore.getAt(rowIndex);
                    alert("Download results " + rec.get('name'));
                }
            },
            {
                icon   : localResourcesPath+'/img/delete-icon.png',
                tooltip: 'Delete instance',
                handler: function(grid, rowIndex, colIndex) {
                    var rec = wfStore.getAt(rowIndex);
                    Ext.Msg.confirm('Warning', 'Are you sure that you want to delete '+rec.get('name')+"?",
      	                  function(btn) {
      	                  	if(btn === 'yes')
      	                  	{
	      	                  	Ext.Ajax.request({
	      	      	    			url: deleteWorkflowURL,
	      	      	    			params: {
	      	      	    				"workflowId": rec.get('name')
	      	      	    			},
	      	      	    			success: function(response){
	      	      	    				wfStore.load();
	      	      	    			},
	      	      	    			failure: function(response) {
	      	      	    				Ext.Msg.alert("Error", "Delete failed!");
	      	      	                }
	      	                    });
      	                  	}
      	            });
                }
            }
            ]
        }
    ]
});

var refreshMenuControl = [
	{
       html: 'Submited workflows'
	},
	"->",
	{
		tooltip: 'Refresh list',
		handler: function() {
			  wfStore.load();
		},
		style: {
		    background:'none',
		    backgroundImage: 'url('+localResourcesPath+'/img/refresh-icon.png)',
		    backgroundSize: '90% 85%',
		    backgroundRepeat: 'no-repeat',
			height: 32,
			width: 45,
			margin: 1,
			marginRight: '10px'
		},
		height: 35,
		width: 35
	},
	{
		tooltip: 'Go to Document Library
(open in a new win)',
		height: 32,
		width: 32,
		handler: function() {
		    openInNewTab('file-manager');
		},
		style: {
		    background:'none',
		    backgroundImage: 'url('+localResourcesPath+'/img/folder-icon.png)',
		    backgroundSize: '90% 90%',
		    backgroundRepeat: 'no-repeat',
			height: 32,
			width: 32,
			top: 0,
			margin: 1,
			marginRight: '10px'
		},
		height: 32,
		width: 32
	}
	];

//TODO: the scroll in the list does not work
Ext.define('CF.view.Control', {
	  extend:'Ext.form.Panel',
		style:{
			cursor: 'default'
		},
	  dockedItems:
		  [{
		    xtype: 'toolbar',
		    dock: 'top',
			height: 35,
		    items: refreshMenuControl
		}],
	  items:
		    [
				{
			       xtype: 'panel',
			       items: [wfGrid]
				}
			]
	});

function statusRenderer(val) {
    if (val === 'INIT') {
        return '' + val + '';
    }
    else if (val === 'ERROR') {
        return '' + val + '';
    }
    return val;
}

function openInNewTab(url)
{
  var win=window.open(url, '_blank');
  win.focus();
}

<|endoftext|>


<commit_before>'use strict';

var slack = require('./slack.js');
var clc = require('cli-color');
var moment = require('moment-timezone');
const logger = require('simple-console-logger');
logger.configure({level: process.env.LOGLEVEL || 'info'});

// Entry point for DAG node
module.exports = function(got) {
  const inData = got['in'];
  const getData = got['get'];
  var results = [];
  var botToken;
  let settings = null;
  let reports = [];
  let outgoingMessage = null;
  var initialMsg = "Hello, I\'m <@scrumbot>, please send me stand-up reports on my private channel when I ask for them. \n You can also ask me for `status` and `help`.";
  // Extract the Slack API token
  logger.debug("InData ", inData);
  logger.debug("GET ", got['get'])

  inData.data.forEach(function(d) {
    logger.debug('IN ITEM', d);
    reports.push({
      name: "reports",
      key: d.key,
      value: d.value.toString()
    });
  });

  getData.forEach(function(d) {
    //Get settings and slack token.
    logger.debug('LK ITEM', d.data[0]);
    if (d.data.key == 'settings' && d.data[0].value) {
      settings = JSON.parse(d.data[0].value);
    }
    if(settings == null) {
      settings = {
        tz: "US/Eastern",
        startOfDay: "9",
        meetingCall: "11"
      };
    }

    if (d.data[0] && d.data[0].key == 'slack/bot_access_token' && d.data[0].value) {
      botToken = d.data[0].value.toString();
      logger.debug("BT ", botToken)
    }
  });

  var now = moment.tz(settings.tz);
  logger.debug("LOCAL TIME ", now.format('MMMM Do YYYY, h:mm:ss a zz'));
  //Is it the weekend?
  if (now.day() > 0 && now.day() < 6) {
    logger.debug("Its a workday")
    //Is it start of Day?
    if (now.hour() == parseInt(settings.startOfDay)) {
      // Do we have anyone on the team?
      if (reports.length > 0) {
        logger.debug("Resetting Reports");
        //Reset reports
        // Iterate over all report records and reset them.
        for (var d of reports) {
          logger.debug('RESETTING: ', d);
          results.push({
            name: "reports",
            key: d.key,
            value: "No report yet"
          });
        }
        // Reset current summary
        results.push({
          "name": "currentSummary",
          "key": "current",
          "value": null
        });
      } else {
        //No one joined team yet, send out hello message
        logger.debug("No one on team");
        let timezoneMessage = `\nYour current timezone is ${now.format('zz')}, your workday starts at ${settings.startOfDay} o'clock and I'll send out a meeting call at ${settings.meetingCall} o'clock.`;
        let settingsMsg = "\nYour administrator can change these settings on your <https://dashboard.redsift.cloud/dashboard|Red Sift dashboard>.";
        outgoingMessage = initialMsg + timezoneMessage + settingsMsg;
      }
    }
    if (now.hour() == parseInt(settings.meetingCall)) {
      logger.debug("SEND OUT MEETING CALL");
      outgoingMessage = 'Hello, time for the standup, what are you working on today?';
    }
  } else {
    logger.debug("YOU CAN SLEEP IN")
  }

  // Send out message(s)
  // var wakeup = 'Hello, time for the standup, what are you working on today?';
  //
  if (outgoingMessage) {
    try {
      results.push(slack.postMessage("#general", outgoingMessage, null, botToken).then(() => {
        return null;
      }));
    } catch (ex) {
      logger.error('meetingcall: Exception: ', ex);
    }
    finally {
      return results;
    }
  } else {
    return results;
  }

};
<commit_msg>fixed settings key check<commit_after>'use strict';

var slack = require('./slack.js');
var clc = require('cli-color');
var moment = require('moment-timezone');
const logger = require('simple-console-logger');
logger.configure({level: process.env.LOGLEVEL || 'info'});

// Entry point for DAG node
module.exports = function(got) {
  const inData = got['in'];
  const getData = got['get'];
  var results = [];
  var botToken;
  let settings = null;
  let reports = [];
  let outgoingMessage = null;
  var initialMsg = "Hello, I\'m <@scrumbot>, please send me stand-up reports on my private channel when I ask for them. \n You can also ask me for `status` and `help`.";
  // Extract the Slack API token
  logger.debug("InData ", inData);
  logger.debug("GET ", got['get'])

  inData.data.forEach(function(d) {
    logger.debug('IN ITEM', d);
    reports.push({
      name: "reports",
      key: d.key,
      value: d.value.toString()
    });
  });

  getData.forEach(function(d) {
    //Get settings and slack token.
    logger.debug('LK ITEM', d.data[0]);
    if (d.data[0].key == 'settings' && d.data[0].value) {
      settings = JSON.parse(d.data[0].value);
    }
    if(settings == null) {
      settings = {
        tz: "US/Eastern",
        startOfDay: "9",
        meetingCall: "11"
      };
    }

    if (d.data[0] && d.data[0].key == 'slack/bot_access_token' && d.data[0].value) {
      botToken = d.data[0].value.toString();
      logger.debug("BT ", botToken)
    }
  });

  var now = moment.tz(settings.tz);
  logger.debug("LOCAL TIME ", now.format('MMMM Do YYYY, h:mm:ss a zz'));
  //Is it the weekend?
  if (now.day() > 0 && now.day() < 6) {
    logger.debug("Its a workday")
    //Is it start of Day?
    if (now.hour() == parseInt(settings.startOfDay)) {
      // Do we have anyone on the team?
      if (reports.length > 0) {
        logger.debug("Resetting Reports");
        //Reset reports
        // Iterate over all report records and reset them.
        for (var d of reports) {
          logger.debug('RESETTING: ', d);
          results.push({
            name: "reports",
            key: d.key,
            value: "No report yet"
          });
        }
        // Reset current summary
        results.push({
          "name": "currentSummary",
          "key": "current",
          "value": null
        });
      } else {
        //No one joined team yet, send out hello message
        logger.debug("No one on team");
        let timezoneMessage = `\nYour current timezone is ${now.format('zz')}, your workday starts at ${settings.startOfDay} o'clock and I'll send out a meeting call at ${settings.meetingCall} o'clock.`;
        let settingsMsg = "\nYour administrator can change these settings on your <https://dashboard.redsift.cloud/dashboard|Red Sift dashboard>.";
        outgoingMessage = initialMsg + timezoneMessage + settingsMsg;
      }
    }
    if (now.hour() == parseInt(settings.meetingCall)) {
      logger.debug("SEND OUT MEETING CALL");
      outgoingMessage = 'Hello, time for the standup, what are you working on today?';
    }
  } else {
    logger.debug("YOU CAN SLEEP IN")
  }

  // Send out message(s)
  // var wakeup = 'Hello, time for the standup, what are you working on today?';
  //
  if (outgoingMessage) {
    try {
      results.push(slack.postMessage("#general", outgoingMessage, null, botToken).then(() => {
        return null;
      }));
    } catch (ex) {
      logger.error('meetingcall: Exception: ', ex);
    }
    finally {
      return results;
    }
  } else {
    return results;
  }

};
<|endoftext|>


<commit_before>const path = require('path');
const project = require('./aurelia_project/aurelia.json');
const _ = require('lodash');

const karmaConfig = project.unitTestRunner;

let testSrc = [
    { pattern: karmaConfig.source, included: false },
    'test/aurelia-karma.js'
];

let output = project.platform.output;
let appSrc = project.build.bundles.map(x => path.join(output, x.name));
let entryIndex = appSrc.indexOf(path.join(output, project.build.loader.configTarget));
let entryBundle = appSrc.splice(entryIndex, 1)[0];
let sourceMaps = [{pattern:'scripts/**/*.js.map', included: false}];
let files = [entryBundle].concat('scripts/dep-bundle.js').concat(testSrc).concat(appSrc).concat(sourceMaps);
let transpilerOptions = project.transpiler.options;
transpilerOptions.sourceMap = 'inline';

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: [project.testFramework.id],
        browserNoActivityTimeout: 60000,
        files: files,
        exclude: ['**/*.scss'],
        remapIstanbulReporter:    {
            reports: {
                'text-summary': null,
                json: 'test/coverage/coverage.json',
                lcovonly: 'test/coverage/lcov.info',
                //html: 'test/coverage/mapped'
            }
        },
        junitReporter: {
            outputDir: 'test/junit',
            useBrowserName: false
        },
        preprocessors: {
            [karmaConfig.source]: [project.transpiler.id],
            [appSrc]: ['sourcemap'],
            'scripts/app*.js': ['coverage']
        },
        coverageReporter:    {
            type: 'html',
            dir:  'test/coverage/bundled'
        },
        'babelPreprocessor': { options: transpilerOptions },
        reporters: ['progress', 'coverage',  'junit'/*'karma-remap-istanbul'*/],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: [
            //'Chrome',
           // 'ChromeHeadless',
            'FirefoxHeadless'
        ],
        customLaunchers: {
            'ChromeHeadless': {
                base: 'Chrome',
                flags: [
                    '--no-sandbox',
                    '--headless',
                    '--disable-gpu',
                    '--remote-debugging-port=9222'
                ]
            },
            'FirefoxHeadless': {
                base: 'Firefox',
                flags: [
                    '-headless'
                ]
            }
        },
        /** **************************************************************************** */

        /*
         * Continuous Integration mode
         * if true, Karma captures browsers, runs the tests and exits
         */
        singleRun: true,
        // client.args must be a array of string.
        // Leave 'aurelia-root', project.paths.root in this order so we can find
        // the root of the aurelia project.
        client: {
            args: ['aurelia-root', project.paths.root]
        }
    });
};
<commit_msg>Update karma.conf.js<commit_after>const path = require('path');
const project = require('./aurelia_project/aurelia.json');
const _ = require('lodash');

const karmaConfig = project.unitTestRunner;

let testSrc = [
    { pattern: karmaConfig.source, included: false },
    'test/aurelia-karma.js'
];

let output = project.platform.output;
let appSrc = project.build.bundles.map(x => path.join(output, x.name));
let entryIndex = appSrc.indexOf(path.join(output, project.build.loader.configTarget));
let entryBundle = appSrc.splice(entryIndex, 1)[0];
let sourceMaps = [{pattern:'scripts/**/*.js.map', included: false}];
let files = [entryBundle].concat('scripts/dep-bundle.js')
    .concat({pattern: "node_modules/reflect-metadata/Reflect.js", include: true })
    .concat(testSrc)
    .concat(appSrc)
    .concat(sourceMaps);
let transpilerOptions = project.transpiler.options;
transpilerOptions.sourceMap = 'inline';

module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: [project.testFramework.id],
        browserNoActivityTimeout: 60000,
        files: files,
        exclude: ['**/*.scss'],
        remapIstanbulReporter:    {
            reports: {
                'text-summary': null,
                json: 'test/coverage/coverage.json',
                lcovonly: 'test/coverage/lcov.info',
                //html: 'test/coverage/mapped'
            }
        },
        junitReporter: {
            outputDir: 'test/junit',
            useBrowserName: false
        },
        preprocessors: {
            [karmaConfig.source]: [project.transpiler.id],
            [appSrc]: ['sourcemap'],
            'scripts/app*.js': ['coverage']
        },
        coverageReporter:    {
            type: 'html',
            dir:  'test/coverage/bundled'
        },
        'babelPreprocessor': { options: transpilerOptions },
        reporters: ['progress', 'coverage',  'junit'/*'karma-remap-istanbul'*/],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: [
            //'Chrome',
            'ChromeHeadless',
            'FirefoxHeadless'
        ],
        customLaunchers: {
            'ChromeHeadless': {
                base: 'Chrome',
                flags: [
                    '--no-sandbox',
                    '--headless',
                    '--disable-gpu',
                    '--remote-debugging-port=9222'
                ]
            },
            'FirefoxHeadless': {
                base: 'Firefox',
                flags: [
                    '-headless'
                ]
            }
        },
        /** **************************************************************************** */

        /*
         * Continuous Integration mode
         * if true, Karma captures browsers, runs the tests and exits
         */
        singleRun: true,
        // client.args must be a array of string.
        // Leave 'aurelia-root', project.paths.root in this order so we can find
        // the root of the aurelia project.
        client: {
            args: ['aurelia-root', project.paths.root]
        }
    });
};
<|endoftext|>