<commit_before>/*
 * build.js: Titanium Mobile CLI build command
 *
 * Copyright (c) 2012-2013, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	fields = require('fields'),
	fs = require('fs'),
	jsanalyze = require('titanium-sdk/lib/jsanalyze'),
	path = require('path'),
	sprintf = require('sprintf'),
	ti = require('titanium-sdk'),
	tiappxml = require('titanium-sdk/lib/tiappxml'),
	wrench = require('wrench'),
	__ = appc.i18n(__dirname).__;

fields.setup({
	formatters: {
		error: function (err) {
			if (err instanceof Error) {
				return ('[ERROR] ' + err.message).red + '\n';
			}
			err = '' + err;
			return '\n' + (/^(\[ERROR\])/i.test(err) ? err : '[ERROR] ' + err.replace(/^Error\:/i, '').trim()).red;
		}
	},
	style: {
		accelerator: 'cyan'
	}
});

exports.cliVersion = '>=3.2.1';
exports.title = __('Build');
exports.desc = __('builds a project');
exports.extendedDesc = 'Builds an existing app or module project.';

exports.config = function (logger, config, cli) {
	fields.setup({ colors: cli.argv.colors });

	return function (finished) {
		cli.createHook('build.config', function (callback) {
			ti.platformOptions(logger, config, cli, 'build', function (platformConf) {
				var conf = {
					flags: {
						'build-only': {
							abbr: 'b',
							desc: __('only perform the build; if true, does not install or run the app')
						},
						force: {
							abbr: 'f',
							desc: __('force a full rebuild')
						},
						legacy: {
							desc: __('build using the old Python-based builder.py; deprecated')
						},
						'skip-js-minify': {
							default: false,
							desc: __('bypasses JavaScript minification; %s builds are never minified; only supported for %s and %s', 'simulator'.cyan, 'Android'.cyan, 'iOS'.cyan)
						}
					},
					options: appc.util.mix({
						platform: {
							abbr: 'p',
							callback: function (platform) {
								cli.argv.$originalPlatform = platform;
								platform = ti.resolvePlatform(platform);

								var p = platformConf[platform];
								p && p.options && Object.keys(p.options).forEach(function (name) {
									if (p.options[name].default && cli.argv[name] === undefined) {
										cli.argv[name] = p.options[name].default;
									}
								});

								return platform;
							},
							desc: __('the target build platform'),
							hint: __('platform'),
							order: 2,
							prompt: {
								label: __('Target platform'),
								error: __('Invalid platform'),
								validator: function (platform) {
									if (!platform) {
										throw new Error(__('Invalid platform'));
									} else if (ti.availablePlatforms.indexOf(platform) == -1) {
										throw new Error(__('Invalid platform: %s', platform));
									}
									return true;
								}
							},
							required: true,
							skipValueCheck: true,
							values: ti.targetPlatforms
						},
						'project-dir': {
							abbr: 'd',
							callback: function (projectDir) {
								if (projectDir === '') {
									// no option value was specified
									// check if current directory is a valid dir
									// if not output meaningful error message
									projectDir = conf.options['project-dir'].default;
									if (!fs.existsSync(path.join(projectDir, 'tiapp.xml'))) {
										return;
									}
								}

								// start file logging here
								console.log(logBanner(cli));
								patchLogger(logger, cli);

								// load the tiapp.xml
								try {
									var tiapp = cli.tiapp = new tiappxml(path.join(projectDir, 'tiapp.xml'));
								} catch (ex) {
									logger.error(ex);
									logger.log();
									process.exit(1);
								}

								tiapp.properties || (tiapp.properties = {});

								// make sure the tiapp.xml is sane
								ti.validateTiappXml(logger, config, tiapp);

								// check that the Titanium SDK version is correct
								if (!ti.validateCorrectSDK(logger, config, cli, 'build')) {
									throw new cli.GracefulShutdown();
								}

								return projectDir;
							},
							desc: __('the directory containing the project'),
							default: process.env.SOURCE_ROOT ? path.join(process.env.SOURCE_ROOT, '..', '..') : '.',
							order: 1,
							prompt: function (callback) {
								callback(fields.file({
									promptLabel: __('Where is the __project directory__?'),
									complete: true,
									showHidden: true,
									ignoreDirs: new RegExp(config.get('cli.ignoreDirs')),
									ignoreFiles: /.*/,
									validate: conf.options['project-dir'].validate
								}));
							},
							required: true,
							validate: function (projectDir, callback) {
								var isDefault = projectDir == conf.options['project-dir'].default;

								var dir = appc.fs.resolvePath(projectDir);

								if (!fs.existsSync(dir)) {
									return callback(new Error(__('Project directory does not exist')));
								}

								var tiappFile = path.join(dir, 'tiapp.xml'),
									root = path.resolve('/');

								// try to find the tiapp.xml
								while (!fs.existsSync(tiappFile)) {
									dir = path.dirname(dir);
									if (dir == root) {
										if (!isDefault) {
											callback(new Error(__('Invalid project directory "%s" because tiapp.xml not found', projectDir)));
											return;
										} else {
											callback(true);
											return;
										}
									}
									tiappFile = path.join(dir, 'tiapp.xml');
								}

								callback(null, dir);
							}
						}
					}, ti.commonOptions(logger, config)),
					platforms: platformConf
				};
				callback(null, conf);
			});
		})(function (err, result) {
			finished(result);
		});
	};
};

exports.validate = function (logger, config, cli) {
	// TODO: set the type to 'app' for now, but we'll need to determine if the project is an app or a module
	cli.argv.type = 'app';

	ti.validatePlatform(logger, cli, 'platform');

	// since we need validate() to be async, we return a function in which the cli
	// will immediately call
	return function (finished) {
		function next(result) {
			if (result !== false) {
				// no error, load the tiapp.xml plugins
				ti.loadPlugins(logger, config, cli, cli.argv['project-dir'], function () {
					finished(result);
				});
			} else {
				finished(result);
			}
		}

		// loads the platform specific bulid command and runs its validate() function
		var result = ti.validatePlatformOptions(logger, config, cli, 'build');
		if (result && typeof result == 'function') {
			result(next);
		} else {
			next(result);
		}
	};
};

exports.run = function (logger, config, cli, finished) {
	var platform = ti.resolvePlatform(cli.argv.platform),
		buildModule = path.join(__dirname, '..', '..', platform, 'cli', 'commands', '_build.js'),
		counter = 0;

	if (!fs.existsSync(buildModule)) {
		logger.error(__('Unable to find platform specific build command') + '\n');
		logger.log(__("Your SDK installation may be corrupt. You can reinstall it by running '%s'.", (cli.argv.$ + ' sdk update --force --default').cyan) + '\n');
		process.exit(1);
	}

	if (config.get('cli.sendAPIUsage', true)) {
		cli.on('build.finalize', function (builder) {
			var deployType = builder.deployType || cli.argv['deploy-type'] || null;
			if (deployType == 'production') {
				cli.addAnalyticsEvent('Titanium API Usage', {
					platform: platform,
					tisdkname: (ti.manifest && ti.manifest.name) || (cli.sdk && cli.sdk.name) || null,
					tisdkver: (ti.manifest && ti.manifest.version) || (cli.sdk && cli.sdk.name) || null,
					deployType: deployType,
					target: builder.target || cli.argv.target || null,
					usage: jsanalyze.getAPIUsage()
				}, 'ti.apiusage');
			}
		});
	}

	require(buildModule).run(logger, config, cli, function (err) {
		if (!counter++) {
			var delta = appc.time.prettyDiff(cli.startTime, Date.now());
			if (err) {
				logger.error(__('Project failed to build after %s', delta));
				(err.message || err.toString()).trim().split('\n').forEach(function (msg) {
					logger.error(msg);
				});
				logger.log();
				process.exit(1);
			} else {
				logger.info(__('Project built successfully in %s', delta.cyan) + '\n');
			}

			finished();
		}
	});
};

/**
 * Monkey-patch the logger object to enable file logging during build
 * @param {Object} logger - The logger instance
 * @param {Object} cli - The CLI instance
 */
