<commit_before>'use strict';

const	Intercom	= require('larvitamintercom'),
	request	= require('request'),
	assert	= require('assert'),
	amsync	= require(__dirname + '/../index.js'),
	async	= require('async'),
	http	= require('http'),
	nics	= require('os').networkInterfaces(),
	log	= require('winston'),
	sql	= 'CREATE TABLE `bosse` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL); INSERT INTO bosse (name) VALUES(\'duh\');',
	db	= require('larvitdb'),
	fs	= require('fs'),
	_	= require('lodash');

let	intercomConfigFile,
	intercom;

// Set up winston
log.remove(log.transports.Console);
/**/log.add(log.transports.Console, {
	'level':	'warn',
	'colorize':	true,
	'timestamp':	true,
	'json':	false
});/**/

before(function (done) {
	this.timeout(10000);
	const	tasks	= [];

	// Run DB Setup
	tasks.push(function (cb) {
		let confFile;

		if (process.env.DBCONFFILE === undefined) {
			confFile = __dirname + '/../config/db_test.json';
		} else {
			confFile = process.env.DBCONFFILE;
		}

		log.verbose('DB config file: "' + confFile + '"');

		// First look for absolute path
		fs.stat(confFile, function (err) {
			if (err) {

				// Then look for this string in the config folder
				confFile = __dirname + '/../config/' + confFile;
				fs.stat(confFile, function (err) {
					if (err) throw err;
					log.verbose('DB config: ' + JSON.stringify(require(confFile)));
					db.setup(require(confFile), cb);
				});

				return;
			}

			log.verbose('DB config: ' + JSON.stringify(require(confFile)));
			db.setup(require(confFile), cb);
		});
	});

	// Check for empty db
	tasks.push(function (cb) {
		db.query('SHOW TABLES', function (err, rows) {
			if (err) throw err;

			if (rows.length) {
				throw new Error('Database is not empty. To make a test, you must supply an empty database!');
			}

			cb();
		});
	});

	// Get intercom config file and start intercom
	tasks.push(function (cb) {
		if (process.env.INTCONFFILE === undefined) {
			intercomConfigFile = __dirname + '/../config/amqp_test.json';
		} else {
			intercomConfigFile = process.env.INTCONFFILE;
		}

		log.verbose('Intercom config file: "' + intercomConfigFile + '"');

		// First look for absolute path
		fs.stat(intercomConfigFile, function (err) {
			if (err) {

				// Then look for this string in the config folder
				intercomConfigFile = __dirname + '/../config/' + intercomConfigFile;
				fs.stat(intercomConfigFile, function (err) {
					if (err) throw err;
					log.verbose('Intercom config: ' + JSON.stringify(require(intercomConfigFile)));
					intercom	= new Intercom(require(intercomConfigFile));
					intercom.on('ready', cb);
				});

				return;
			}

			log.verbose('Intercom config: ' + JSON.stringify(require(intercomConfigFile)));
			intercom = new Intercom(require(intercomConfigFile));
			intercom.on('ready', cb);
		});
	});

	async.series(tasks, done);
});

describe('Basics', function () {
	it('server', function (done) {
		const	exchangeName	= 'test_dataDump_server',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			options	= {'exchange': exchangeName},
			tasks	= [];

		let	msgHandled	= false;

		this.slow(500);

		function handleMsg(message, ack) {
			const	reqOptions	= {};

			ack();

			if (message.action !== 'dumpResponse' || msgHandled !== false) {
				return;
			}

			msgHandled = true;

			assert(message.endpoints, 'message.endpoints must an array with entries');

			if (message.endpoints[0].family === 'IPv6') {
				reqOptions.uri = 'http://[' + message.endpoints[0].host + ']';
			} else {
				reqOptions.uri = 'http://' + message.endpoints[0].host;
			}

			reqOptions.uri	+= ':' + message.endpoints[0].port;
			reqOptions.headers	= {'token': message.endpoints[0].token};

			request(reqOptions, function (err, res, body) {
				if (err) throw err;

				assert.deepEqual(_.trim(body), _.trim(sql));
				done();
			});
		}

		// Start server
		tasks.push(function (cb) {
			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom2;

			new amsync.SyncServer(options, cb);
		});

		// Subscribe to happenings on the queue on intercom1
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleMsg, cb);
		});

		// Send the request to the queue
		tasks.push(function (cb) {
			intercom1.send({'action': 'requestDump', 'noOfTokens': 1}, {'exchange': exchangeName}, cb);
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});

	it('client', function (done) {
		const	exchangeName	= 'test_dataDump_client',
			msgContent	= 'wlüpp!',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			token	= 'fjärtkorv',
			tasks	= [];

		this.slow(500);

		function handleIncMsg(message, ack) {
			ack();

			if (message.action !== 'requestDump') {
				return;
			}

			let	server;

			server = http.createServer(function (req, res) {
				assert.deepEqual(req.headers.token, token);
				res.writeHead(200, {'Content-Type': 'plain/text'});
				res.end(msgContent);
				server.close();
			});
			server.listen(0);
			server.on('error', function (err) {
				throw err;
			});

			server.on('listening', function () {
				const	servedPort	= server.address().port,
					message	= {'action': 'dumpResponse', 'endpoints': []};

				for (const nic of Object.keys(nics)) {
					for (let i = 0; nics[nic][i] !== undefined; i ++) {
						const	nicAddress	= nics[nic][i];

						if (nicAddress.internal === false) {
							message.endpoints.push({
								'family':	nicAddress.family,
								'host':	nicAddress.address,
								'port':	servedPort,
								'token':	token
							});
						}
					}
				}

				intercom1.send(message, {'exchange': exchangeName});
			});
		}

		// Listen to the queue for dump requests
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleIncMsg, cb);
		});

		// Start client
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			new amsync.SyncClient(options, function (err, res) {
				let	syncData	= Buffer.from('');

				if (err) { cb(err); return; }

				res.on('data', function (chunk) {
					syncData	=	Buffer.concat([syncData, chunk], syncData.length + chunk.length);
				});

				res.on('end', function () {
					assert.deepEqual(syncData.toString(), msgContent);
					done();
				});

				res.on('error', cb);
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});

	it('server with port range', function (done) {
		const	exchangeName	= 'test_dataDump_server',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			options	= {'exchange': exchangeName},
			tasks	= [];

		let	msgHandled	= false;

		this.slow(500);

		function handleMsg(message, ack) {
			const	reqOptions	= {};

			ack();

			if (message.action !== 'dumpResponse' || msgHandled !== false) {
				return;
			}

			msgHandled = true;

			assert(message.endpoints, 'message.endpoints must an array with entries');

			if (message.endpoints[0].family === 'IPv6') {
				reqOptions.uri = 'http://[' + message.endpoints[0].host + ']';
			} else {
				reqOptions.uri = 'http://' + message.endpoints[0].host;
			}

			reqOptions.uri	+= ':' + message.endpoints[0].port;

			reqOptions.headers	= {'token': message.endpoints[0].token};

			request(reqOptions, function (err, res, body) {
				if (err) throw err;

				assert.deepEqual(_.trim(body), _.trim(sql));
				done();
			});
		}

		// Start server
		tasks.push(function (cb) {
			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom2;
			options.minPort	= 9000;
			options.maxPort	= 9100;

			new amsync.SyncServer(options, cb);
		});

		// Subscribe to happenings on the queue on intercom1
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleMsg, cb);
		});

		// Send the request to the queue
		tasks.push(function (cb) {
			intercom1.send({'action': 'requestDump', 'noOfTokens': 1}, {'exchange': exchangeName}, cb);
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});
});