function patchLogger(logger, cli) {
	var origLoggerLog = logger.log,
		platform = ti.resolvePlatform(cli.argv.platform),
		buildDir = path.join(cli.argv['project-dir'], 'build'),
		logFileStream;

	fs.existsSync(buildDir) || wrench.mkdirSyncRecursive(buildDir);

	// create our write stream
	logFileStream = fs.createWriteStream(path.join(buildDir, 'build_' + platform + '.log'), { 'flags': 'w', 'encoding': 'ascii' });

	// write the banner to start out the log
	logFileStream.write(logBanner(cli));

	// override the existing log function
	logger.log = function() {
		// most of this copied from the CLI's logger.js logger.log() function
		var args = Array.prototype.slice.call(arguments),
			padLevels = logger.padLevels,
			prefix;

		// if there are no args (i.e. a blank line), we need at least one space
		args.length || args.unshift(' ');

		// if we're not being called from info/warn/error/debug, then set this as a general log entry
		args[0] in logger.levels || args.unshift('_');

		// turn off padding
		logger.padLevels = args[0] != '_';

		// get rid of any null args
		while (args.length && args[args.length-1] == null) args.pop();

		// if we're logging an error, we need to cast to a string so that sprintf doesn't complain
		if (args[1] instanceof Error || Object.prototype.toString.call(args[1]) == '[object Error]') {
			args[1] = (args[1].stack || args[1].toString()) + '\n';
		} else if (args[1] == null || args[1] == undefined) {
			args[1] = '';
		}

		typeof type != 'string' && (args[1] = ''+args[1]);

		// strip off starting full colons
		args[1] = args[1].replace(/:\s{1}/, ' ');

		// add [INFO] type prefixes for each line
		prefix = (args[0] != "_") ? "[" + args[0].toUpperCase() + "]" + ((args[0].length===5) ? '  ' : '   ') : "";

		// log it to our log file, stripping out the color codes
		logFileStream.write("\n" + prefix + args[1].replace(/\x1B\[\d+m/g, ''));

		// call the original logger with our cleaned up args
		origLoggerLog.apply(logger, [args[0], args.length > 2 ? sprintf.apply(null, args.slice(1)) : args[1]]);

		// restore padding
		logger.padLevels = padLevels;
	}
}

/**
* Outputs environment details at the top of the log file
* for each run of `titanium build`
* @param {Object} cli - The CLI instance
*
* See http://en.wikipedia.org/wiki/Darwin_%28operating_system%29#Release_history for
* os.release() to version mapping for OS X. (e.g. 14.0.0 is v10.10 Yosemite)
*/
function logBanner(cli) {
	var os = require('os');
	return new Date().toLocaleString() + '\n\n' +
		'Build Environment \n' +
		'   Host OS         = ' + (os.platform()==='darwin' ? "OS X" : os.platform()) + ' ' + os.release() + ', ' + os.arch() + '\n'  +
		'   Target platform = ' + ti.resolvePlatform(cli.argv.platform) + '\n'  +
		'   CLI version     = ' + cli.version + '\n'  +
		'   SDK version     = ' + cli.argv.sdk + '\n' +
		'   SDK path        = ' + cli.sdk.path + '\n' +
		'   Node version    = ' + process.version + '\n' +
		'   Command         = ' + cli.argv.$ + ' ' + cli.argv.$_.join(' ') + '\n' +
		'\n';
}<commit_msg>change to logger.log(), move to avoid tripling output<commit_after>/*
 * build.js: Titanium Mobile CLI build command
 *
 * Copyright (c) 2012-2013, Appcelerator, Inc.  All Rights Reserved.
 * See the LICENSE file for more information.
 */

var appc = require('node-appc'),
	fields = require('fields'),
	fs = require('fs'),
	jsanalyze = require('titanium-sdk/lib/jsanalyze'),
	path = require('path'),
	sprintf = require('sprintf'),
	ti = require('titanium-sdk'),
	tiappxml = require('titanium-sdk/lib/tiappxml'),
	wrench = require('wrench'),
	__ = appc.i18n(__dirname).__;

fields.setup({
	formatters: {
		error: function (err) {
			if (err instanceof Error) {
				return ('[ERROR] ' + err.message).red + '\n';
			}
			err = '' + err;
			return '\n' + (/^(\[ERROR\])/i.test(err) ? err : '[ERROR] ' + err.replace(/^Error\:/i, '').trim()).red;
		}
	},
	style: {
		accelerator: 'cyan'
	}
});

exports.cliVersion = '>=3.2.1';
exports.title = __('Build');
exports.desc = __('builds a project');
exports.extendedDesc = 'Builds an existing app or module project.';

exports.config = function (logger, config, cli) {
	fields.setup({ colors: cli.argv.colors });

	return function (finished) {
		cli.createHook('build.config', function (callback) {
			ti.platformOptions(logger, config, cli, 'build', function (platformConf) {
				var conf = {
					flags: {
						'build-only': {
							abbr: 'b',
							desc: __('only perform the build; if true, does not install or run the app')
						},
						force: {
							abbr: 'f',
							desc: __('force a full rebuild')
						},
						legacy: {
							desc: __('build using the old Python-based builder.py; deprecated')
						},
						'skip-js-minify': {
							default: false,
							desc: __('bypasses JavaScript minification; %s builds are never minified; only supported for %s and %s', 'simulator'.cyan, 'Android'.cyan, 'iOS'.cyan)
						}
					},
					options: appc.util.mix({
						platform: {
							abbr: 'p',
							callback: function (platform) {
								cli.argv.$originalPlatform = platform;
								platform = ti.resolvePlatform(platform);

								var p = platformConf[platform];
								p && p.options && Object.keys(p.options).forEach(function (name) {
									if (p.options[name].default && cli.argv[name] === undefined) {
										cli.argv[name] = p.options[name].default;
									}
								});

								return platform;
							},
							desc: __('the target build platform'),
							hint: __('platform'),
							order: 2,
							prompt: {
								label: __('Target platform'),
								error: __('Invalid platform'),
								validator: function (platform) {
									if (!platform) {
										throw new Error(__('Invalid platform'));
									} else if (ti.availablePlatforms.indexOf(platform) == -1) {
										throw new Error(__('Invalid platform: %s', platform));
									}
									return true;
								}
							},
							required: true,
							skipValueCheck: true,
							values: ti.targetPlatforms
						},
						'project-dir': {
							abbr: 'd',
							callback: function (projectDir) {
								if (projectDir === '') {
									// no option value was specified
									// check if current directory is a valid dir
									// if not output meaningful error message
									projectDir = conf.options['project-dir'].default;
									if (!fs.existsSync(path.join(projectDir, 'tiapp.xml'))) {
										return;
									}
								}

								// start file logging here
								patchLogger(logger, cli);

								// load the tiapp.xml
								try {
									var tiapp = cli.tiapp = new tiappxml(path.join(projectDir, 'tiapp.xml'));
								} catch (ex) {
									logger.error(ex);
									logger.log();
									process.exit(1);
								}

								tiapp.properties || (tiapp.properties = {});

								// make sure the tiapp.xml is sane
								ti.validateTiappXml(logger, config, tiapp);

								// check that the Titanium SDK version is correct
								if (!ti.validateCorrectSDK(logger, config, cli, 'build')) {
									throw new cli.GracefulShutdown();
								}

								return projectDir;
							},
							desc: __('the directory containing the project'),
							default: process.env.SOURCE_ROOT ? path.join(process.env.SOURCE_ROOT, '..', '..') : '.',
							order: 1,
							prompt: function (callback) {
								callback(fields.file({
									promptLabel: __('Where is the __project directory__?'),
									complete: true,
									showHidden: true,
									ignoreDirs: new RegExp(config.get('cli.ignoreDirs')),
									ignoreFiles: /.*/,
									validate: conf.options['project-dir'].validate
								}));
							},
							required: true,
							validate: function (projectDir, callback) {
								var isDefault = projectDir == conf.options['project-dir'].default;

								var dir = appc.fs.resolvePath(projectDir);

								if (!fs.existsSync(dir)) {
									return callback(new Error(__('Project directory does not exist')));
								}

								var tiappFile = path.join(dir, 'tiapp.xml'),
									root = path.resolve('/');

								// try to find the tiapp.xml
								while (!fs.existsSync(tiappFile)) {
									dir = path.dirname(dir);
									if (dir == root) {
										if (!isDefault) {
											callback(new Error(__('Invalid project directory "%s" because tiapp.xml not found', projectDir)));
											return;
										} else {
											callback(true);
											return;
										}
									}
									tiappFile = path.join(dir, 'tiapp.xml');
								}

								callback(null, dir);
							}
						}
					}, ti.commonOptions(logger, config)),
					platforms: platformConf
				};
				logger.log(logBanner(cli));
				callback(null, conf);
			});
		})(function (err, result) {
			finished(result);
		});
	};
};

exports.validate = function (logger, config, cli) {
	// TODO: set the type to 'app' for now, but we'll need to determine if the project is an app or a module
	cli.argv.type = 'app';

	ti.validatePlatform(logger, cli, 'platform');

	// since we need validate() to be async, we return a function in which the cli
	// will immediately call
	return function (finished) {
		function next(result) {
			if (result !== false) {
				// no error, load the tiapp.xml plugins
				ti.loadPlugins(logger, config, cli, cli.argv['project-dir'], function () {
					finished(result);
				});
			} else {
				finished(result);
			}
		}

		// loads the platform specific bulid command and runs its validate() function
		var result = ti.validatePlatformOptions(logger, config, cli, 'build');
		if (result && typeof result == 'function') {
			result(next);
		} else {
			next(result);
		}
	};
};

exports.run = function (logger, config, cli, finished) {
	var platform = ti.resolvePlatform(cli.argv.platform),
		buildModule = path.join(__dirname, '..', '..', platform, 'cli', 'commands', '_build.js'),
		counter = 0;

	if (!fs.existsSync(buildModule)) {
		logger.error(__('Unable to find platform specific build command') + '\n');
		logger.log(__("Your SDK installation may be corrupt. You can reinstall it by running '%s'.", (cli.argv.$ + ' sdk update --force --default').cyan) + '\n');
		process.exit(1);
	}

	if (config.get('cli.sendAPIUsage', true)) {
		cli.on('build.finalize', function (builder) {
			var deployType = builder.deployType || cli.argv['deploy-type'] || null;
			if (deployType == 'production') {
				cli.addAnalyticsEvent('Titanium API Usage', {
					platform: platform,
					tisdkname: (ti.manifest && ti.manifest.name) || (cli.sdk && cli.sdk.name) || null,
					tisdkver: (ti.manifest && ti.manifest.version) || (cli.sdk && cli.sdk.name) || null,
					deployType: deployType,
					target: builder.target || cli.argv.target || null,
					usage: jsanalyze.getAPIUsage()
				}, 'ti.apiusage');
			}
		});
	}

	require(buildModule).run(logger, config, cli, function (err) {
		if (!counter++) {
			var delta = appc.time.prettyDiff(cli.startTime, Date.now());
			if (err) {
				logger.error(__('Project failed to build after %s', delta));
				(err.message || err.toString()).trim().split('\n').forEach(function (msg) {
					logger.error(msg);
				});
				logger.log();
				process.exit(1);
			} else {
				logger.info(__('Project built successfully in %s', delta.cyan) + '\n');
			}

			finished();
		}
	});
};

/**
 * Monkey-patch the logger object to enable file logging during build
 * @param {Object} logger - The logger instance
 * @param {Object} cli - The CLI instance
 */
function patchLogger(logger, cli) {
	var origLoggerLog = logger.log,
		platform = ti.resolvePlatform(cli.argv.platform),
		buildDir = path.join(cli.argv['project-dir'], 'build'),
		logFileStream;

	fs.existsSync(buildDir) || wrench.mkdirSyncRecursive(buildDir);

	// create our write stream
	logFileStream = fs.createWriteStream(path.join(buildDir, 'build_' + platform + '.log'), { 'flags': 'w', 'encoding': 'ascii' });

	// write the banner to start out the log
	logFileStream.write(logBanner(cli));

	// override the existing log function
	logger.log = function() {
		// most of this copied from the CLI's logger.js logger.log() function
		var args = Array.prototype.slice.call(arguments),
			padLevels = logger.padLevels,
			prefix;

		// if there are no args (i.e. a blank line), we need at least one space
		args.length || args.unshift(' ');

		// if we're not being called from info/warn/error/debug, then set this as a general log entry
		args[0] in logger.levels || args.unshift('_');

		// turn off padding
		logger.padLevels = args[0] != '_';

		// get rid of any null args
		while (args.length && args[args.length-1] == null) args.pop();

		// if we're logging an error, we need to cast to a string so that sprintf doesn't complain
		if (args[1] instanceof Error || Object.prototype.toString.call(args[1]) == '[object Error]') {
			args[1] = (args[1].stack || args[1].toString()) + '\n';
		} else if (args[1] == null || args[1] == undefined) {
			args[1] = '';
		}

		typeof type != 'string' && (args[1] = ''+args[1]);

		// strip off starting full colons
		args[1] = args[1].replace(/:\s{1}/, ' ');

		// add [INFO] type prefixes for each line
		prefix = (args[0] != "_") ? "[" + args[0].toUpperCase() + "]" + ((args[0].length===5) ? '  ' : '   ') : "";

		// log it to our log file, stripping out the color codes
		logFileStream.write("\n" + prefix + args[1].replace(/\x1B\[\d+m/g, ''));

		// call the original logger with our cleaned up args
		origLoggerLog.apply(logger, [args[0], args.length > 2 ? sprintf.apply(null, args.slice(1)) : args[1]]);

		// restore padding
		logger.padLevels = padLevels;
	}
}

/**
* Outputs environment details at the top of the log file
* for each run of `titanium build`
* @param {Object} cli - The CLI instance
*
* See http://en.wikipedia.org/wiki/Darwin_%28operating_system%29#Release_history for
* os.release() to version mapping for OS X. (e.g. 14.0.0 is v10.10 Yosemite)
*/
function logBanner(cli) {
	var os = require('os');
	return new Date().toLocaleString() + '\n\n' +
		'Build Environment \n' +
		'   Host OS         = ' + (os.platform()==='darwin' ? "OS X" : os.platform()) + ' ' + os.release() + ', ' + os.arch() + '\n'  +
		'   Target platform = ' + ti.resolvePlatform(cli.argv.platform) + '\n'  +
		'   CLI version     = ' + cli.version + '\n'  +
		'   SDK version     = ' + cli.argv.sdk + '\n' +
		'   SDK path        = ' + cli.sdk.path + '\n' +
		'   Node version    = ' + process.version + '\n' +
		'   Command         = ' + cli.argv.$ + ' ' + cli.argv.$_.join(' ') + '\n' +
		'\n';
}<|endoftext|>


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

    angular
        .module('partner')
        .controller('HomeController', HomeController);

    function HomeController($scope, $rootScope, $firebaseAuth, userService, $state){
        var vm = this;
        var ref = new Firebase($rootScope.fbUrl);
        vm.authObj = $firebaseAuth(ref);

        if($rootScope.currentUser)
        {
            console.log($rootScope.currentUser);
            $scope.currentUser = $rootScope.currentUser.profile;
            vm.title = $scope.currentUser.title;
        }
        //console.log(currentUser);
    }

})();