describe('Database', function () {
	it('should sync MariaDB/MySQL stuff', function (done) {
		const	exchangeName	= 'test_dataDump_mariadb',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			tasks	= [];

		this.slow(500);

		// Start server
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName};

			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom1;

			new amsync.SyncServer(options, cb);
		});

		// Write sync to db
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			amsync.mariadb(options, cb);
		});

		// Check database
		tasks.push(function (cb) {
			db.query('SELECT * FROM bosse', function (err, rows) {
				if (err) throw err;

				assert.deepEqual(rows.length,	1);
				assert.deepEqual(rows[0].id,	1);
				assert.deepEqual(rows[0].name,	'duh');
				cb();
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;

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

describe('Custom http receiver', function () {
	it('should read path', function (done) {
		const	exchangeName	= 'test_dataDump_custom',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			tasks	= [];

		this.slow(500);

		// Wait for the intercoms to come online
		tasks.push(function (cb) {intercom1.ready(cb);});
		tasks.push(function (cb) {intercom2.ready(cb);});

		// Start server
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom1};

			let	syncServer;

			syncServer = new amsync.SyncServer(options, cb);

			syncServer.handleHttpReq_original = syncServer.handleHttpReq;

			syncServer.handleHttpReq = function (req, res) {

				// Set custom content type
				res.setHeader('Content-Type', 'text/plain');
				//console.log(req);
				// Run different commands depending on request url
				if (req.url === '/') {
					syncServer.options.dataDumpCmd = {'command': 'echo', 'args': ['-n', 'blergh']};
				} else {
					syncServer.options.dataDumpCmd = {'command': 'echo', 'args': ['-n', req.url]};
				}

				// Run the original request handler
				syncServer.handleHttpReq_original(req, res);
			};
		});

		// Start the client
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			options.requestOptions	= {'path': '/foobar'};

			new amsync.SyncClient(options, function (err, res) {
				let	syncData	= Buffer.from('');

				if (err) throw err;

				res.on('data', function (chunk) {
					syncData	=	Buffer.concat([syncData, chunk], syncData.length + chunk.length);
				});

				res.on('end', function () {
					assert.deepEqual(syncData.toString(), options.requestOptions.path);
					cb();
				});

				res.on('error', function (err) {
					throw err;
				});
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;
			done();
		});
	});
});

after(function (done) {
	db.removeAllTables(done);
});
<commit_msg>Removed noOfTokens from tests since there is no support for it anyways<commit_after>'use strict';

const	Intercom	= require('larvitamintercom'),
	request	= require('request'),
	assert	= require('assert'),
	amsync	= require(__dirname + '/../index.js'),
	async	= require('async'),
	http	= require('http'),
	nics	= require('os').networkInterfaces(),
	log	= require('winston'),
	sql	= 'CREATE TABLE `bosse` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL); INSERT INTO bosse (name) VALUES(\'duh\');',
	db	= require('larvitdb'),
	fs	= require('fs'),
	_	= require('lodash');

let	intercomConfigFile,
	intercom;

// Set up winston
log.remove(log.transports.Console);
/**/log.add(log.transports.Console, {
	'level':	'warn',
	'colorize':	true,
	'timestamp':	true,
	'json':	false
});/**/

before(function (done) {
	this.timeout(10000);
	const	tasks	= [];

	// Run DB Setup
	tasks.push(function (cb) {
		let confFile;

		if (process.env.DBCONFFILE === undefined) {
			confFile = __dirname + '/../config/db_test.json';
		} else {
			confFile = process.env.DBCONFFILE;
		}

		log.verbose('DB config file: "' + confFile + '"');

		// First look for absolute path
		fs.stat(confFile, function (err) {
			if (err) {

				// Then look for this string in the config folder
				confFile = __dirname + '/../config/' + confFile;
				fs.stat(confFile, function (err) {
					if (err) throw err;
					log.verbose('DB config: ' + JSON.stringify(require(confFile)));
					db.setup(require(confFile), cb);
				});

				return;
			}

			log.verbose('DB config: ' + JSON.stringify(require(confFile)));
			db.setup(require(confFile), cb);
		});
	});

	// Check for empty db
	tasks.push(function (cb) {
		db.query('SHOW TABLES', function (err, rows) {
			if (err) throw err;

			if (rows.length) {
				throw new Error('Database is not empty. To make a test, you must supply an empty database!');
			}

			cb();
		});
	});

	// Get intercom config file and start intercom
	tasks.push(function (cb) {
		if (process.env.INTCONFFILE === undefined) {
			intercomConfigFile = __dirname + '/../config/amqp_test.json';
		} else {
			intercomConfigFile = process.env.INTCONFFILE;
		}

		log.verbose('Intercom config file: "' + intercomConfigFile + '"');

		// First look for absolute path
		fs.stat(intercomConfigFile, function (err) {
			if (err) {

				// Then look for this string in the config folder
				intercomConfigFile = __dirname + '/../config/' + intercomConfigFile;
				fs.stat(intercomConfigFile, function (err) {
					if (err) throw err;
					log.verbose('Intercom config: ' + JSON.stringify(require(intercomConfigFile)));
					intercom	= new Intercom(require(intercomConfigFile));
					intercom.on('ready', cb);
				});

				return;
			}

			log.verbose('Intercom config: ' + JSON.stringify(require(intercomConfigFile)));
			intercom = new Intercom(require(intercomConfigFile));
			intercom.on('ready', cb);
		});
	});

	async.series(tasks, done);
});

describe('Basics', function () {
	it('server', function (done) {
		const	exchangeName	= 'test_dataDump_server',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			options	= {'exchange': exchangeName},
			tasks	= [];

		let	msgHandled	= false;

		this.slow(500);

		function handleMsg(message, ack) {
			const	reqOptions	= {};

			ack();

			if (message.action !== 'dumpResponse' || msgHandled !== false) {
				return;
			}

			msgHandled = true;

			assert(message.endpoints, 'message.endpoints must an array with entries');

			if (message.endpoints[0].family === 'IPv6') {
				reqOptions.uri	= 'http://[' + message.endpoints[0].host + ']';
			} else {
				reqOptions.uri	= 'http://' + message.endpoints[0].host;
			}

			reqOptions.uri	+= ':' + message.endpoints[0].port;
			reqOptions.headers	= {'token': message.endpoints[0].token};

			request(reqOptions, function (err, res, body) {
				if (err) throw err;

				assert.deepEqual(_.trim(body), _.trim(sql));
				done();
			});
		}

		// Start server
		tasks.push(function (cb) {
			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom2;

			new amsync.SyncServer(options, cb);
		});

		// Subscribe to happenings on the queue on intercom1
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleMsg, cb);
		});

		// Send the request to the queue
		tasks.push(function (cb) {
			intercom1.send({'action': 'requestDump'}, {'exchange': exchangeName}, cb);
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});

	it('client', function (done) {
		const	exchangeName	= 'test_dataDump_client',
			msgContent	= 'wlüpp!',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			token	= 'fjärtkorv',
			tasks	= [];

		this.slow(500);

		function handleIncMsg(message, ack) {
			ack();

			if (message.action !== 'requestDump') {
				return;
			}

			let	server;

			server = http.createServer(function (req, res) {
				assert.deepEqual(req.headers.token, token);
				res.writeHead(200, {'Content-Type': 'plain/text'});
				res.end(msgContent);
				server.close();
			});
			server.listen(0);
			server.on('error', function (err) {
				throw err;
			});

			server.on('listening', function () {
				const	servedPort	= server.address().port,
					message	= {'action': 'dumpResponse', 'endpoints': []};

				for (const nic of Object.keys(nics)) {
					for (let i = 0; nics[nic][i] !== undefined; i ++) {
						const	nicAddress	= nics[nic][i];

						if (nicAddress.internal === false) {
							message.endpoints.push({
								'family':	nicAddress.family,
								'host':	nicAddress.address,
								'port':	servedPort,
								'token':	token
							});
						}
					}
				}

				intercom1.send(message, {'exchange': exchangeName});
			});
		}

		// Listen to the queue for dump requests
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleIncMsg, cb);
		});

		// Start client
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			new amsync.SyncClient(options, function (err, res) {
				let	syncData	= Buffer.from('');

				if (err) { cb(err); return; }

				res.on('data', function (chunk) {
					syncData	=	Buffer.concat([syncData, chunk], syncData.length + chunk.length);
				});

				res.on('end', function () {
					assert.deepEqual(syncData.toString(), msgContent);
					done();
				});

				res.on('error', cb);
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});

	it('server with port range', function (done) {
		const	exchangeName	= 'test_dataDump_server',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			options	= {'exchange': exchangeName},
			tasks	= [];

		let	msgHandled	= false;

		this.slow(500);

		function handleMsg(message, ack) {
			const	reqOptions	= {};

			ack();

			if (message.action !== 'dumpResponse' || msgHandled !== false) {
				return;
			}

			msgHandled = true;

			assert(message.endpoints, 'message.endpoints must an array with entries');

			if (message.endpoints[0].family === 'IPv6') {
				reqOptions.uri = 'http://[' + message.endpoints[0].host + ']';
			} else {
				reqOptions.uri = 'http://' + message.endpoints[0].host;
			}

			reqOptions.uri	+= ':' + message.endpoints[0].port;

			reqOptions.headers	= {'token': message.endpoints[0].token};

			request(reqOptions, function (err, res, body) {
				if (err) throw err;

				assert.deepEqual(_.trim(body), _.trim(sql));
				done();
			});
		}

		// Start server
		tasks.push(function (cb) {
			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom2;
			options.minPort	= 9000;
			options.maxPort	= 9100;

			new amsync.SyncServer(options, cb);
		});

		// Subscribe to happenings on the queue on intercom1
		tasks.push(function (cb) {
			intercom1.subscribe({'exchange': exchangeName}, handleMsg, cb);
		});

		// Send the request to the queue
		tasks.push(function (cb) {
			intercom1.send({'action': 'requestDump', 'noOfTokens': 1}, {'exchange': exchangeName}, cb);
		});

		async.series(tasks, function (err) {
			if (err) throw err;
		});
	});
});