$( document ).on( "pagecreate", function() {
    // The window width and height are decreased by 30 to take the tolerance of 15 pixels at each side into account
    function scale( width, height, padding, border ) {
        var scrWidth = $( window ).width() - 30,
            scrHeight = $( window ).height() - 30,
            ifrPadding = 2 * padding,
            ifrBorder = 2 * border,
            ifrWidth = width + ifrPadding + ifrBorder,
            ifrHeight = height + ifrPadding + ifrBorder,
            h, w;
        if ( ifrWidth < scrWidth && ifrHeight < scrHeight ) {
            w = ifrWidth;
            h = ifrHeight;
        } else if ( ( ifrWidth / scrWidth ) > ( ifrHeight / scrHeight ) ) {
            w = scrWidth;
            h = ( scrWidth / ifrWidth ) * ifrHeight;
        } else {
            h = scrHeight;
            w = ( scrHeight / ifrHeight ) * ifrWidth;
        }
        return {
            'width': w - ( ifrPadding + ifrBorder ),
            'height': h - ( ifrPadding + ifrBorder )
        };
    };
    $( ".ui-popup iframe" )
        .attr( "width", 0 )
        .attr( "height", "auto" );
    $( "#popupVideo" ).on({
        popupbeforeposition: function() {
            // call our custom function scale() to get the width and height
            var size = scale( 497, 298, 15, 1 ),
                w = size.width,
                h = size.height;
            $( "#popupVideo iframe" )
                .attr( "width", w )
                .attr( "height", h );
        },
        popupafterclose: function() {
            $( "#popupVideo iframe" )
                .attr( "width", 0 )
                .attr( "height", 0 );
        }
    });
});
<commit_msg>Update homeController.js<commit_after>
(function(){
    'use strict';

    angular
        .module('partner')
        .controller('HomeController', HomeController);

    function HomeController($scope, $rootScope, $firebaseAuth, userService, $state){
        var vm = this;
        var ref = new Firebase($rootScope.fbUrl);
        vm.authObj = $firebaseAuth(ref);

        if($rootScope.currentUser)
        {
            console.log($rootScope.currentUser);
            $scope.currentUser = $rootScope.currentUser.profile;
            vm.title = $scope.currentUser.title;
        }
        //console.log(currentUser);
    }

$( document ).on( "pagecreate", function() {
    // The window width and height are decreased by 30 to take the tolerance of 15 pixels at each side into account
    function scale( width, height, padding, border ) {
        var scrWidth = $( window ).width() - 30,
            scrHeight = $( window ).height() - 30,
            ifrPadding = 2 * padding,
            ifrBorder = 2 * border,
            ifrWidth = width + ifrPadding + ifrBorder,
            ifrHeight = height + ifrPadding + ifrBorder,
            h, w;
        if ( ifrWidth < scrWidth && ifrHeight < scrHeight ) {
            w = ifrWidth;
            h = ifrHeight;
        } else if ( ( ifrWidth / scrWidth ) > ( ifrHeight / scrHeight ) ) {
            w = scrWidth;
            h = ( scrWidth / ifrWidth ) * ifrHeight;
        } else {
            h = scrHeight;
            w = ( scrHeight / ifrHeight ) * ifrWidth;
        }
        return {
            'width': w - ( ifrPadding + ifrBorder ),
            'height': h - ( ifrPadding + ifrBorder )
        };
    };
    $( ".ui-popup iframe" )
        .attr( "width", 0 )
        .attr( "height", "auto" );
    $( "#popupVideo" ).on({
        popupbeforeposition: function() {
            // call our custom function scale() to get the width and height
            var size = scale( 497, 298, 15, 1 ),
                w = size.width,
                h = size.height;
            $( "#popupVideo iframe" )
                .attr( "width", w )
                .attr( "height", h );
        },
        popupafterclose: function() {
            $( "#popupVideo iframe" )
                .attr( "width", 0 )
                .attr( "height", 0 );
        }
    });
});
<|endoftext|>


<commit_before>var logger = require("../../server/logger.js"),
    fs = require("fs"),
    wrench = require("wrench"),
    path = require("path"),
    tishadow_app = path.join(__dirname, "../..","app"),
    config = require("./config"),
    _ = require("underscore");

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

 var required_modules = [
        '<module platform="iphone" version="0.1">yy.tidynamicfont</module>',
        '<module platform="iphone" version="0.3">net.iamyellow.tiws</module>',
        '<module platform="android" version="0.1">net.iamyellow.tiws</module>',
        '<module platform="iphone" version="1.0.2">ti.compression</module>',
        '<module platform="android" version="2.0.3">ti.compression</module>'
 ];

 var required_properties = [
    '<property name="ti.android.bug2373.finishfalseroot" type="bool">false</property>',
    '<property name="ti.android.bug2373.skipAlert" type="bool">true</property>',
    '<property name="cli.includeAllTiModules" type="bool">true</property>'
 ]

exports.copyCoreProject = function(env) {
  var dest = env.destination || ".";
  if (!fs.existsSync(dest) || !fs.lstatSync(dest).isDirectory()) {
    logger.error("Destination folder does not exist.");
    return false;
  }
  if (dest === ".") {
    logger.error("You really don't want to write to the current directory.");
    return false;
  }

  if (env.upgrade) {
    logger.info("Upgrading existing app....");

    if (!fs.existsSync(path.join(dest,'Resources'))) {
      logger.error("Could not find existing tishadow app");
      return false;
    }
    wrench.copyDirSyncRecursive(path.join(tishadow_app, 'Resources'), path.join(dest,'Resources'));
  } else {
    logger.info("Creating new app...");

    wrench.copyDirSyncRecursive(tishadow_app, dest);

    //inject new GUID
    var source_tiapp = fs.readFileSync(path.join(tishadow_app,"tiapp.xml"),'utf8');
    fs.writeFileSync(path.join(dest,"tiapp.xml"),
         source_tiapp
           .replace("{{GUID}}", 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);})) // GUID one-liner: http://stackoverflow.com/a/2117523
           .replace("{{APPID}}", env.appid)
                    );
  }
  return true;
};