describe('Database', function () {
	it('should sync MariaDB/MySQL stuff', function (done) {
		const	exchangeName	= 'test_dataDump_mariadb',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			tasks	= [];

		this.slow(500);

		// Start server
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName};

			options.dataDumpCmd = {
				'command':	'echo',
				'args':	[sql]
			};

			options['Content-Type']	= 'application/sql';
			options.intercom	= intercom1;

			new amsync.SyncServer(options, cb);
		});

		// Write sync to db
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			amsync.mariadb(options, cb);
		});

		// Check database
		tasks.push(function (cb) {
			db.query('SELECT * FROM bosse', function (err, rows) {
				if (err) throw err;

				assert.deepEqual(rows.length,	1);
				assert.deepEqual(rows[0].id,	1);
				assert.deepEqual(rows[0].name,	'duh');
				cb();
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;

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

describe('Custom http receiver', function () {
	it('should read path', function (done) {
		const	exchangeName	= 'test_dataDump_custom',
			intercom1	= new Intercom(require(intercomConfigFile)),
			intercom2	= new Intercom(require(intercomConfigFile)),
			tasks	= [];

		this.slow(500);

		// Wait for the intercoms to come online
		tasks.push(function (cb) {intercom1.ready(cb);});
		tasks.push(function (cb) {intercom2.ready(cb);});

		// Start server
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom1};

			let	syncServer;

			syncServer = new amsync.SyncServer(options, cb);

			syncServer.handleHttpReq_original = syncServer.handleHttpReq;

			syncServer.handleHttpReq = function (req, res) {

				// Set custom content type
				res.setHeader('Content-Type', 'text/plain');
				//console.log(req);
				// Run different commands depending on request url
				if (req.url === '/') {
					syncServer.options.dataDumpCmd = {'command': 'echo', 'args': ['-n', 'blergh']};
				} else {
					syncServer.options.dataDumpCmd = {'command': 'echo', 'args': ['-n', req.url]};
				}

				// Run the original request handler
				syncServer.handleHttpReq_original(req, res);
			};
		});

		// Start the client
		tasks.push(function (cb) {
			const	options	= {'exchange': exchangeName, 'intercom': intercom2};

			options.requestOptions	= {'path': '/foobar'};

			new amsync.SyncClient(options, function (err, res) {
				let	syncData	= Buffer.from('');

				if (err) throw err;

				res.on('data', function (chunk) {
					syncData	=	Buffer.concat([syncData, chunk], syncData.length + chunk.length);
				});

				res.on('end', function () {
					assert.deepEqual(syncData.toString(), options.requestOptions.path);
					cb();
				});

				res.on('error', function (err) {
					throw err;
				});
			});
		});

		async.series(tasks, function (err) {
			if (err) throw err;
			done();
		});
	});
});

after(function (done) {
	db.removeAllTables(done);
});
<|endoftext|>


<commit_before>var tutorial_paused = false;
var tutorial_txt = false;
var tutorial_sprite = false;
var prev_player_vel_y = 0;
var tutorial_OK_txt = false;
var tutorial_time = 0;

// Used to prevent pesky bug where camera is in the same location for multiple frames.  Tutorial message should only show once
var prev_idx = -2;
var idx = -1;

demo.tutorial = function(){};
demo.tutorial.prototype = {
    preload: function(){
        // Always include this line
//        loadImages();

        // Change to the correct boss
//        loadCatBoss();

        // Make this equal to the size of the tilemap
        game.world.setBounds(0, 0, 1000, 3600);

        ////////////////////////////////////////////////////
        // possible refactor
        // load in tile map assets
        // This should be customized for each stage
        game.load.tilemap('stage', 'assets/tilemaps/Tutorial/TestMapFitted.json', null, Phaser.Tilemap.TILED_JSON);
        game.load.image('grass_platform', 'assets/tilemaps/Tutorial/grass_platform.png');
        game.load.image('ladder_sprite', 'assets/tilemaps/Tutorial/new_ladder_sprite.png');
        game.load.image('ladder_sprite_top', 'assets/tilemaps/Tutorial/new_ladder_sprite.png');
        ///////////////////////////////////////////////////

    },
    create: function(){
        // Reinitialize vars
        tutorial_paused = false;
        tutorial_txt = false;
        tutorial_sprite = false;
        prev_player_vel_y = 0;
        tutorial_OK_txt = false;
        tutorial_time = 0;

        // Used to prevent pesky bug where camera is in the same location for multiple frames.  Tutorial message should only show once
        prev_idx = -2;
        idx = -1;

        // Stop sounds when starting a state
        game.sound.stopAll();

        // start game at bottom of screen
        game.camera.y = game.world.height;
//        game.camera.y = 1800

        // Add game background
        add_game_bg('bg1')

        ///////////////////////////////////////////
        // Consider refactoring
        // add in the tile map
        map = game.add.tilemap('stage');
        map.addTilesetImage('grass_platform');
        map.addTilesetImage('ladder_sprite');
        map.addTilesetImage('ladder_sprite_top');

        layer1 = map.createLayer('Platforms');
        layer2 = map.createLayer('Ladders');
        layer1.resizeWorld();
        layer2.resizeWorld();
        game.physics.arcade.enable(layer1);
        game.physics.arcade.enable(layer2);

        // set collisions for the tilemaps
        map.setCollisionBetween(1, 3, true, layer1);
        map.setCollisionBetween(4, 5, true, layer2);

        // load in sound
        guitar1 = game.add.audio('guitar');
        // loops guitar music
        guitar1.play('','',0.5,true,true);
        /////////////////////////////////////////////

        // Add chameleon at x,y
        createChameleon(500,game.world.height - 400);
//        createChameleon(550, 1950);

        // Add boss at x,y
//        place_cat_boss(0,0);

        // place fruit
        make_fruit_groups();
        placeFruit(300, 2300, "bluefruit")
        placeFruit(600, 1700,"bluefruit");
        placeFruit(150, 1000, "greenfruit");
        placeFruit(200, 300, "bluefruit");
        placeFruit(150, 350, "greenfruit");
        placeFruit(500, 250, "bluefruit");
        placeFruit(750, 200, "greenfruit");
        placeFruit(950, 200, "purplefruit");
        placeFruit(60, 300, "purplefruit");

        // place enemy
        make_enemy_groups();
        var snake1 = placeSnake(0+25, 1950+50, ["purple"]);
        snake1.mytween = game.add.tween(snake1).to({x:[200+25, 0+25], y:[1950+50,1950+50]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false);

        var bird1 = placeBird(300+25, 700+25,["blue"]);
        // make enemy move
        bird1.mytween = game.add.tween(bird1).to({x:[100+25, 300+25], y:[950+25, 700+25]}, 7000, Phaser.Easing.Linear.None, true, 0, -1, false);
//        // place static enemies
        placeBird(500+25,1650+25,["blue"]);

        bigbird = placeBird(200,200,['purple','green','blue']);
        bigbird.scale.setTo(1,1);
        bigbird.mytween = game.add.tween(bigbird).to({x:[850, 850, 200, 200], y:[300, 200, 300, 200]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false);

        // place moving platforms
        addMovingPlatforms();
        placeMP(150, 2450, 2, 1, 5, 0, 100, 0);
        placeMP(100, 2300, 2, 1, 7, 0, 150, 0);
        placeMP(50, 2150, 2, 1, 9, 0, 200, 0);
//        placeMP(350, 1600, 3, 1, 0, 6, 0, 100);
        placeMP(200, 900, 3, 1, 8, 0, 100, 0);

        // place balloons
        make_balloon_group();
        placeBalloon(50, 900);

        make_healthpack_groups();

        // Inventory should be the last thing added so that it is on top of all other sprites (never hidden)
        createInventory(0, 525);

        // place health hearts *****
        place_hearts(450, 0);

        add_pause_darkener();

    },
    update: function(){
//        console.log(player.body.x, player.body.y);
        // These are the heights at which the game automatically pauses and displays a message
        var stop_heights = [2627, 2626, 2625, 2624, 2623, 2622, 1500, 1499, 1498, 1497, 1496, 1];
//        var stop_heights = [];
        idx = stop_heights.indexOf(game.camera.y);
//        console.log(idx, prev_idx);
        if (idx >= 0 && prev_idx!=idx) {
            disp_tut_msgs(idx);
        }

        // colide with grass and allow player to jump
        game.physics.arcade.collide(player, layer1);

//        if (game.camera.y != 0) {
//            // catboss stays asleep until 3 seconds after camera reaches the top
//            cat_boss.throw_ball_timer = game.time.time + 3000;
//        }
//        var boss_collision_list = [layer1, layer2]
//        cat_boss_move(boss_collision_list);

//        console.log(player.body.x, player.body.y);
        if (!tutorial_paused) {
            // Pause the camera and the player when pausing the game
            move_camera(1,1);

            if (game.camera.y >=12 && player.body.bottom <= 650 && player.body.right-player.body.width >= 725 && player.body.right <= 925){
                // Force the player onto the platform until the boss is fully revealed if the player is on the highest platform
                player.body.velocity.x = 0;
                player.body.velocity.y = 50;
                // If player is frozen, move camera up faster
                move_camera(0,2);

            } else if (player.ballooning){
                chameleon_float();
            } else {
                chameleonmove();
                //      check player position and either call ladder function or take into account ladder top
                var tile_arr = get_surrounding_tiles(layer2, map);
                ladder_movement(tile_arr, 4, 5);
            }

            birds_group.forEach(moveBird, this);
            snakes_group.forEach(moveSnake, this);
            moving_platform_group.forEach(movingPlatformsUpdate, this);

        }

        // player health update
        update_health(player.health);
    }
};
<commit_msg>added colored tiles + collisions to tutorial<commit_after>var tutorial_paused = false;
var tutorial_txt = false;
var tutorial_sprite = false;
var prev_player_vel_y = 0;
var tutorial_OK_txt = false;
var tutorial_time = 0;

// Used to prevent pesky bug where camera is in the same location for multiple frames.  Tutorial message should only show once
var prev_idx = -2;
var idx = -1;

demo.tutorial = function(){};
demo.tutorial.prototype = {
    preload: function(){
        // Always include this line
//        loadImages();

        // Change to the correct boss
//        loadCatBoss();

        // Make this equal to the size of the tilemap
        game.world.setBounds(0, 0, 1000, 3600);

        ////////////////////////////////////////////////////
        // possible refactor
        // load in tile map assets
        // This should be customized for each stage
        game.load.tilemap('stage', 'assets/tilemaps/Tutorial/TestMapFitted.json', null, Phaser.Tilemap.TILED_JSON);
        game.load.image('grass_platform', 'assets/tilemaps/Tutorial/grass_platform.png');
        game.load.image('ladder_sprite', 'assets/tilemaps/Tutorial/new_ladder_sprite.png');
        game.load.image('ladder_sprite_top', 'assets/tilemaps/Tutorial/new_ladder_sprite.png');
        game.load.image('blue_snow', 'assets/tilemaps/IceStage/blue_snow.png');
        ///////////////////////////////////////////////////

    },
    create: function(){
        // Reinitialize vars
        tutorial_paused = false;
        tutorial_txt = false;
        tutorial_sprite = false;
        prev_player_vel_y = 0;
        tutorial_OK_txt = false;
        tutorial_time = 0;

        // Used to prevent pesky bug where camera is in the same location for multiple frames.  Tutorial message should only show once
        prev_idx = -2;
        idx = -1;

        // Stop sounds when starting a state
        game.sound.stopAll();

        // start game at bottom of screen
        game.camera.y = game.world.height;
//        game.camera.y = 1800

        // Add game background
        add_game_bg('bg1')

        ///////////////////////////////////////////
        // Consider refactoring
        // add in the tile map
        map = game.add.tilemap('stage');
        map.addTilesetImage('grass_platform');
        map.addTilesetImage('ladder_sprite');
        map.addTilesetImage('ladder_sprite_top');
        map.addTilesetImage('blue_snow');

        layer1 = map.createLayer('Platforms');
        layer2 = map.createLayer('Ladders');
        layer1.resizeWorld();
        layer2.resizeWorld();
        game.physics.arcade.enable(layer1);
        game.physics.arcade.enable(layer2);

        // set collisions for the tilemaps
        map.setCollisionBetween(1, 3, true, layer1);
        map.setCollisionBetween(4, 5, true, layer2);
        map.setCollisionBetween(6, 8, true, layer1);

        // load in sound
        guitar1 = game.add.audio('guitar');
        // loops guitar music
        guitar1.play('','',0.5,true,true);
        /////////////////////////////////////////////

        // Add chameleon at x,y
        createChameleon(500,game.world.height - 400);
//        createChameleon(550, 1950);

        // Add boss at x,y
//        place_cat_boss(0,0);

        // place fruit
        make_fruit_groups();
        placeFruit(300, 2300, "bluefruit")
        placeFruit(600, 1700,"bluefruit");
        placeFruit(150, 1000, "greenfruit");
        placeFruit(200, 300, "bluefruit");
        placeFruit(150, 350, "greenfruit");
        placeFruit(500, 250, "bluefruit");
        placeFruit(750, 200, "greenfruit");
        placeFruit(950, 200, "purplefruit");
        placeFruit(60, 300, "purplefruit");

        // place enemy
        make_enemy_groups();
        var snake1 = placeSnake(0+25, 1950+50, ["purple"]);
        snake1.mytween = game.add.tween(snake1).to({x:[200+25, 0+25], y:[1950+50,1950+50]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false);

        var bird1 = placeBird(300+25, 700+25,["blue"]);
        // make enemy move
        bird1.mytween = game.add.tween(bird1).to({x:[100+25, 300+25], y:[950+25, 700+25]}, 7000, Phaser.Easing.Linear.None, true, 0, -1, false);
//        // place static enemies
        placeBird(500+25,1650+25,["blue"]);

        bigbird = placeBird(200,200,['purple','green','blue']);
        bigbird.scale.setTo(1,1);
        bigbird.mytween = game.add.tween(bigbird).to({x:[850, 850, 200, 200], y:[300, 200, 300, 200]}, 4000, Phaser.Easing.Linear.None, true, 0, -1, false);

        // place moving platforms
        addMovingPlatforms();
        placeMP(150, 2450, 2, 1, 5, 0, 100, 0);
        placeMP(100, 2300, 2, 1, 7, 0, 150, 0);
        placeMP(50, 2150, 2, 1, 9, 0, 200, 0);
//        placeMP(350, 1600, 3, 1, 0, 6, 0, 100);
        placeMP(200, 900, 3, 1, 8, 0, 100, 0);

        // place balloons
        make_balloon_group();
        placeBalloon(50, 900);

        make_healthpack_groups();

        // Inventory should be the last thing added so that it is on top of all other sprites (never hidden)
        createInventory(0, 525);

        // place health hearts *****
        place_hearts(450, 0);

        add_pause_darkener();

    },
    update: function(){
//        console.log(player.body.x, player.body.y);
        // These are the heights at which the game automatically pauses and displays a message
        var stop_heights = [2627, 2626, 2625, 2624, 2623, 2622, 1500, 1499, 1498, 1497, 1496, 1];
//        var stop_heights = [];
        idx = stop_heights.indexOf(game.camera.y);
//        console.log(idx, prev_idx);
        if (idx >= 0 && prev_idx!=idx) {
            disp_tut_msgs(idx);
        }

        // colide with grass and allow player to jump
        game.physics.arcade.collide(player, layer1);

//        if (game.camera.y != 0) {
//            // catboss stays asleep until 3 seconds after camera reaches the top
//            cat_boss.throw_ball_timer = game.time.time + 3000;
//        }
//        var boss_collision_list = [layer1, layer2]
//        cat_boss_move(boss_collision_list);

//        console.log(player.body.x, player.body.y);
        if (!tutorial_paused) {
            // Pause the camera and the player when pausing the game
            move_camera(1,1);

            if (game.camera.y >=12 && player.body.bottom <= 650 && player.body.right-player.body.width >= 725 && player.body.right <= 925){
                // Force the player onto the platform until the boss is fully revealed if the player is on the highest platform
                player.body.velocity.x = 0;
                player.body.velocity.y = 50;
                // If player is frozen, move camera up faster
                move_camera(0,2);

            } else if (player.ballooning){
                chameleon_float();
            } else {
                chameleonmove();
                //      check player position and either call ladder function or take into account ladder top
                var tile_arr = get_surrounding_tiles(layer2, map);
                ladder_movement(tile_arr, 4, 5);
            }

            tutorial_dictionary = {1:player.color, 2:player.color, 3:player.color, 4:player.color, 5:player.color, 6:"blue", 7:"blue", 8:"blue"};

            var tile_arr7 = get_surrounding_tiles(layer1, map);
            collideIce(tile_arr7, tutorial_dictionary, 1);

            birds_group.forEach(moveBird, this);
            snakes_group.forEach(moveSnake, this);
            moving_platform_group.forEach(movingPlatformsUpdate, this);

        }

        // player health update
        update_health(player.health);
    }
};
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode, isFirefox */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading calendar.ui.js ...');

  var TSCORE = require('tscore');

  require('datetimepicker');
  require('moment');

  function initCalendarUI() {
    $('#dateCalendarInput').click(function() {
      $('#dateTimeCalendar').hide();
      $('#dateTimeRange').hide();
      $('#dateCalendar').show();
    });

    $('#dateTimeInput').click(function() {
      $('#dateTimeCalendar').show();
      $('#dateTimeRange').hide();
      $('#dateCalendar').hide();
    });
    $('#dateTimeRangeInput').click(function() {
      $('#dateTimeCalendar').hide();
      $('#dateTimeRange').show();
      $('#dateCalendar').hide();
    });

    $('.nav-tabs a[href="#dateCalendarTab"]').on('click', function() {
      $('#dateCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: false
      });
      var defaultDateCalendar = "2016-01-01";
      $('#dateCalendar').on('dp.change', function(e) {
        var d;
        var currentDate;
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
        $('#newTagName').val(currentDate);
      });
      $('#dateCalendar').data('DateTimePicker').format('YYYY/MM/DD').defaultDate(defaultDateCalendar).viewMode('days').show();
    });

    $('.nav-tabs a[href="#dateTimeCalendarTab"]').on('click', function() {
      $('#dateTimeCalendar').datetimepicker({
        viewMode: 'days',
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: false
      });
      var defaultDateCalendar = "1990-01-01";
      $('#dateTimeCalendar').on('dp.change', function(e) {
        var currentDate;
        var d = e.date._d;
        var getHours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
        var getMinutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
        //var getSeconds = d.getSeconds();

        var time = getHours + '' + getMinutes + '' + '00';
        currentDate = TSCORE.Utils.parseDate(d);
        var dateDivider;
        dateDivider = '~';
        currentDate = currentDate + dateDivider + time;

        $('#newTagName').val(currentDate);
      });
      $('#dateTimeCalendar').data('DateTimePicker').format('YYYY/MM/DD').defaultDate(defaultDateCalendar).viewMode('days').show();
    });

    $('.nav-tabs a[href="#dateRangeTab"]').on('click', function() {
      var defaultDateCalendarFrom = "2016-01-01";
      var defaultDateCalendarTo = "2016-01-01";

      $('#dateTimeRangeCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        //extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: false
      });

      $('#dateTimeRangeCalendar').on('dp.change', function(e) {
        var d = e.date._d;
        var currentMinDate = TSCORE.Utils.parseDate(d);
        var oldValue = $('#newTagName').val();
        oldValue = oldValue.split('-');
        oldValue = oldValue[1];
        $('#newTagName').val(currentMinDate + "-" + oldValue);
      });

      $('#dateTimeRangeCalendar').data('DateTimePicker').defaultDate(defaultDateCalendarFrom).viewMode('days').show();

      $('#dateTimeRangeMaxCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        //extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: false
      });

      $('#dateTimeRangeMaxCalendar').on('dp.change', function(e) {
        var d = e.date._d;
        var currentMaxDate = TSCORE.Utils.parseDate(d);

        var oldValue = $('#newTagName').val();
        oldValue = oldValue.split('-');
        oldValue = oldValue[0];
        $('#newTagName').val(oldValue + "-" + currentMaxDate);
      });

      $('#dateTimeRangeMaxCalendar').data('DateTimePicker').defaultDate(defaultDateCalendarTo).viewMode('days').show();
    });
  }

  function dateCalendarTag(currentDateTime) {
    var defaultDateCalendar = TSCORE.Utils.parseToDate(currentDateTime);
    var viewMode = '', format = '';

    if (defaultDateCalendar.toString().length === 7 || defaultDateCalendar.length === 7) {
      viewMode = 'months';
      format = 'YYYY/MM';
    } else if (defaultDateCalendar.toString().length === 4) {
      viewMode = 'years';
      format = 'YYYY';
    } else if (defaultDateCalendar.toString().length === 10) {
      viewMode = 'days';
      format = 'YYYY/MM/DD';
    } else {
      viewMode = 'days';
      format = 'YYYY/MM/DD';
    }

    $('#dateCalendar').datetimepicker({
      //extraFormats: ['YYYY-MM-DD', 'YYYY-MM'],
      format: 'YYYY/MM/DD',
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateCalendar').on('dp.change', function(e) {
      var d;
      var currentDate;
      if (viewMode === 'years') {
        d = e.date._d;
        currentDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'default' || viewMode === 'days') {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
      } else {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
      }
      $('#newTagName').val(currentDate);
    });
    $('#dateCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(defaultDateCalendar).viewMode(viewMode).toggle().show();
  }

  function showDateTimeCalendar(currentDateTime) {
    $('#dateTimeCalendar').datetimepicker({
      inline: true,
      sideBySide: true,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true,
      extraFormats: ['YYYY-MM-DD HH:mm:ss', 'HH:mm:ss', 'HH:mm']
    });

    var defaultDate = TSCORE.Utils.convertToDateTime(currentDateTime);
    $('#dateTimeCalendar').on('dp.change', function(e) {
      var currentDate;
      var d = e.date._d;
      var getHours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
      var getMinutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
      //var getSeconds = d.getSeconds();

      var time = getHours + '' + getMinutes + '' + '00';
      currentDate = TSCORE.Utils.parseDate(d);
      var dateDivider;
      var dateTag = TSCORE.selectedTag;
      if (dateTag.length !== 5) {
        if (dateTag.indexOf('~') !== -1) {
          dateDivider = '~';
          currentDate = currentDate + dateDivider + time;
        }
        if (dateTag.indexOf(':') !== -1 && dateTag.length !== 5) {
          dateDivider = ':';
          currentDate = currentDate + dateDivider + time;
        }
        if (dateTag.indexOf('!') !== -1 && dateTag.length !== 5) {
          dateDivider = '!';
          currentDate = currentDate + dateDivider + time;
        }
      } else {
        if (dateTag.indexOf('~')) {
          dateDivider = '~';
          currentDate = getHours + dateDivider + getMinutes;
        }
        if (dateTag.indexOf(':')) {
          dateDivider = ':';
          currentDate = getHours + dateDivider + getMinutes;
        }
        if (dateTag.indexOf('!')) {
          dateDivider = '!';
          currentDate = getHours + dateDivider + getMinutes;
        }
      }
      $('#newTagName').val(currentDate);
    });

    $('#dateTimeCalendar').data('DateTimePicker').format('YYYY-MM-DD HH:mm:ss').useCurrent(true).defaultDate(defaultDate).toggle().show();
  }

  function dateRangeCalendar(currentDateTime) {
    var range = TSCORE.Utils.convertToDateRange(currentDateTime);
    console.log(range);
    var viewMode = '', format = '';
    if ((range[0].toString().length === 6 || range[0].length === 6) &&
      (range[1].toString().length === 6 || range[1].length === 6)) {
      viewMode = 'months';
      format = 'YYYY-MM';
    } else if (range[0].toString().length === 4 &&
      range[1].toString().length === 4) {
      viewMode = 'years';
      format = 'YYYY';
    } else {
      viewMode = 'days';
      format = 'YYYY-MM-DD';
    }

    $('#dateTimeRangeCalendar').datetimepicker({
      extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateTimeRangeCalendar').on('dp.change', function(e) {
      var currentMinDate;
      var d;
      if (viewMode === 'years') {
        d = e.date._d;
        currentMinDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentMinDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'days') {
        d = e.date._d;
        currentMinDate = TSCORE.Utils.parseDate(d);
      }
      var oldValue = $('#newTagName').val();
      oldValue = oldValue.split('-');
      oldValue = oldValue[1];
      $('#newTagName').val(currentMinDate + "-" + oldValue);
    });

    $('#dateTimeRangeCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(TSCORE.Utils.convertToDate(range[0])).viewMode(viewMode).toggle().show();

    $('#dateTimeRangeMaxCalendar').datetimepicker({
      extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateTimeRangeMaxCalendar').on('dp.change', function(e) {
      var d;
      var currentMaxDate;
      if (viewMode === 'years') {
        d = e.date._d;
        currentMaxDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentMaxDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'days') {
        d = e.date._d;
        currentMaxDate = TSCORE.Utils.parseDate(d);
      }
      var oldValue = $('#newTagName').val();
      oldValue = oldValue.split('-');
      oldValue = oldValue[0];
      $('#newTagName').val(oldValue + "-" + currentMaxDate);
    });

    $('#dateTimeRangeMaxCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(TSCORE.Utils.convertToDate(range[1])).viewMode(viewMode).toggle().show();
  }

  function tagRecognition(dataTag) {
    var geoLocationRegExp = /^([-+]?)([\d]{1,2})(((\.)(\d+)(,)))(\s*)(([-+]?)([\d]{1,3})((\.)(\d+))?)$/g;

    var dateTimeRegExp = /^\d\d\d\d-(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/g;
    var dateTimeWinRegExp = /^(([0-1]?[0-9])|([2][0-3]))!([0-5]?[0-9])(!([0-5]?[0-9]))?$/g;
    var dateRangeRegExp = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[-]([0]?[1-9]|[1][0-2])$/g;
    var geoTag = 'geo-tag';
    var currentCoordinate;
    var currentDateTime = dataTag;

    var year = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 4;
    var month = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 6;
    var date = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 8;

    var convertToDateTime = TSCORE.Utils.convertToDateTime(currentDateTime);

    var yearRange, monthRange, dateRange;

    if (dataTag.lastIndexOf('+') !== -1) {
      currentCoordinate = TSCORE.Utils.splitValue(dataTag, dataTag.lastIndexOf('+'));
    } else if (dataTag.lastIndexOf('-') !== -1) {
      currentCoordinate = TSCORE.Utils.splitValue(dataTag, dataTag.lastIndexOf('-'));

      var character = currentDateTime.split("-");
      if (!currentCoordinate.search(".") && character) {
        var firstInt = parseInt(character[0]);
        var secondInt = parseInt(character[1]);
        yearRange = monthRange = dateRange =
          typeof firstInt === 'number' && !isNaN(firstInt) &&
          typeof secondInt === 'number' && !isNaN(secondInt);
      }
    }

    var dateRegExp = yearRange || monthRange || dateRange ||
      currentDateTime.match(dateTimeRegExp) ||
      currentDateTime.match(dateTimeWinRegExp) ||
      year || month || date || convertToDateTime;

    if (geoLocationRegExp.exec(currentCoordinate) || geoTag === dataTag) {
      if (TSCORE.PRO) {
        $('.nav-tabs a[href="#geoLocation"]').tab('show');
      } else {
        $('.nav-tabs a[href="#formEditTag"]').tab('show');
      }
    } else if (dateRegExp) {

      var dateTab = year || month || date;
      var dateTimeTab = currentDateTime.match(dateTimeRegExp) ||
        currentDateTime.match(dateTimeWinRegExp) || convertToDateTime;
      var dateRangeTab = currentDateTime.match(dateRangeRegExp) ||
        yearRange || monthRange || dateRange;

      if (dateTab) {
        $('.nav-tabs a[href="#dateCalendarTab"]').tab('show');
        //$('#dateCalendarInput').prop('checked', true);
        //if (document.getElementById('dateCalendarInput').checked) {
        TSCORE.Calendar.dateCalendarTag(currentDateTime);
      } else if (dateTimeTab) {
        $('.nav-tabs a[href="#dateTimeCalendarTab"]').tab('show');
        //$('#dateTimeInput').prop('checked', true);
        //if (document.getElementById('dateTimeInput').checked) {
        TSCORE.Calendar.showDateTimeCalendar(currentDateTime);
      } else if (dateRangeTab) {
        $('.nav-tabs a[href="#dateRangeTab"]').tab('show');
        //$('#dateTimeRangeInput').prop('checked', true);
        //if (document.getElementById('dateTimeRangeInput').checked) {
        TSCORE.Calendar.dateRangeCalendar(currentDateTime);
      }
    } else if (!(dateRegExp && geoLocationRegExp.exec(currentCoordinate))) {
      $('.nav-tabs a[href="#formEditTag"]').tab('show');
    } else {
      throw new TypeError("Invalid data.");
    }
  }

  // Public API definition
  exports.initCalendarUI = initCalendarUI;
  exports.dateCalendarTag = dateCalendarTag;
  exports.showDateTimeCalendar = showDateTimeCalendar;
  exports.dateRangeCalendar = dateRangeCalendar;
  exports.tagRecognition = tagRecognition;
});<commit_msg>refactoring<commit_after>/* Copyright (c) 2012-2016 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */

/* global define, Handlebars, isNode, isFirefox */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading calendar.ui.js ...');

  var TSCORE = require('tscore');

  require('datetimepicker');
  require('moment');

  function initCalendarUI() {
    $('#dateCalendarInput').click(function() {
      $('#dateTimeCalendar').hide();
      $('#dateTimeRange').hide();
      $('#dateCalendar').show();
    });

    $('#dateTimeInput').click(function() {
      $('#dateTimeCalendar').show();
      $('#dateTimeRange').hide();
      $('#dateCalendar').hide();
    });
    $('#dateTimeRangeInput').click(function() {
      $('#dateTimeCalendar').hide();
      $('#dateTimeRange').show();
      $('#dateCalendar').hide();
    });

    $('.nav-tabs a[href="#dateCalendarTab"]').on('click', function() {
      $('#dateCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: true
      });
      var defaultDateCalendar = "2016-01-01";
      $('#dateCalendar').on('dp.change', function(e) {
        var d;
        var currentDate;
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
        $('#newTagName').val(currentDate);
      });
      $('#dateCalendar').data('DateTimePicker').format('YYYY/MM/DD').defaultDate(defaultDateCalendar).viewMode('days').toggle().show();
    });

    $('.nav-tabs a[href="#dateTimeCalendarTab"]').on('click', function() {
      $('#dateTimeCalendar').datetimepicker({
        viewMode: 'days',
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: true
      });
      var defaultDateCalendar = "1990-01-01";
      $('#dateTimeCalendar').on('dp.change', function(e) {
        var currentDate;
        var d = e.date._d;
        var getHours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
        var getMinutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
        //var getSeconds = d.getSeconds();

        var time = getHours + '' + getMinutes + '' + '00';
        currentDate = TSCORE.Utils.parseDate(d);
        var dateDivider;
        dateDivider = '~';
        currentDate = currentDate + dateDivider + time;

        $('#newTagName').val(currentDate);
      });
      $('#dateTimeCalendar').data('DateTimePicker').format('YYYY/MM/DD').defaultDate(defaultDateCalendar).viewMode('days').toggle().show();
    });

    $('.nav-tabs a[href="#dateRangeTab"]').on('click', function() {
      var defaultDateCalendarFrom = "2016-01-01";
      var defaultDateCalendarTo = "2016-01-01";

      $('#dateTimeRangeCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        //extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: true
      });

      $('#dateTimeRangeCalendar').on('dp.change', function(e) {
        var d = e.date._d;
        var currentMinDate = TSCORE.Utils.parseDate(d);
        var oldValue = $('#newTagName').val();
        oldValue = oldValue.split('-');
        oldValue = oldValue[1];
        $('#newTagName').val(currentMinDate + "-" + oldValue);
      });

      $('#dateTimeRangeCalendar').data('DateTimePicker').defaultDate(defaultDateCalendarFrom).viewMode('days').toggle().show();

      $('#dateTimeRangeMaxCalendar').datetimepicker({
        viewMode: 'days',
        format: 'YYYY/MM/DD',
        //extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
        inline: true,
        sideBySide: false,
        calendarWeeks: true,
        showTodayButton: true,
        allowInputToggle: true,
        useCurrent: true
      });

      $('#dateTimeRangeMaxCalendar').on('dp.change', function(e) {
        var d = e.date._d;
        var currentMaxDate = TSCORE.Utils.parseDate(d);

        var oldValue = $('#newTagName').val();
        oldValue = oldValue.split('-');
        oldValue = oldValue[0];
        $('#newTagName').val(oldValue + "-" + currentMaxDate);
      });

      $('#dateTimeRangeMaxCalendar').data('DateTimePicker').defaultDate(defaultDateCalendarTo).viewMode('days').toggle().show();
    });
  }

  function dateCalendarTag(currentDateTime) {
    var defaultDateCalendar = TSCORE.Utils.parseToDate(currentDateTime);
    var viewMode = '', format = '';

    if (defaultDateCalendar.toString().length === 7 || defaultDateCalendar.length === 7) {
      viewMode = 'months';
      format = 'YYYY/MM';
    } else if (defaultDateCalendar.toString().length === 4) {
      viewMode = 'years';
      format = 'YYYY';
    } else if (defaultDateCalendar.toString().length === 10) {
      viewMode = 'days';
      format = 'YYYY/MM/DD';
    } else {
      viewMode = 'days';
      format = 'YYYY/MM/DD';
    }

    $('#dateCalendar').datetimepicker({
      //extraFormats: ['YYYY-MM-DD', 'YYYY-MM'],
      format: 'YYYY/MM/DD',
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateCalendar').on('dp.change', function(e) {
      var d;
      var currentDate;
      if (viewMode === 'years') {
        d = e.date._d;
        currentDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'default' || viewMode === 'days') {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
      } else {
        d = e.date._d;
        currentDate = TSCORE.Utils.parseDate(d);
      }
      $('#newTagName').val(currentDate);
    });
    $('#dateCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(defaultDateCalendar).viewMode(viewMode).toggle().show();
  }

  function showDateTimeCalendar(currentDateTime) {
    $('#dateTimeCalendar').datetimepicker({
      inline: true,
      sideBySide: true,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true,
      extraFormats: ['YYYY-MM-DD HH:mm:ss', 'HH:mm:ss', 'HH:mm']
    });

    var defaultDate = TSCORE.Utils.convertToDateTime(currentDateTime);
    $('#dateTimeCalendar').on('dp.change', function(e) {
      var currentDate;
      var d = e.date._d;
      var getHours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
      var getMinutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
      //var getSeconds = d.getSeconds();

      var time = getHours + '' + getMinutes + '' + '00';
      currentDate = TSCORE.Utils.parseDate(d);
      var dateDivider;
      var dateTag = TSCORE.selectedTag;
      if (dateTag.length !== 5) {
        if (dateTag.indexOf('~') !== -1) {
          dateDivider = '~';
          currentDate = currentDate + dateDivider + time;
        }
        if (dateTag.indexOf(':') !== -1 && dateTag.length !== 5) {
          dateDivider = ':';
          currentDate = currentDate + dateDivider + time;
        }
        if (dateTag.indexOf('!') !== -1 && dateTag.length !== 5) {
          dateDivider = '!';
          currentDate = currentDate + dateDivider + time;
        }
      } else {
        if (dateTag.indexOf('~')) {
          dateDivider = '~';
          currentDate = getHours + dateDivider + getMinutes;
        }
        if (dateTag.indexOf(':')) {
          dateDivider = ':';
          currentDate = getHours + dateDivider + getMinutes;
        }
        if (dateTag.indexOf('!')) {
          dateDivider = '!';
          currentDate = getHours + dateDivider + getMinutes;
        }
      }
      $('#newTagName').val(currentDate);
    });

    $('#dateTimeCalendar').data('DateTimePicker').format('YYYY-MM-DD HH:mm:ss').useCurrent(true).defaultDate(defaultDate).toggle().show();
  }

  function dateRangeCalendar(currentDateTime) {
    var range = TSCORE.Utils.convertToDateRange(currentDateTime);
    console.log(range);
    var viewMode = '', format = '';
    if ((range[0].toString().length === 6 || range[0].length === 6) &&
      (range[1].toString().length === 6 || range[1].length === 6)) {
      viewMode = 'months';
      format = 'YYYY-MM';
    } else if (range[0].toString().length === 4 &&
      range[1].toString().length === 4) {
      viewMode = 'years';
      format = 'YYYY';
    } else {
      viewMode = 'days';
      format = 'YYYY-MM-DD';
    }

    $('#dateTimeRangeCalendar').datetimepicker({
      extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateTimeRangeCalendar').on('dp.change', function(e) {
      var currentMinDate;
      var d;
      if (viewMode === 'years') {
        d = e.date._d;
        currentMinDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentMinDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'days') {
        d = e.date._d;
        currentMinDate = TSCORE.Utils.parseDate(d);
      }
      var oldValue = $('#newTagName').val();
      oldValue = oldValue.split('-');
      oldValue = oldValue[1];
      $('#newTagName').val(currentMinDate + "-" + oldValue);
    });

    $('#dateTimeRangeCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(TSCORE.Utils.convertToDate(range[0])).viewMode(viewMode).toggle().show();

    $('#dateTimeRangeMaxCalendar').datetimepicker({
      extraFormats: ['YYYY-MM-DD', 'YYYY-MM', 'YYYY-MM-DDTHH:MM:SS', 'YYYY-MM-DDTHH:MM', 'YYYY-MM-DD HH:mm:ss'],
      inline: true,
      sideBySide: false,
      calendarWeeks: true,
      showTodayButton: true,
      allowInputToggle: true,
      useCurrent: true
    });

    $('#dateTimeRangeMaxCalendar').on('dp.change', function(e) {
      var d;
      var currentMaxDate;
      if (viewMode === 'years') {
        d = e.date._d;
        currentMaxDate = d.getFullYear();
      } else if (viewMode === 'months') {
        d = e.date._d;
        currentMaxDate = TSCORE.Utils.parseDateMonth(d);
      } else if (viewMode === 'days') {
        d = e.date._d;
        currentMaxDate = TSCORE.Utils.parseDate(d);
      }
      var oldValue = $('#newTagName').val();
      oldValue = oldValue.split('-');
      oldValue = oldValue[0];
      $('#newTagName').val(oldValue + "-" + currentMaxDate);
    });

    $('#dateTimeRangeMaxCalendar').data('DateTimePicker').format(format).useCurrent(true).defaultDate(TSCORE.Utils.convertToDate(range[1])).viewMode(viewMode).toggle().show();
  }

  function tagRecognition(dataTag) {
    var geoLocationRegExp = /^([-+]?)([\d]{1,2})(((\.)(\d+)(,)))(\s*)(([-+]?)([\d]{1,3})((\.)(\d+))?)$/g;

    var dateTimeRegExp = /^\d\d\d\d-(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/g;
    var dateTimeWinRegExp = /^(([0-1]?[0-9])|([2][0-3]))!([0-5]?[0-9])(!([0-5]?[0-9]))?$/g;
    var dateRangeRegExp = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[-]([0]?[1-9]|[1][0-2])$/g;
    var geoTag = 'geo-tag';
    var currentCoordinate;
    var currentDateTime = dataTag;

    var year = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 4;
    var month = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 6;
    var date = parseInt(currentDateTime) && !isNaN(currentDateTime) &&
      currentDateTime.length === 8;

    var convertToDateTime = TSCORE.Utils.convertToDateTime(currentDateTime);

    var yearRange, monthRange, dateRange;

    if (dataTag.lastIndexOf('+') !== -1) {
      currentCoordinate = TSCORE.Utils.splitValue(dataTag, dataTag.lastIndexOf('+'));
    } else if (dataTag.lastIndexOf('-') !== -1) {
      currentCoordinate = TSCORE.Utils.splitValue(dataTag, dataTag.lastIndexOf('-'));

      var character = currentDateTime.split("-");
      if (!currentCoordinate.search(".") && character) {
        var firstInt = parseInt(character[0]);
        var secondInt = parseInt(character[1]);
        yearRange = monthRange = dateRange =
          typeof firstInt === 'number' && !isNaN(firstInt) &&
          typeof secondInt === 'number' && !isNaN(secondInt);
      }
    }

    var dateRegExp = yearRange || monthRange || dateRange ||
      currentDateTime.match(dateTimeRegExp) ||
      currentDateTime.match(dateTimeWinRegExp) ||
      year || month || date || convertToDateTime;

    if (geoLocationRegExp.exec(currentCoordinate) || geoTag === dataTag) {
      if (TSCORE.PRO) {
        $('.nav-tabs a[href="#geoLocation"]').tab('show');
      } else {
        $('.nav-tabs a[href="#plainEditorTab"]').tab('show');
      }
    } else if (dateRegExp) {
      console.log("DATAAAAAAAAAAAAAAA")

      var dateTab = year || month || date;
      var dateTimeTab = currentDateTime.match(dateTimeRegExp) ||
        currentDateTime.match(dateTimeWinRegExp) || convertToDateTime;
      var dateRangeTab = currentDateTime.match(dateRangeRegExp) ||
        yearRange || monthRange || dateRange;

      if (dateTab) {
        $('.nav-tabs a[href="#dateCalendarTab"]').tab('show');
        //$('#dateCalendarInput').prop('checked', true);
        //if (document.getElementById('dateCalendarInput').checked) {
        TSCORE.Calendar.dateCalendarTag(currentDateTime);
      } else if (dateTimeTab) {
        $('.nav-tabs a[href="#dateTimeCalendarTab"]').tab('show');
        //$('#dateTimeInput').prop('checked', true);
        //if (document.getElementById('dateTimeInput').checked) {
        TSCORE.Calendar.showDateTimeCalendar(currentDateTime);
      } else if (dateRangeTab) {
        $('.nav-tabs a[href="#dateRangeTab"]').tab('show');
        //$('#dateTimeRangeInput').prop('checked', true);
        //if (document.getElementById('dateTimeRangeInput').checked) {
        TSCORE.Calendar.dateRangeCalendar(currentDateTime);
      }
    } else if (!(dateRegExp && geoLocationRegExp.exec(currentCoordinate))) {
      $('.nav-tabs a[href="#plainEditorTab"]').tab('show');
    } else {
      throw new TypeError("Invalid data.");
    }
  }

  // Public API definition
  exports.initCalendarUI = initCalendarUI;
  exports.dateCalendarTag = dateCalendarTag;
  exports.showDateTimeCalendar = showDateTimeCalendar;
  exports.dateRangeCalendar = dateRangeCalendar;
  exports.tagRecognition = tagRecognition;
});<|endoftext|>


<commit_before>define(["sprd/entity/DesignConfigurationBase", "sprd/entity/Size", "sprd/entity/Font", "sprd/util/ProductUtil", "sprd/entity/BlobImage", "sprd/data/IImageUploadService", "flow", "underscore", "sprd/util/ArrayUtil", "sprd/extensions/CanvasToBlob", "xaml!sprd/data/DesignerApiDataSource", "sprd/model/Transformer", "sprd/model/AbstractShop", "sprd/entity/TextConfiguration", "xaml!sprd/view/svg/BendingTextConfigurationUploadRenderer"],
    function(DesignConfigurationBase, Size, Font, ProductUtil, BlobImage, IImageUploadService, flow, _, ArrayUtil, CanvasToBlob, DesignerApiDataSource, Transformer, Shop, TextConfiguration, BendingTextConfigurationUploadRenderer) {
        var PATH_TYPE = {
            OUTER_CIRCLE: "outer_circle",
            INNER_CIRCLE: "inner_circle",
            HEART: "heart"
        };

        var designCache = {},
            copyrightWordList = TextConfiguration.getCopyrightWordList();

        return DesignConfigurationBase.inherit('sprd.model.BendingTextConfiguration', {

            defaults: {
                fontSize: 16,

                _size: Size,
                aspectRatio: 1,
                _allowScale: true,
                loading: false,
                initialized: false,
                isNew: false,
                isTemplate: false,

                angle: 50,
                path: PATH_TYPE.OUTER_CIRCLE,
                textPath: "{textPath()}",
                dy: "{dy()}",

                textPathOffsetX: 0,
                textPathOffsetY: 0,
                transformer: null,
                copyrightWordList: null,
                initialText: null
            },

            type: "bendingText",
            representationType: "text",

            $events: [
                "recalculateSize"
            ],

            inject: {
                imageUploadService: IImageUploadService,
                designerApi: DesignerApiDataSource,
                context: "context"
            },

            ctor: function() {
                this.callBase();

                copyrightWordList.bind("add", function() {
                    this._validateText();
                }, this);

                this.$synchronizeCache = designCache;
            },

            textChangedSinceCreation: function () {
                var initialText = this.$.initialText,
                    currentText = this.$.text;

                if (!initialText) {
                    return true;
                }

                return initialText !== currentText;
            },

            isOnlyWhiteSpace: function () {
                var text = this.$.text;
                if (!text) {
                    return true;
                }

                return /^[\s\n\r]*$/.test(text);
            },

            init: function(options, callback) {
                var properties = this.$.properties,
                    context = this.$.context,
                    self = this;
                options = options || {};

                this.initTransformer();
                if (!_.isEmpty(properties)) {

                    if (this.$.initialized) {
                        callback && callback();
                    }

                    flow()
                        .seq(function(cb) {
                            options = _.clone(options);
                            options.noDesignFetch = true;

                            DesignConfigurationBase.prototype.init.call(self, options, cb);
                        })
                        .seq(function(cb) {
                            var fontFamilies = context.$.fontFamilies;
                            if (fontFamilies.size()) {
                                cb();
                            } else {
                                fontFamilies.fetch({fullData: true}, cb);
                            }
                        })
                        .seq("fontFamily", function() {
                            var fontFamilyId = properties.fontFamilyId;
                            if (fontFamilyId) {
                                var items = context.$.fontFamilies.$items;

                                for (var i = items.length; i--;) {
                                    if (items[i].$.id == properties.fontFamilyId) {
                                        return items[i];
                                    }
                                }
                            }
                        })
                        .seq(function() {
                            var printType = self.$.printType;
                            if (printType && properties.fill) {
                                self.setColor(null, printType.getClosestPrintColor(properties.fill))
                            }
                        })
                        .seq(function() {
                            if (properties.text) {

                                var fontFamily = this.vars.fontFamily,
                                    fontWeight = properties.fontWeight,
                                    fontStyle = properties.fontStyle;

                                var scale = {
                                    x: properties.scale,
                                    y: properties.scale
                                };

                                var size = new Size({
                                    width: (properties.size && properties.size.width) || 0,
                                    height: (properties.size && properties.size.height) || 0
                                });

                                self.set({
                                    text: properties.text,
                                    angle: properties.angle || 50,
                                    path: properties.path || PATH_TYPE.OUTER_CIRCLE,
                                    font: fontFamily.getFont(fontWeight, fontStyle),
                                    fontSize: properties.fontSize || 16,
                                    _size: size,
                                    scale: scale
                                })
                            }
                        })
                        .exec(function(err) {
                            self.set("initialized", true);
                            callback && callback(err);
                        });
                } else {
                    callback && callback();
                }

            },

            _commitText: function() {
                this._validateText();
            },

            initTransformer: function() {
                var shop = this.$.designerApi.createEntity(Shop, this.$.context.$.id);
                this.set('transformer', shop.createEntity(Transformer));
            },

            size: function() {
                return this.$._size || Size.empty;
            }.onChange("_size").on("sizeChanged"),

            compose: function() {
                var ret = this.callBase();
                var font = this.$.font;
                ret.properties.type = "bendingText";
                ret.properties.text = this.$.text;
                ret.properties.angle = this.$.angle;
                ret.properties.fontFamilyId = font.getFontFamily().$.id;
                ret.properties.fontWeight = font.$.weight;
                ret.properties.fontStyle = font.$.style;
                ret.properties.fontSize = this.$.fontSize;
                if (!this.$.printColors.isEmpty()) {
                    ret.properties.fill = this.$.printColors.at(0).toHexString();
                }
                ret.properties.path = this.$.path;
                ret.properties.scale = this.$.scale.x;
                ret.properties.size = this.$._size.$;

                return ret;
            },

            _initializeBindingsBeforeComplete: function() {
                this.callBase();

                var recalculateSize = function() {
                    var self = this;
                    self.trigger("recalculateSize", self);
                    this.trigger('configurationChanged');
                };

                this.bind("change:text", recalculateSize, this);
                this.bind("change:angle", recalculateSize, this);
                this.bind("change:font", recalculateSize, this);
                this.bind("change:fontSize", recalculateSize, this);

                this.bind("change:printColors", function() {
                    this.trigger('configurationChanged');
                }, this)
            },

            _validatePrintTypeSize: function(printType, width, height, scale) {
                var ret = this.callBase();

                if (!printType || !scale) {
                    return ret;
                }

                ret.minBound = this._isScaleTooSmall(printType, scale);

                return ret;
            },

            _isScaleTooSmall: function(printType, scale) {
                var font = this.$.font,
                    fontSize = this.$.fontSize;

                if (printType.isShrinkable()) {
                    return false;
                }

                if (font && fontSize) {
                    return Math.min(Math.abs(scale.x), Math.abs(scale.y)) < font.$.minimalSize / fontSize;
                }

                return false;
            },

            textPath: function() {
                var a = this.$.angle;

                this.set("path", PATH_TYPE.OUTER_CIRCLE);
                if (a < 0) {
                    a = -a;

                    return "M 0, 0 m oneTime, twoTime a oneTime, oneTime 0 1, 0 0, twoTime a oneTime, oneTime 0 1, 0 0, -twoTime"
                        .replace(/oneTime/g, "" + a)
                        .replace(/twoTime/g, "" + (2 * a));

                } else {
                    return "M 0, 0 m oneTime, 0 a oneTime, oneTime 0 1, 1 0, -twoTime a oneTime, oneTime 0 1, 1 0, twoTime"
                        .replace(/oneTime/g, "" + a)
                        .replace(/twoTime/g, "" + (2 * a));
                }

            }.on("recalculateSize"),

            dy: function() {
                return this.$.angle < 0 ? 16 : 0;
            }.onChange("angle"),

            getPossiblePrintTypes: function(appearance) {
                var ret = [],
                    tmp,
                    printArea = this.$.printArea,
                    font = this.$.font;

                if (!printArea || !font) {
                    return ret;
                }

                tmp = this.getPossiblePrintTypesForPrintArea(printArea, appearance);
                _.each(tmp, function(element) {
                    if (ret.indexOf(element) === -1) {
                        ret.push(element);
                    }
                });

                return ret;
            }.onChange("printArea", "font"),

            setColor: function(layerIndex, color) {
                var printColors = this.$.printColors;
                if (printColors && color) {
                    printColors.reset([color]);
                }
            },

            getPossiblePrintTypesForPrintArea: function(printArea, appearance) {
                var fontFamily = this.$.font.getFontFamily(),
                    text = this.$.text;

                if (text) {
                    var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForTextOnPrintArea(fontFamily, printArea, appearance),
                        digitalPrintTypes = _.filter(possiblePrintTypes, function(printType) {
                            return !printType.isPrintColorColorSpace();
                        });
                    return ArrayUtil.moveToStart(possiblePrintTypes, digitalPrintTypes);
                }
            },

            save: function(callback) {
                var self = this,
                    digitalPrint = !this.$.printType.isPrintColorColorSpace();

                var cacheId = [self.$.angle, self.$.text, self.$.font.$.id, self.$.fontSize, self.$.printType.$.id];
                var fill = self.$.printColors.at(0).toHexString();

                if (digitalPrint) {
                    cacheId.push(fill);
                }

                cacheId = cacheId.join("-");

                this.synchronizeFunctionCall(function(callback) {

                    flow()
                        .seq('design', function(cb) {
                            self.transformTextPath(cb);
                        })
                        .exec(function(err, results) {
                            callback(err, results.design);
                        });

                }, cacheId, function(err, design) {
                    self.set('design', design);
                    callback(err);
                }, this);

            },

            getPrintColor: function() {
                var configuration = this,
                    printColors = configuration.$.printColors,
                    printColor = null;

                if (printColors && printColors.size()) {
                    printColor = printColors.at(0).toHexString();
                }

                return printColor;
            }.on("printColors"),

            transformTextPath: function(callback) {
                var self = this;
                try {
                    var uploadRenderer = this.$stage.createComponent(BendingTextConfigurationUploadRenderer, {
                        configuration: this
                    });
                    this.$stage.addChild(uploadRenderer);
                    var svgContent = uploadRenderer.getElementAsString();
                } catch (e) {
                    callback(e, null);
                } finally {
                    this.$stage.removeChild(uploadRenderer);
                }

                var transformer = this.$.transformer;

                transformer.set('content', svgContent);
                transformer.save(null, function(err, transformer) {
                    if (err) {
                        return callback(err, transformer);
                    }

                    var upload = transformer.get("content");

                    var designId = (upload.designId || "").replace(/^u?/, "u"),
                        design = self.$.context.getCollection("designs").createItem(designId);

                    design.fetch(function(err) {
                        callback(err, design);
                    });
                })
            },

            saveTakesTime: function() {
                return true;
            },

            isAllowedOnPrintArea: function(printArea) {
                return printArea && printArea.get("restrictions.textAllowed") == true;
            },

            _additionalValidation: function($, options) {
                if (this._hasSome($, ["angle", "text", "fontSize"])) {
                    return {
                        angle: $.angle,
                        text: $.text,
                        validateHardBoundary: true
                    };
                }

            },

            _validateText: function() {
                var text = (this.$.text || "").toLowerCase(),
                    badWord;

                if (text.length > 1) {
                    // check that we don't contain copyright content
                    if (copyrightWordList && copyrightWordList.size()) {
                        badWord = copyrightWordList.find(function(word) {
                            return text.indexOf(word.toLowerCase()) !== -1;
                        });

                        this._setError("copyright", badWord);
                    }
                }
            }
        });
    });
<commit_msg>Fixed double callback call<commit_after>define(["sprd/entity/DesignConfigurationBase", "sprd/entity/Size", "sprd/entity/Font", "sprd/util/ProductUtil", "sprd/entity/BlobImage", "sprd/data/IImageUploadService", "flow", "underscore", "sprd/util/ArrayUtil", "sprd/extensions/CanvasToBlob", "xaml!sprd/data/DesignerApiDataSource", "sprd/model/Transformer", "sprd/model/AbstractShop", "sprd/entity/TextConfiguration", "xaml!sprd/view/svg/BendingTextConfigurationUploadRenderer"],
    function(DesignConfigurationBase, Size, Font, ProductUtil, BlobImage, IImageUploadService, flow, _, ArrayUtil, CanvasToBlob, DesignerApiDataSource, Transformer, Shop, TextConfiguration, BendingTextConfigurationUploadRenderer) {
        var PATH_TYPE = {
            OUTER_CIRCLE: "outer_circle",
            INNER_CIRCLE: "inner_circle",
            HEART: "heart"
        };

        var designCache = {},
            copyrightWordList = TextConfiguration.getCopyrightWordList();

        return DesignConfigurationBase.inherit('sprd.model.BendingTextConfiguration', {

            defaults: {
                fontSize: 16,

                _size: Size,
                aspectRatio: 1,
                _allowScale: true,
                loading: false,
                initialized: false,
                isNew: false,
                isTemplate: false,

                angle: 50,
                path: PATH_TYPE.OUTER_CIRCLE,
                textPath: "{textPath()}",
                dy: "{dy()}",

                textPathOffsetX: 0,
                textPathOffsetY: 0,
                transformer: null,
                copyrightWordList: null,
                initialText: null
            },

            type: "bendingText",
            representationType: "text",

            $events: [
                "recalculateSize"
            ],

            inject: {
                imageUploadService: IImageUploadService,
                designerApi: DesignerApiDataSource,
                context: "context"
            },

            ctor: function() {
                this.callBase();

                copyrightWordList.bind("add", function() {
                    this._validateText();
                }, this);

                this.$synchronizeCache = designCache;
            },

            textChangedSinceCreation: function () {
                var initialText = this.$.initialText,
                    currentText = this.$.text;

                if (!initialText) {
                    return true;
                }

                return initialText !== currentText;
            },

            isOnlyWhiteSpace: function () {
                var text = this.$.text;
                if (!text) {
                    return true;
                }

                return /^[\s\n\r]*$/.test(text);
            },

            init: function(options, callback) {
                var properties = this.$.properties,
                    context = this.$.context,
                    self = this;
                options = options || {};

                this.initTransformer();
                if (!_.isEmpty(properties)) {

                    if (this.$.initialized) {
                        callback && callback();
                        return;
                    }

                    flow()
                        .seq(function(cb) {
                            options = _.clone(options);
                            options.noDesignFetch = true;

                            DesignConfigurationBase.prototype.init.call(self, options, cb);
                        })
                        .seq(function(cb) {
                            var fontFamilies = context.$.fontFamilies;
                            if (fontFamilies.size()) {
                                cb();
                            } else {
                                fontFamilies.fetch({fullData: true}, cb);
                            }
                        })
                        .seq("fontFamily", function() {
                            var fontFamilyId = properties.fontFamilyId;
                            if (fontFamilyId) {
                                var items = context.$.fontFamilies.$items;

                                for (var i = items.length; i--;) {
                                    if (items[i].$.id == properties.fontFamilyId) {
                                        return items[i];
                                    }
                                }
                            }
                        })
                        .seq(function() {
                            var printType = self.$.printType;
                            if (printType && properties.fill) {
                                self.setColor(null, printType.getClosestPrintColor(properties.fill))
                            }
                        })
                        .seq(function() {
                            if (properties.text) {

                                var fontFamily = this.vars.fontFamily,
                                    fontWeight = properties.fontWeight,
                                    fontStyle = properties.fontStyle;

                                var scale = {
                                    x: properties.scale,
                                    y: properties.scale
                                };

                                var size = new Size({
                                    width: (properties.size && properties.size.width) || 0,
                                    height: (properties.size && properties.size.height) || 0
                                });

                                self.set({
                                    text: properties.text,
                                    angle: properties.angle || 50,
                                    path: properties.path || PATH_TYPE.OUTER_CIRCLE,
                                    font: fontFamily.getFont(fontWeight, fontStyle),
                                    fontSize: properties.fontSize || 16,
                                    _size: size,
                                    scale: scale
                                })
                            }
                        })
                        .exec(function(err) {
                            self.set("initialized", true);
                            callback && callback(err);
                        });
                } else {
                    callback && callback();
                }

            },

            _commitText: function() {
                this._validateText();
            },

            initTransformer: function() {
                var shop = this.$.designerApi.createEntity(Shop, this.$.context.$.id);
                this.set('transformer', shop.createEntity(Transformer));
            },

            size: function() {
                return this.$._size || Size.empty;
            }.onChange("_size").on("sizeChanged"),

            compose: function() {
                var ret = this.callBase();
                var font = this.$.font;
                ret.properties.type = "bendingText";
                ret.properties.text = this.$.text;
                ret.properties.angle = this.$.angle;
                ret.properties.fontFamilyId = font.getFontFamily().$.id;
                ret.properties.fontWeight = font.$.weight;
                ret.properties.fontStyle = font.$.style;
                ret.properties.fontSize = this.$.fontSize;
                if (!this.$.printColors.isEmpty()) {
                    ret.properties.fill = this.$.printColors.at(0).toHexString();
                }
                ret.properties.path = this.$.path;
                ret.properties.scale = this.$.scale.x;
                ret.properties.size = this.$._size.$;

                return ret;
            },

            _initializeBindingsBeforeComplete: function() {
                this.callBase();

                var recalculateSize = function() {
                    var self = this;
                    self.trigger("recalculateSize", self);
                    this.trigger('configurationChanged');
                };

                this.bind("change:text", recalculateSize, this);
                this.bind("change:angle", recalculateSize, this);
                this.bind("change:font", recalculateSize, this);
                this.bind("change:fontSize", recalculateSize, this);

                this.bind("change:printColors", function() {
                    this.trigger('configurationChanged');
                }, this)
            },

            _validatePrintTypeSize: function(printType, width, height, scale) {
                var ret = this.callBase();

                if (!printType || !scale) {
                    return ret;
                }

                ret.minBound = this._isScaleTooSmall(printType, scale);

                return ret;
            },

            _isScaleTooSmall: function(printType, scale) {
                var font = this.$.font,
                    fontSize = this.$.fontSize;

                if (printType.isShrinkable()) {
                    return false;
                }

                if (font && fontSize) {
                    return Math.min(Math.abs(scale.x), Math.abs(scale.y)) < font.$.minimalSize / fontSize;
                }

                return false;
            },

            textPath: function() {
                var a = this.$.angle;

                this.set("path", PATH_TYPE.OUTER_CIRCLE);
                if (a < 0) {
                    a = -a;

                    return "M 0, 0 m oneTime, twoTime a oneTime, oneTime 0 1, 0 0, twoTime a oneTime, oneTime 0 1, 0 0, -twoTime"
                        .replace(/oneTime/g, "" + a)
                        .replace(/twoTime/g, "" + (2 * a));

                } else {
                    return "M 0, 0 m oneTime, 0 a oneTime, oneTime 0 1, 1 0, -twoTime a oneTime, oneTime 0 1, 1 0, twoTime"
                        .replace(/oneTime/g, "" + a)
                        .replace(/twoTime/g, "" + (2 * a));
                }

            }.on("recalculateSize"),

            dy: function() {
                return this.$.angle < 0 ? 16 : 0;
            }.onChange("angle"),

            getPossiblePrintTypes: function(appearance) {
                var ret = [],
                    tmp,
                    printArea = this.$.printArea,
                    font = this.$.font;

                if (!printArea || !font) {
                    return ret;
                }

                tmp = this.getPossiblePrintTypesForPrintArea(printArea, appearance);
                _.each(tmp, function(element) {
                    if (ret.indexOf(element) === -1) {
                        ret.push(element);
                    }
                });

                return ret;
            }.onChange("printArea", "font"),

            setColor: function(layerIndex, color) {
                var printColors = this.$.printColors;
                if (printColors && color) {
                    printColors.reset([color]);
                }
            },

            getPossiblePrintTypesForPrintArea: function(printArea, appearance) {
                var fontFamily = this.$.font.getFontFamily(),
                    text = this.$.text;

                if (text) {
                    var possiblePrintTypes = ProductUtil.getPossiblePrintTypesForTextOnPrintArea(fontFamily, printArea, appearance),
                        digitalPrintTypes = _.filter(possiblePrintTypes, function(printType) {
                            return !printType.isPrintColorColorSpace();
                        });
                    return ArrayUtil.moveToStart(possiblePrintTypes, digitalPrintTypes);
                }
            },

            save: function(callback) {
                var self = this,
                    digitalPrint = !this.$.printType.isPrintColorColorSpace();

                var cacheId = [self.$.angle, self.$.text, self.$.font.$.id, self.$.fontSize, self.$.printType.$.id];
                var fill = self.$.printColors.at(0).toHexString();

                if (digitalPrint) {
                    cacheId.push(fill);
                }

                cacheId = cacheId.join("-");

                this.synchronizeFunctionCall(function(callback) {

                    flow()
                        .seq('design', function(cb) {
                            self.transformTextPath(cb);
                        })
                        .exec(function(err, results) {
                            callback(err, results.design);
                        });

                }, cacheId, function(err, design) {
                    self.set('design', design);
                    callback(err);
                }, this);

            },

            getPrintColor: function() {
                var configuration = this,
                    printColors = configuration.$.printColors,
                    printColor = null;

                if (printColors && printColors.size()) {
                    printColor = printColors.at(0).toHexString();
                }

                return printColor;
            }.on("printColors"),

            transformTextPath: function(callback) {
                var self = this;
                try {
                    var uploadRenderer = this.$stage.createComponent(BendingTextConfigurationUploadRenderer, {
                        configuration: this
                    });
                    this.$stage.addChild(uploadRenderer);
                    var svgContent = uploadRenderer.getElementAsString();
                } catch (e) {
                    callback(e, null);
                } finally {
                    this.$stage.removeChild(uploadRenderer);
                }

                var transformer = this.$.transformer;

                transformer.set('content', svgContent);
                transformer.save(null, function(err, transformer) {
                    if (err) {
                        return callback(err, transformer);
                    }

                    var upload = transformer.get("content");

                    var designId = (upload.designId || "").replace(/^u?/, "u"),
                        design = self.$.context.getCollection("designs").createItem(designId);

                    design.fetch(function(err) {
                        callback(err, design);
                    });
                })
            },

            saveTakesTime: function() {
                return true;
            },

            isAllowedOnPrintArea: function(printArea) {
                return printArea && printArea.get("restrictions.textAllowed") == true;
            },

            _additionalValidation: function($, options) {
                if (this._hasSome($, ["angle", "text", "fontSize"])) {
                    return {
                        angle: $.angle,
                        text: $.text,
                        validateHardBoundary: true
                    };
                }

            },

            _validateText: function() {
                var text = (this.$.text || "").toLowerCase(),
                    badWord;

                if (text.length > 1) {
                    // check that we don't contain copyright content
                    if (copyrightWordList && copyrightWordList.size()) {
                        badWord = copyrightWordList.find(function(word) {
                            return text.indexOf(word.toLowerCase()) !== -1;
                        });

                        this._setError("copyright", badWord);
                    }
                }
            }
        });
    });
<|endoftext|>