exports.build = function(env) {
  var dest = env.destination || ".";
  var dest_resources = path.join(dest,"Resources");
  var dest_fonts = path.join(dest_resources,"fonts");
  var dest_modules = path.join(dest,"modules");
  var dest_platform = path.join(dest,"platform");
  var template_file = path.join(tishadow_app,"Resources","appify.js");

  //set to bundle mode
  env._name = "bundle";
  var compiler = require("./compiler");
  //bundle the source
  compiler(env,function() {

    //copy tishadow src
    if (exports.copyCoreProject(env)) {
      // generate app.js
      var template = fs.readFileSync(template_file,'utf8');
      var new_app_js = _.template(template, {proto: "http" + (config.isTiCaster ? "s" : ""), host:config.host, port: config.port, room: config.room, app_name: config.app_name});
      fs.writeFileSync(path.join(dest_resources,"app.js"),new_app_js);
      //copy fonts
      if(fs.existsSync(config.fonts_path)) {
        wrench.copyDirSyncRecursive(config.fonts_path,dest_fonts);
      }
      //copy splash screen and icons
      ['iphone','android','blackberry','mobileweb','tizen'].forEach(function(platform) {
        if(fs.existsSync(path.join(config.resources_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.resources_path,platform),path.join(dest_resources,platform),{
            filter: new RegExp("(\.png|images|res-.*|fonts|\.otf|\.ttf)$","i"),
            whitelist: true
          });
        }
        if(fs.existsSync(path.join(config.modules_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.modules_path,platform),path.join(dest_modules,platform),{preserve:true});
        }
        if(fs.existsSync(path.join(config.platform_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.platform_path,platform),path.join(dest_platform,platform));
        }
      });
      // copy tiapp.xml and inject modules
      var source_tiapp = fs.readFileSync(path.join(config.base,"tiapp.xml"),'utf8');
      required_modules.push("</modules>")
      var injected_xml = required_modules.concat(required_properties);
      fs.writeFileSync(path.join(dest,"tiapp.xml"),
                       source_tiapp
                       .replace(/<plugin[^>]*>ti\.alloy<\/plugin>/,"")
                       .replace(/<property[^>]+ti\.android\.bug2373\.finishfalseroot[^>]+>true<\/property>/,'')
                       .replace("<modules/>","<modules></modules>")
                       .replace("</modules>",injected_xml.join("\n")));
      // copy the bundle
      fs.writeFileSync(path.join(dest_resources, config.app_name.replace(/ /g,"_") + ".zip"),fs.readFileSync(config.bundle_file));

      logger.info("TiShadow app ready");
    }
  });
}
<commit_msg>Fixes not being able to restart in singleTop mode<commit_after>var logger = require("../../server/logger.js"),
    fs = require("fs"),
    wrench = require("wrench"),
    path = require("path"),
    tishadow_app = path.join(__dirname, "../..","app"),
    config = require("./config"),
    _ = require("underscore");

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

 var required_modules = [
        '<module platform="iphone" version="0.1">yy.tidynamicfont</module>',
        '<module platform="iphone" version="0.3">net.iamyellow.tiws</module>',
        '<module platform="android" version="0.1">net.iamyellow.tiws</module>',
        '<module platform="iphone" version="1.0.2">ti.compression</module>',
        '<module platform="android" version="2.0.3">ti.compression</module>'
 ];

 var required_properties = [
    '<property name="ti.android.bug2373.finishfalseroot" type="bool">false</property>',
    '<property name="ti.android.bug2373.skipAlert" type="bool">true</property>',
    '<property name="cli.includeAllTiModules" type="bool">true</property>'
 ]

exports.copyCoreProject = function(env) {
  var dest = env.destination || ".";
  if (!fs.existsSync(dest) || !fs.lstatSync(dest).isDirectory()) {
    logger.error("Destination folder does not exist.");
    return false;
  }
  if (dest === ".") {
    logger.error("You really don't want to write to the current directory.");
    return false;
  }

  if (env.upgrade) {
    logger.info("Upgrading existing app....");

    if (!fs.existsSync(path.join(dest,'Resources'))) {
      logger.error("Could not find existing tishadow app");
      return false;
    }
    wrench.copyDirSyncRecursive(path.join(tishadow_app, 'Resources'), path.join(dest,'Resources'));
  } else {
    logger.info("Creating new app...");

    wrench.copyDirSyncRecursive(tishadow_app, dest);

    //inject new GUID
    var source_tiapp = fs.readFileSync(path.join(tishadow_app,"tiapp.xml"),'utf8');
    fs.writeFileSync(path.join(dest,"tiapp.xml"),
         source_tiapp
           .replace("{{GUID}}", 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);})) // GUID one-liner: http://stackoverflow.com/a/2117523
           .replace("{{APPID}}", env.appid)
                    );
  }
  return true;
};

exports.build = function(env) {
  var dest = env.destination || ".";
  var dest_resources = path.join(dest,"Resources");
  var dest_fonts = path.join(dest_resources,"fonts");
  var dest_modules = path.join(dest,"modules");
  var dest_platform = path.join(dest,"platform");
  var template_file = path.join(tishadow_app,"Resources","appify.js");

  //set to bundle mode
  env._name = "bundle";
  var compiler = require("./compiler");
  //bundle the source
  compiler(env,function() {

    //copy tishadow src
    if (exports.copyCoreProject(env)) {
      // generate app.js
      var template = fs.readFileSync(template_file,'utf8');
      var new_app_js = _.template(template, {proto: "http" + (config.isTiCaster ? "s" : ""), host:config.host, port: config.port, room: config.room, app_name: config.app_name});
      fs.writeFileSync(path.join(dest_resources,"app.js"),new_app_js);
      //copy fonts
      if(fs.existsSync(config.fonts_path)) {
        wrench.copyDirSyncRecursive(config.fonts_path,dest_fonts);
      }
      //copy splash screen and icons
      ['iphone','android','blackberry','mobileweb','tizen'].forEach(function(platform) {
        if(fs.existsSync(path.join(config.resources_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.resources_path,platform),path.join(dest_resources,platform),{
            filter: new RegExp("(\.png|images|res-.*|fonts|\.otf|\.ttf)$","i"),
            whitelist: true
          });
        }
        if(fs.existsSync(path.join(config.modules_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.modules_path,platform),path.join(dest_modules,platform),{preserve:true});
        }
        if(fs.existsSync(path.join(config.platform_path,platform))) {
          wrench.copyDirSyncRecursive(path.join(config.platform_path,platform),path.join(dest_platform,platform));
        }
      });
      // copy tiapp.xml and inject modules
      var source_tiapp = fs.readFileSync(path.join(config.base,"tiapp.xml"),'utf8');
      required_modules.push("</modules>")
      var injected_xml = required_modules.concat(required_properties);
      fs.writeFileSync(path.join(dest,"tiapp.xml"),
                       source_tiapp
                       .replace(/<plugin[^>]*>ti\.alloy<\/plugin>/,"")
                       .replace(/<property[^>]+ti\.android\.bug2373\.finishfalseroot[^>]+>true<\/property>/,'')
                       .replace('android:launchMode="singleTop"','')
                       .replace("<modules/>","<modules></modules>")
                       .replace("</modules>",injected_xml.join("\n")));
      // copy the bundle
      fs.writeFileSync(path.join(dest_resources, config.app_name.replace(/ /g,"_") + ".zip"),fs.readFileSync(config.bundle_file));

      logger.info("TiShadow app ready");
    }
  });
}
<|endoftext|>


<commit_before>import apis from '../apis'

export function getSuggestions(name) {
  return dispatch => {
    const url = apis.GET_SUGGESTIONS(encodeURIComponent(name))
    fetch(url)
      .then(res => res.json())
      .then(games => {
        dispatch({ type: 'GET_SUGGESTIONS_SUCCESS', suggestions: games })
      })
      .catch(error => {
        dispatch({ type: 'FETCH_ERROR', error, url })
      })
  }
}
<commit_msg>Fix bug when the recommendations list show while loading<commit_after>import apis from '../apis'

export function getSuggestions(name) {
  return (dispatch, getState) => {
    const state = getState()

    if (!state.app.get('loading')) {
      const url = apis.GET_SUGGESTIONS(encodeURIComponent(name))
      fetch(url)
        .then(res => res.json())
        .then(games => {
          dispatch({ type: 'GET_SUGGESTIONS_SUCCESS', suggestions: games })
        })
        .catch(error => {
          dispatch({ type: 'FETCH_ERROR', error, url })
        })
    }
  }
}
<|endoftext|>


<commit_before>$(document).foundation()
<commit_msg>Delete app.js<commit_after><|endoftext|>


<commit_before>/**
 * Grid for the game board. Use this to easily position
 * characters and game components.
 *
 * Examples: this.x = grid.column(5);
 *           this.y = grid.row(5);
 */
var grid = {
    /**
     * {number} pixels
     */
    COLUMN : 101,
    /**
     * {number} pixels
     */
    ROW    : 83,
    /**
     * {number} pixels
     */
    _OFFSET: 25,
};

/**
 * Return the proper pixel number for a given column
 * @param {number} column
 * @return {number} pixels
 */
grid.column = function (column) {
    return column * this.COLUMN;
};

/**
 * Return the proper pixel number for a given row
 * @param {number} row
 * @return {number} pixels
 */
grid.row = function (row) {
    return row * this.ROW - this._OFFSET;
};

// Enemies our player must avoid
var Enemy = function () {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = grid.column(-1);
    this.y = grid.row(1);

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function (dt) {
    this.x += dt * 40;
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function () {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.

var Player = function () {
    this.x = grid.column(2);
    this.y = grid.row(5);
    this.intent = null;
    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/char-boy.png';
};

Player.prototype.update = function () {
};

/**
 * Draw the player on screen
 */
Player.prototype.render = function () {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

/**
 * Handle input
 * @param {string} key
 */
Player.prototype.handleInput = function (key) {
    // TODO Restrict disallowed movements
    this.intent = key;
};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [new Enemy()];
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function (e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down',
    };

    player.handleInput(allowedKeys[e.keyCode]);
});
<commit_msg>feat: Implement simple player update<commit_after>/**
 * Grid for the game board. Use this to easily position
 * characters and game components.
 *
 * Examples: this.x = grid.column(5);
 *           this.y = grid.row(5);
 */
var grid = {
    /**
     * {number} pixels
     */
    COLUMN : 101,
    /**
     * {number} pixels
     */
    ROW    : 83,
    /**
     * {number} pixels
     */
    _OFFSET: 25,
};

/**
 * Return the proper pixel number for a given column
 * @param {number} column
 * @return {number} pixels
 */
grid.column = function (column) {
    return column * this.COLUMN;
};

/**
 * Return the proper pixel number for a given row
 * @param {number} row
 * @return {number} pixels
 */
grid.row = function (row) {
    return row * this.ROW - this._OFFSET;
};

// Enemies our player must avoid
var Enemy = function () {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = grid.column(-1);
    this.y = grid.row(1);

    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function (dt) {
    this.x += dt * 40;
    // You should multiply any movement by the dt parameter
    // which will ensure the game runs at the same speed for
    // all computers.
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function () {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.

var Player = function () {
    this.x = grid.column(2);
    this.y = grid.row(5);
    this.intent = null;
    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/char-boy.png';
};
/**
 * Update player's position, required method for game
 */
Player.prototype.update = function () {
    switch (this.intent) {
        case 'left':
            this.x -= grid.COLUMN;
            break;
        case 'up':
            this.y -= grid.ROW;
            break;
        case 'right':
            this.x += grid.COLUMN;
            break;
        case 'down':
            this.y += grid.ROW;
            break;
    }
    // intent was fulfilled
    this.intent = null;
};

/**
 * Draw the player on screen
 */
Player.prototype.render = function () {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

/**
 * Handle input
 * @param {string} key
 */
Player.prototype.handleInput = function (key) {
    // TODO Restrict disallowed movements
    this.intent = key;
};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [new Enemy()];
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function (e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down',
    };

    player.handleInput(allowedKeys[e.keyCode]);
});
<|endoftext|>


<commit_before>var myApp =  angular.module('myApp', [
    'ngRoute',
    'firebase',
    'myAppControllers'
]);

myApp.config(['$routeProvider', '$locationProvider',  function($routeProvider, $locationProvider) {
  "use strict";

  $routeProvider
    .when('/home', {
      templateUrl: 'partials/home.html',
      controller: 'HomeCtrl'
    })
    .when('/signup', {
      templateUrl: 'partials/signup.html',
      controller: 'SignUpCtrl'
    })
    .when('/login', {
      templateUrl: 'partials/login.html',
      controller: 'LogInCtrl'
    })
    .when('/idea/:ideaId', {
      templateUrl: 'partials/idea.html',
      controller: 'IdeaCtrl'
    })
    // Set defualt view of our app to home
    .otherwise({
      redirectTo: '/home'
    });

    $locationProvider.html5Mode(true);
  }
]);<commit_msg>update<commit_after>var myApp =  angular.module('myApp', [
    'ngRoute',
    'firebase',
    'myAppControllers'
]);

myApp.config(['$routeProvider', '$locationProvider',  function($routeProvider, $locationProvider) {
  "use strict";

  $routeProvider
    .when('home', {
      templateUrl: 'partials/home.html',
      controller: 'HomeCtrl'
    })
    .when('signup', {
      templateUrl: 'partials/signup.html',
      controller: 'SignUpCtrl'
    })
    .when('login', {
      templateUrl: 'partials/login.html',
      controller: 'LogInCtrl'
    })
    .when('idea/:ideaId', {
      templateUrl: 'partials/idea.html',
      controller: 'IdeaCtrl'
    })
    // Set defualt view of our app to home
    .otherwise({
      redirectTo: '/home'
    });

    $locationProvider.html5Mode(true);
  }
]);<|endoftext|>


<commit_before>var clientApp = angular.module('clientApp', ['ui.bootstrap', 'hljs', 'common', 'smart-table',
		'angulartics', 'angulartics.google.analytics']);

/**
 * Main application controller. Populates the form and submits the Service Request.
 */
clientApp.controller('ClientAppCtrl', function($scope, $log, AuthService, clientAppHelper, utils,
		ProgressbarService, advancedSettings, SERVICES_CONFIG, credentials) {
	//Populate the form.
	$scope.settings = advancedSettings;
	$scope.environments = SERVICES_CONFIG.environments;
	$scope.selectedEnvironment = SERVICES_CONFIG.environments[1].id;
	$scope.services = SERVICES_CONFIG.services;
	$scope.selectedService = SERVICES_CONFIG.services[0].id;
	$scope.serviceDescription = SERVICES_CONFIG.services[0].description;
	$scope.placeholder = SERVICES_CONFIG.placeholder;
	$scope.alerts = [];

	//Chrome specific operations. E.g. Chrome Storage related functionality.
	clientAppHelper.performChromeOperations($scope);

	//Submit the configured Service Request.
	$scope.submit = function() {
		//Remove any previous errors/alerts and hide the previous response.
		$scope.alerts = [];
		$scope.copyMessage = "";
		$scope.displayResponse = false;
		$scope.processing = true;

		//Update Progress Bar.
		$scope.progress = ProgressbarService.getProgressState('START');

		if (advancedSettings.autoAuthenticate) {
			//Check that they've supplied credentials. If so, persist them.
			if (!clientAppHelper.areCredentialsPresent()) {
				$scope.alerts.push({type: 'danger', msg: "You need to enter a user ID and a password for automatic authentication. Some services also require an Application ID. See 'Advanced Settings'."});
				$scope.processing = false;
				return;
			}
			clientAppHelper.persistCredentials($scope.selectedEnvironment);

			//Delete cookies that can interfere with authentication.
			clientAppHelper.deleteCookies();

			//Retrieve an Authentication Token based on the selected environment.
			var authEndpoint = clientAppHelper.configureServiceUrl($scope.selectedEnvironment, "auth");
			AuthService.getAuthCookie(authEndpoint).then(
				function(success) {
					clientAppHelper.configureAndCallService($scope, success.authorization);
				},
				function(error) {
					$log.error(error);
					$scope.alerts.push({type: 'danger', msg: "An error occurred while authenticating. Please check the Application ID, User ID and Password."});
					$scope.alerts.push({type: 'info', msg: "If the problem persists, you may want to try Incognito Mode or try clearing your cache. If the issue is solely with a particular environment, then the Authentication Service for that environment may be down."});
					$scope.processing = false;
				}
			);
		} else {
			clientAppHelper.configureAndCallService($scope, "(Automatic Authentication Disabled)");
		}
	};

	//Copy the request or response to the clipboard.
	$scope.copy = function(text) {
		$scope.copyMessage = "Successfully copied to the Clipboard.";
		utils.copyToClipboard(text);
	};

	$scope.changeEnvironment = function(env) {
		//Change the credentials to match the environment.
		if (credentials[env]) {
			advancedSettings.credentials = JSON.parse(JSON.stringify(credentials[env]));
		} else {
			advancedSettings.credentials = {};
		}

		//Display a warning if the production environment is selected.
		if (env === SERVICES_CONFIG.environments[2].id) {
			$scope.alerts.push({type: 'warning', msg: "Please be careful using the PRODUCTION environment. A valid production user and password need to be specified."});
		} else {
			$scope.alerts = [];
		}
	};

	//Update the service description to match the selected service.
	$scope.changeService = function(id) {
		for (var service of SERVICES_CONFIG.services) {
			if (service.id === id) {
				$scope.serviceDescription = service.description;
				break;
			}
		}
	};
});
<commit_msg>Update error message<commit_after>var clientApp = angular.module('clientApp', ['ui.bootstrap', 'hljs', 'common', 'smart-table',
		'angulartics', 'angulartics.google.analytics']);

/**
 * Main application controller. Populates the form and submits the Service Request.
 */
clientApp.controller('ClientAppCtrl', function($scope, $log, AuthService, clientAppHelper, utils,
		ProgressbarService, advancedSettings, SERVICES_CONFIG, credentials) {
	//Populate the form.
	$scope.settings = advancedSettings;
	$scope.environments = SERVICES_CONFIG.environments;
	$scope.selectedEnvironment = SERVICES_CONFIG.environments[1].id;
	$scope.services = SERVICES_CONFIG.services;
	$scope.selectedService = SERVICES_CONFIG.services[0].id;
	$scope.serviceDescription = SERVICES_CONFIG.services[0].description;
	$scope.placeholder = SERVICES_CONFIG.placeholder;
	$scope.alerts = [];

	//Chrome specific operations. E.g. Chrome Storage related functionality.
	clientAppHelper.performChromeOperations($scope);

	//Submit the configured Service Request.
	$scope.submit = function() {
		//Remove any previous errors/alerts and hide the previous response.
		$scope.alerts = [];
		$scope.copyMessage = "";
		$scope.displayResponse = false;
		$scope.processing = true;

		//Update Progress Bar.
		$scope.progress = ProgressbarService.getProgressState('START');

		if (advancedSettings.autoAuthenticate) {
			//Check that they've supplied credentials. If so, persist them.
			if (!clientAppHelper.areCredentialsPresent()) {
				$scope.alerts.push({type: 'danger', msg: "You need to enter a user ID and a password for automatic authentication. Some services also require an Application ID. See 'Advanced Settings'."});
				$scope.processing = false;
				return;
			}
			clientAppHelper.persistCredentials($scope.selectedEnvironment);

			//Delete cookies that can interfere with authentication.
			clientAppHelper.deleteCookies();

			//Retrieve an Authentication Token based on the selected environment.
			var authEndpoint = clientAppHelper.configureServiceUrl($scope.selectedEnvironment, "auth");
			AuthService.getAuthCookie(authEndpoint).then(
				function(success) {
					clientAppHelper.configureAndCallService($scope, success.authorization);
				},
				function(error) {
					$log.error(error);
					$scope.alerts.push({type: 'danger', msg: "An error occurred while authenticating. Please check the Application ID, User ID and Password."});
					$scope.alerts.push({type: 'info', msg: "If the problem persists, you may want to try Incognito Mode or try clearing your cache. If the issue is solely with a particular environment, then the Authentication Service for that environment may be down or the account may be locked out."});
					$scope.processing = false;
				}
			);
		} else {
			clientAppHelper.configureAndCallService($scope, "(Automatic Authentication Disabled)");
		}
	};

	//Copy the request or response to the clipboard.
	$scope.copy = function(text) {
		$scope.copyMessage = "Successfully copied to the Clipboard.";
		utils.copyToClipboard(text);
	};

	$scope.changeEnvironment = function(env) {
		//Change the credentials to match the environment.
		if (credentials[env]) {
			advancedSettings.credentials = JSON.parse(JSON.stringify(credentials[env]));
		} else {
			advancedSettings.credentials = {};
		}

		//Display a warning if the production environment is selected.
		if (env === SERVICES_CONFIG.environments[2].id) {
			$scope.alerts.push({type: 'warning', msg: "Please be careful using the PRODUCTION environment. A valid production user and password need to be specified."});
		} else {
			$scope.alerts = [];
		}
	};

	//Update the service description to match the selected service.
	$scope.changeService = function(id) {
		for (var service of SERVICES_CONFIG.services) {
			if (service.id === id) {
				$scope.serviceDescription = service.description;
				break;
			}
		}
	};
});
<|endoftext|>


<commit_before>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de marketing digital, no somos nadie."
    }
];

var objHerramientas =  [
    {
        url: "https://github.com/",
        linkText: "github",
        text: "Web que permite tener subidos tus repositorios git y así poder trabajar de forma colaborativa. Tiene versión Premiun con muchas mejoras. Dispone de las github-pages que te permiten desplegar webs estáticas incluso en la versión gratuita."
    },
    {
        url: "https://www.gitignore.io/",
        linkText: "gitignore",
        text: "Tras git init suele ser habitual crear un gitignore para configurar qué se debe ignorar en el historial. Esta aplicación nos ayudará mucho en esa tarea. Hay que indicarle qué tecnologías estamos usando y gitignore hace el resto."
    },
    {
        url: "http://web-dev.tools/",
        linkText: "Web Dev Tools",
        text: "Tres herramientas que te permiten generar tu propio framework CSS. Son, como si se tratase de los 3 mosqueteros, Gridifier, Typographier y Modulifier. Ideales para proyectos donde quieras ir con el menor peso posible."
    },
    {
        url: "http://www.regexr.com/",
        linkText: "Regexr",
        text: "Nos permite crear y probar en tiempo real expresiones regulares. Muy útil cuando ya estamos desesperados de buscar algo en stackoverflow y no damos con ello."
    },
    {
        url: "http://pxtoem.com/",
        linkText: "pxtoem",
        text: "Conversor de pixel a em y de em a pixel. Muy útil cuando recibimos diseños gráficos hechos en pixeles."
    },
    {
        url: "http://currentmillis.com/",
        linkText: "currentmillis",
        text: "¿Problemas con UTC time, local time, Epoch, Unix timestamp? Esta web te ayudará con ello."
    },
    {
        url: "http://bradfrost.github.io/this-is-responsive/patterns.html",
        linkText: "Plantillas responsive",
        text: "Sirven como boilerplates de una página, proyecto o landing page. No hay que redescubrir la rueda todos los días."
    },
    {
        url: "https://www.w3schools.com/colors/colors_converter.asp",
        linkText: "Convertidor códigos color",
        text: "Convierte todo tipo de códigos: RGB, Hex, HSL, CMYK y por nombre."
    },
    {
        url: "http://www.colorzilla.com/gradient-editor/",
        linkText: "ColorZilla Gradient Generator",
        text: "Herramienta para generar gradientes CSS. Se incluye soporte para IE9."
    },
    {
        url: "http://jeremyckahn.github.io/stylie/",
        linkText: "Stylie",
        text: "Una forma de ajustar tus animaciones CSS de forma visual sencilla."
    },
    {
        url: "http://www.tablesgenerator.com/",
        linkText: "Table generator",
        text: "Generador de tablas LaTex, HTML, Text tables, Markdown tables."
    },
    {
        url: "http://www.cssarrowplease.com/",
        linkText: "CSS arrow please",
        text: "Puedes configurar paneles con flecha, variando el tamaño y la posición de esta. Te da el código CSS para que llevártelo."
    },
    {
        url: "https://pixlr.com/",
        linkText: "Pixlr",
        text: "Una versión light y free de Photoshop online."
    },
    {
        url: "https://icomoon.io/",
        linkText: "Icomoon",
        text: "De las mejores herramientas para generar glifos para tu proyecto. Es modo freemium. Para cuando necesites algo más personalizado de Awesomefont."
    },
    {
        url: "http://lorempixel.com/",
        linkText: "Lorempixel",
        text: "Mientras recibimos las imágenes definitivas y estamos realizando ya la demo en paralelo, esta herramienta nos coloca una imagen al azar cada vez que la llamamos. Se pueden ajustar distintos parámetros como el tamaño y el tema. Creo que el nombre de lorempixel es bastante descriptivo ;)"
    },
    {
        url: "http://www.patternify.com/",
        linkText: "Patternify",
        text: "Generador para patrones de  CSS, ideal para lo que se conoce como grecas. Nos da la imagen en código Base 64."
    },
    {
        url: "https://coolors.co/",
        linkText: "Coolors",
        text: "Generador de paletas, 5 colores. Presenta un apartado para ver cómo se distingue tu paleta con distintas discapacidades."
    },
    {
        url: "https://gravit.io",
        linkText: "Gravit.io",
        text: "Herramienta de diseño gráfico. Una especie de Sketch online y gratuito."
    },
    {
        url: "https://developers.google.com/speed/pagespeed",
        linkText: "Google PageSpeed Insights",
        text: "Herramienta de Google que nos proporciona un informe de mejora rendimiento de nuestra web. Hay que introducir la URL pública y PageSpeed se encarga del resto."
    },
    {
        url: "https://www.sendwithus.com/",
        linkText: "Send with us",
        text: "Te permite realizar envios de email para comprobar tus propios diseños en los distintos clientes web. Lo permite hacer de forma más rápida que mailchimp, simplemente crea tu diseño y haz el envio."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    },
    mounted: function () {
       console.log("blogs is now rendered");
    }
});
var herramientas = new Vue({
    el: '#herramientas',
    data: {
        sectionTitle: "Herramientas",
        aryHerramientas: objHerramientas
    },
    mounted: function () {
       console.log("herramientas is now rendered");
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<commit_msg>Diffnow<commit_after>var objLinkList = [
            { href: "#blogs", linkText: "Blogs" },
            { href: "#herramientas", linkText: "Herramientas" }
        ];
var objBlogs =  [
    {
        url: "https://css-tricks.com/",
        linkText: "css-tricks",
        text: "Indudablemente una de las webs número uno de consulta para un frontend. Artículos y tutoriales de calidad y un buen número de snippets."
    },
    {
        url: "https://www.smashingmagazine.com/",
        linkText: "Smashing Magazine",
        text: "Todo un referente en el mundo de la web. Código, diseño, mobile, UX ... etc. Publican libros con colecciones de sus artículos más interesantes."
    },
    {
        url: "https://www.sitepoint.com/",
        linkText: "Site Point",
        text: "Artículos meticulosos de gran calidad, podcast, libros y cursos (a veces gratis). También imprescindible."
    },
    {
        url: "https://scotch.io/",
        linkText: "Scotch.io",
        text: "Tutoriales excelentes sobre el mundo frontend y backend javascript. Disponen de cursos free y premium. ¡¡No perdérselo!!"
    },
    {
        url: "https://davidwalsh.name/",
        linkText: "David Walsh Blog",
        text: "log del gurú JavaScript David Walsh. Conviene seguirle y leer sus interesantes artículos. No solo habla de JavaScript, también aborda otras tecnologías web."
    },
    {
        url: "http://alistapart.com/articles",
        linkText: "A List Apart",
        text: "Artículos de todo lo relacionado con la web. Son artículos de una calidad tan extraordinaria que algunos son un referente."
    },
    {
        url: "https://webmasters.googleblog.com/",
        linkText: "Google Webmaster Blog",
        text: "No puede faltar el blog oficial de Google para webmasters."
    },
    {
        url: "http://lea.verou.me/",
        linkText: "Lea Verou",
        text: "La gran Lea Verou. Proyectos, charlas, artículos. Una eminencia en el CSS."
    },
    {
        url: "http://wesbos.com/blog/",
        linkText: "Web Bos",
        text: "Artículos, videos y tutoriales"
    },
    {
        url: "http://www.developerdrive.com/",
        linkText: "Developer Drive",
        text: "Artículos sobre todo tipo de tecnología de desarrollo web."
    },
    {
        url: "http://www.cssportal.com/",
        linkText: "CSS Portal",
        text: "Snippets, generadores y herramientas para desarrollar en CSS."
    },
    {
        url: "http://www.elmaquetadorweb.com/",
        linkText: "El maquetador web",
        text: "Excelente blog mantenido por Javi Luna y Pedro Marín donde nos cuentan muchos trucos en esto del CSS. Me encanta el nombre de maquetador, término en desuso hoy en día.  ;D"
    },
    {
        url: "https://toddmotto.com/",
        linkText: "Todd Motto",
        text: "Artículos y tutoriales sobre JavaScript, Angular y Typescript. Dispone de muy buenos cursos en premium."
    },
    {
        url: "http://valhead.com/blog/",
        linkText: "Val Head Blog",
        text: "Artículos y tutoriales de una especialista en animaciones CSS web."
    },
    {
        url: "https://codyhouse.co/",
        linkText: "Cody House",
        text: "Colecciones gratuitas de snippets de HTML, CSS y JavaScript. También disponen de cursos premium."
    },
    {
        url: "http://www.kylejlarson.com/blog/ ",
        linkText: "kyle J. Larson",
        text: "Buenos consejos para el diseño web."
    },
    {
        url: "http://www.naderdabit.me/#/",
        linkText: "Nader Dabit",
        text: "Tutoriales sobre ReactJS, Angular, NPM ."
    },
    {
        url: "http://mrbool.com/",
        linkText: "Mr. Bool",
        text: "Tutoriales y cursos. ES6, Node+NPM, Ionic, Angular, NoSQL."
    },
    {
        url: "http://www.marketingenredes.com/",
        linkText: "Marketing en redes",
        text: "Sin unos buenos consejos como estos de marketing digital, no somos nadie."
    }
];

var objHerramientas =  [
    {
        url: "https://github.com/",
        linkText: "github",
        text: "Web que permite tener subidos tus repositorios git y así poder trabajar de forma colaborativa. Tiene versión Premiun con muchas mejoras. Dispone de las github-pages que te permiten desplegar webs estáticas incluso en la versión gratuita."
    },
    {
        url: "https://www.gitignore.io/",
        linkText: "gitignore",
        text: "Tras git init suele ser habitual crear un gitignore para configurar qué se debe ignorar en el historial. Esta aplicación nos ayudará mucho en esa tarea. Hay que indicarle qué tecnologías estamos usando y gitignore hace el resto."
    },
    {
        url: "http://web-dev.tools/",
        linkText: "Web Dev Tools",
        text: "Tres herramientas que te permiten generar tu propio framework CSS. Son, como si se tratase de los 3 mosqueteros, Gridifier, Typographier y Modulifier. Ideales para proyectos donde quieras ir con el menor peso posible."
    },
    {
        url: "http://www.regexr.com/",
        linkText: "Regexr",
        text: "Nos permite crear y probar en tiempo real expresiones regulares. Muy útil cuando ya estamos desesperados de buscar algo en stackoverflow y no damos con ello."
    },
    {
        url: "http://pxtoem.com/",
        linkText: "pxtoem",
        text: "Conversor de pixel a em y de em a pixel. Muy útil cuando recibimos diseños gráficos hechos en pixeles."
    },
    {
        url: "http://currentmillis.com/",
        linkText: "currentmillis",
        text: "¿Problemas con UTC time, local time, Epoch, Unix timestamp? Esta web te ayudará con ello."
    },
    {
        url: "http://bradfrost.github.io/this-is-responsive/patterns.html",
        linkText: "Plantillas responsive",
        text: "Sirven como boilerplates de una página, proyecto o landing page. No hay que redescubrir la rueda todos los días."
    },
    {
        url: "https://www.w3schools.com/colors/colors_converter.asp",
        linkText: "Convertidor códigos color",
        text: "Convierte todo tipo de códigos: RGB, Hex, HSL, CMYK y por nombre."
    },
    {
        url: "http://www.colorzilla.com/gradient-editor/",
        linkText: "ColorZilla Gradient Generator",
        text: "Herramienta para generar gradientes CSS. Se incluye soporte para IE9."
    },
    {
        url: "http://jeremyckahn.github.io/stylie/",
        linkText: "Stylie",
        text: "Una forma de ajustar tus animaciones CSS de forma visual sencilla."
    },
    {
        url: "http://www.tablesgenerator.com/",
        linkText: "Table generator",
        text: "Generador de tablas LaTex, HTML, Text tables, Markdown tables."
    },
    {
        url: "http://www.cssarrowplease.com/",
        linkText: "CSS arrow please",
        text: "Puedes configurar paneles con flecha, variando el tamaño y la posición de esta. Te da el código CSS para que llevártelo."
    },
    {
        url: "https://pixlr.com/",
        linkText: "Pixlr",
        text: "Una versión light y free de Photoshop online."
    },
    {
        url: "https://icomoon.io/",
        linkText: "Icomoon",
        text: "De las mejores herramientas para generar glifos para tu proyecto. Es modo freemium. Para cuando necesites algo más personalizado de Awesomefont."
    },
    {
        url: "http://lorempixel.com/",
        linkText: "Lorempixel",
        text: "Mientras recibimos las imágenes definitivas y estamos realizando ya la demo en paralelo, esta herramienta nos coloca una imagen al azar cada vez que la llamamos. Se pueden ajustar distintos parámetros como el tamaño y el tema. Creo que el nombre de lorempixel es bastante descriptivo ;)"
    },
    {
        url: "http://www.patternify.com/",
        linkText: "Patternify",
        text: "Generador para patrones de  CSS, ideal para lo que se conoce como grecas. Nos da la imagen en código Base 64."
    },
    {
        url: "https://coolors.co/",
        linkText: "Coolors",
        text: "Generador de paletas, 5 colores. Presenta un apartado para ver cómo se distingue tu paleta con distintas discapacidades."
    },
    {
        url: "https://gravit.io",
        linkText: "Gravit.io",
        text: "Herramienta de diseño gráfico. Una especie de Sketch online y gratuito."
    },
    {
        url: "https://developers.google.com/speed/pagespeed",
        linkText: "Google PageSpeed Insights",
        text: "Herramienta de Google que nos proporciona un informe de mejora rendimiento de nuestra web. Hay que introducir la URL pública y PageSpeed se encarga del resto."
    },
    {
        url: "https://www.sendwithus.com/",
        linkText: "Send with us",
        text: "Te permite realizar envios de email para comprobar tus propios diseños en los distintos clientes web. Lo permite hacer de forma más rápida que mailchimp, simplemente crea tu diseño y haz el envio."
    },
    {
        url: "https://www.diffnow.com/",
        linkText: "Diffnow",
        text: "Para esas comparaciones rápidas que a veces nos surgen. Lo más intesante es que permite hacer comparaciones copy&paste utilizando fragmentos de código."
    }
];

var siteNavigation = new Vue({
    el: "#site-navigation",
    data: {
        linkList: objLinkList
    }
});
var blogs = new Vue({
    el: '#blogs',
    data: {
        sectionTitle: "Blogs",
        aryBlogs: objBlogs
    },
    mounted: function () {
       console.log("blogs is now rendered");
    }
});
var herramientas = new Vue({
    el: '#herramientas',
    data: {
        sectionTitle: "Herramientas",
        aryHerramientas: objHerramientas
    },
    mounted: function () {
       console.log("herramientas is now rendered");
    }
});
var footer = new Vue({
  el: '#footer',
  data: {
    copyright: 'Copyright © ' + new Date().getFullYear() + ' Aitor Alejandro Herrera. MIT License'
  }
});
<|endoftext|>


<commit_before>var app = {
    initialize: function() {
	// Application Constructor
		//Setup authenticator
		log('Setting up auth0Lock');
		this.lock = new Auth0Lock('z0y1xeT9bMcjKuC0ftlsCjL3VWQbBbEE', 'quackrr.auth0.com');

		this.model = new Model();

		this.setupURLS();

		this.setupAJAX();

		this.loggedin = (localStorage.getItem('userID') != null);
		if (this.loggedin == true){
			log('retrieving profile..');
			this.userProfile = this.model.getProfile();
			if (!this.userProfile) {
				log('Token has expired.');
				setInfoMessage('Your session has expired. Please login again.');
				app.loggedin = false;
			}
		}

		//-- for internal testing
		Handlebars.registerHelper('json', function(context) {
    		return JSON.stringify(context);
		});

		this.bindEvents();
		this.route(); //!!! temporary for testing
    },

    setupURLS: function() {
	// Setup RegEx URLs of our routes
		this.loginURL = /#login/;
		this.dologinURL = /#dologin/;
		this.registerURL = /#register/;
		this.doregisterURL = /#doregister/;
		this.overviewURL = /#overview/;
		this.logoutURL = /#logout/;
		this.exitURL = /#exit/;
		this.categoriesURL = /#categories/;
		this.categoryURL = /#category/;
		this.questionsURL = /#random/;
		this.questionURL = /#question/;
		this.profileURL = /#profile/;
		this.nextURL = /#next/;
    },

    bindEvents: function() {
    // Bind all our events
    	document.addEventListener('deviceready', this.onDeviceReady, false); //cordova
    	this.onDeviceReady(); //temp cuz no cordova
    },

    setupAJAX: function() {
    // Setup secure AjaX calls
        log('Setting up secure AjaX calls');
        $.ajaxSetup({
		  'beforeSend': function(xhr) {
		    if (localStorage.getItem('userToken')) {
		      xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('userToken'));
		      if (app.userProfile){
			      xhr.setRequestHeader('ID', app.userProfile.user_id);
			  }
		    }
		  }
		});
    },

    onDeviceReady: function() {
    // When everything is loaded, do this
    	//Setup routing
    	log('Setting up routes');
        $(window).on('hashchange', $.proxy(this.route, this));
    },

    logout: function() {
    	this.loggedin = false;
    	localStorage.removeItem('token');
    	localStorage.removeItem('userID');
		this.userProfile = null;
		history.pushState("", document.title, window.location.pathname); //Reset hash to prevent logging us out when logging in!
		redirect('login');
    },

    getID: function(url) {
    	var idmatch = /\?id=(\d+)/;
    	var matches = url.match(idmatch);
    	if (matches){
    		return matches[1];
    	} else {
    		return false;
    	}
    },

    getPar: function(url, par) {
    	var match = new RegExp("(?:\\?|&)" + par + "=" + "(\\d+)");
    	log(match);
    	var result = url.match(match);
    	if (result){
    		return result[1];
    	} else {
    		return false;
    	}
    },

    route: function(eventt, input) {
    // route is called when a link is clicked
    	var hash = input;
    	if (!hash){
    		if (window.location.hash){
    			hash = window.location.hash;
    		} else {
    			hash = "";
    		}
    	}

    	if (hash.match(/#clearcache/)){
    		$.jStorage.flush();
    		redirect('overview');
    	} else

	    if (hash.match(app.exitURL)){
	    	if(navigator.app){
        		navigator.app.exitApp();
			} else if(navigator.device){
        		navigator.device.exitApp();
			}
	    } else
	    if (!app.loggedin){
	    	log('user not logged in');
	    	if (hash.match(app.registerURL)){
	    		//Process register
	    		var rv = new RegisterView();
				return;
	    	} else if (hash.match(app.doregisterURL)) {
    			var rv = new RegisterView(document.getElementById('login').value, document.getElementById('pass').value, document.getElementById('firstname').value, document.getElementById('lastname').value);
	    		return;
	    	} else if (hash.match(app.dologinURL)) {
	    		var lv = new LoginView(document.getElementById('login').value, document.getElementById('pass').value);
	    		return;
	    	} else {
	    		//Process login
	    		var lv = new LoginView();
	    		return;
	    	}
    	} else {
    		log('user is logged in!');
		    //-- we are sure user is logged in from now on
		    if (hash.match(app.logoutURL)){
		    	this.logout();
		    	return;
		    } else if (hash.match(app.categoriesURL)){
		    	var cv = new CategoriesView();
		    	return;
		    } else if (hash.match(app.categoryURL)){
		    	var cid = this.getID(hash);
		    	if (cid){
		    		var cv = new CategoryView(cid);
		    	} else {
		    		setErrorMessage("No category chosen!");
		    		redirect("overview");
		    	}
		    	return;
		    } else if (hash.match(app.questionURL)){
		    	var qid = this.getID(hash);
		    	if (qid){
		    		var qv = new QuestionView(qid);
		    	} else {
		    		log('no question id given');
		    		setErrorMessage("No question chosen!");
		    		redirect('overview');
		    	}
		    	return;
		    } else if (hash.match(this.questionsURL)){
		    	var qv = new QuestionsView();
		    	return;
		    } else if (hash.match(this.nextURL)) {
		    	var cid = this.getID(hash);
		    	if (cid){
		    		var q = this.model.getRandomQuestion(cid);
		    		if (q){
		    			var qv = new QuestionView(q.catid);
		    		} else {
		    			setInfoMessage('You finished this level! Turn on your internet and go to the category again.');
		    			redirect('overview');
		    		}
		    	} else {
		    		log('no cat id given');
		    		setErrorMessage('No category chosen!');
		    		redirect('overview');
		    	}
		    } else if (hash.match(app.profileURL)){
		    	var pv = new ProfileView();
		    	return;
		    } else {
		    	log(hash);
		    	var ov = new OverviewView();
		    	return;
		    }
		}
    }

};
<commit_msg>Clear cache on logout<commit_after>var app = {
    initialize: function() {
	// Application Constructor
		//Setup authenticator
		log('Setting up auth0Lock');
		this.lock = new Auth0Lock('z0y1xeT9bMcjKuC0ftlsCjL3VWQbBbEE', 'quackrr.auth0.com');

		this.model = new Model();

		this.setupURLS();

		this.setupAJAX();

		this.loggedin = (localStorage.getItem('userID') != null);
		if (this.loggedin == true){
			log('retrieving profile..');
			this.userProfile = this.model.getProfile();
			if (!this.userProfile) {
				log('Token has expired.');
				setInfoMessage('Your session has expired. Please login again.');
				app.loggedin = false;
			}
		}

		//-- for internal testing
		Handlebars.registerHelper('json', function(context) {
    		return JSON.stringify(context);
		});

		this.bindEvents();
		this.route(); //!!! temporary for testing
    },

    setupURLS: function() {
	// Setup RegEx URLs of our routes
		this.loginURL = /#login/;
		this.dologinURL = /#dologin/;
		this.registerURL = /#register/;
		this.doregisterURL = /#doregister/;
		this.overviewURL = /#overview/;
		this.logoutURL = /#logout/;
		this.exitURL = /#exit/;
		this.categoriesURL = /#categories/;
		this.categoryURL = /#category/;
		this.questionsURL = /#random/;
		this.questionURL = /#question/;
		this.profileURL = /#profile/;
		this.nextURL = /#next/;
    },

    bindEvents: function() {
    // Bind all our events
    	document.addEventListener('deviceready', this.onDeviceReady, false); //cordova
    	this.onDeviceReady(); //temp cuz no cordova
    },

    setupAJAX: function() {
    // Setup secure AjaX calls
        log('Setting up secure AjaX calls');
        $.ajaxSetup({
		  'beforeSend': function(xhr) {
		    if (localStorage.getItem('userToken')) {
		      xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('userToken'));
		      if (app.userProfile){
			      xhr.setRequestHeader('ID', app.userProfile.user_id);
			  }
		    }
		  }
		});
    },

    onDeviceReady: function() {
    // When everything is loaded, do this
    	//Setup routing
    	log('Setting up routes');
        $(window).on('hashchange', $.proxy(this.route, this));
    },

    logout: function() {
    	this.loggedin = false;
    	localStorage.removeItem('token');
    	localStorage.removeItem('userID');
    	$.jStorage.flush(); //cache
		this.userProfile = null;
		history.pushState("", document.title, window.location.pathname); //Reset hash to prevent logging us out when logging in!
		redirect('login');
    },

    getID: function(url) {
    	var idmatch = /\?id=(\d+)/;
    	var matches = url.match(idmatch);
    	if (matches){
    		return matches[1];
    	} else {
    		return false;
    	}
    },

    getPar: function(url, par) {
    	var match = new RegExp("(?:\\?|&)" + par + "=" + "(\\d+)");
    	log(match);
    	var result = url.match(match);
    	if (result){
    		return result[1];
    	} else {
    		return false;
    	}
    },

    route: function(eventt, input) {
    // route is called when a link is clicked
    	var hash = input;
    	if (!hash){
    		if (window.location.hash){
    			hash = window.location.hash;
    		} else {
    			hash = "";
    		}
    	}

    	if (hash.match(/#clearcache/)){
    		$.jStorage.flush();
    		redirect('overview');
    	} else

	    if (hash.match(app.exitURL)){
	    	if(navigator.app){
        		navigator.app.exitApp();
			} else if(navigator.device){
        		navigator.device.exitApp();
			}
	    } else
	    if (!app.loggedin){
	    	log('user not logged in');
	    	if (hash.match(app.registerURL)){
	    		//Process register
	    		var rv = new RegisterView();
				return;
	    	} else if (hash.match(app.doregisterURL)) {
    			var rv = new RegisterView(document.getElementById('login').value, document.getElementById('pass').value, document.getElementById('firstname').value, document.getElementById('lastname').value);
	    		return;
	    	} else if (hash.match(app.dologinURL)) {
	    		var lv = new LoginView(document.getElementById('login').value, document.getElementById('pass').value);
	    		return;
	    	} else {
	    		//Process login
	    		var lv = new LoginView();
	    		return;
	    	}
    	} else {
    		log('user is logged in!');
		    //-- we are sure user is logged in from now on
		    if (hash.match(app.logoutURL)){
		    	this.logout();
		    	return;
		    } else if (hash.match(app.categoriesURL)){
		    	var cv = new CategoriesView();
		    	return;
		    } else if (hash.match(app.categoryURL)){
		    	var cid = this.getID(hash);
		    	if (cid){
		    		var cv = new CategoryView(cid);
		    	} else {
		    		setErrorMessage("No category chosen!");
		    		redirect("overview");
		    	}
		    	return;
		    } else if (hash.match(app.questionURL)){
		    	var qid = this.getID(hash);
		    	if (qid){
		    		var qv = new QuestionView(qid);
		    	} else {
		    		log('no cat id given');
		    		setErrorMessage("No question chosen!");
		    		redirect('overview');
		    	}
		    	return;
		    } else if (hash.match(this.questionsURL)){
		    	var qv = new QuestionsView();
		    	return;
		    } else if (hash.match(this.nextURL)) {
		    	var cid = this.getID(hash);
		    	if (cid){
		    		var q = this.model.getRandomQuestion(cid);
		    		if (q){
		    			var qv = new QuestionView(q.catid);
		    		} else {
		    			setInfoMessage('You finished this level! Turn on your internet and go to the category again.');
		    			redirect('overview');
		    		}
		    	} else {
		    		log('no cat id given');
		    		setErrorMessage('No category chosen!');
		    		redirect('overview');
		    	}
		    } else if (hash.match(app.profileURL)){
		    	var pv = new ProfileView();
		    	return;
		    } else {
		    	log(hash);
		    	var ov = new OverviewView();
		    	return;
		    }
		}
    }

};
<|endoftext|>