<commit_before>
var ConexaoServidor = function(_Usuario, _Senha)
{
	var urlBase = "http://192.168.1.200:90?usuario=" + _Usuario + "&senha=" + _Senha;
	var database, databaseName = 'MinhaUnoDB';

 	var validarLogin = function(_EventoLoginValido)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
     		Ti.API.info("Received text: " + this.responseText);
     		if(this.responseText == '1')
     		   _EventoLoginValido();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", urlBase);
 		// Send the request.
 		client.send();
 	}

 	var inicializarDatabase = function()
 	{
 		Ti.API.info("Inicializando Base de Dados");
		database = Ti.Database.open(databaseName);

		//Criação das tabelas feitas desta forma pois não funcionou a passagem de variáveis com o SQL para a função execute.
		database.execute('CREATE TABLE IF NOT EXISTS HorarioSemestre(codigo INTEGER PRIMARY KEY, turma TEXT, nome TEXT, curso TEXT, dataG2 TEXT, dataG3 TEXT, professor TEXT, creditos INTEGER, turno TEXT, grade INTEGER, periodo INTEGER);');
		database.execute('CREATE TABLE IF NOT EXISTS HorarioSemestreDisciplina(codigo INTEGER PRIMARY KEY, turma TEXT, hora TEXT, diasemana TEXT, data TEXT, ocorreu TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS NotaGraduacao(nome TEXT, notaG3 FLOAT, mediaFinal FLOAT, notaG2 FLOAT, notaG1 FLOAT, estadoMateria TEXT, statusAcademico TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS NotaGraduacaoAcademico(nomeDisciplina TEXT, peso TEXT, nota FLOAT, data TEXT, nome TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS MaterialApoio(nomeDisciplina TEXT, publicacao TEXT, nome TEXT, descricao TEXT, url TEXT);');

		database.close();

		Ti.API.info('Chegou ao fim da criacao da base');
 	}

 	var extrairMaterialApoio = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
    		Ti.API.info(this.responseText);
     		var json = JSON.parse(this.responseText);
			var i, j, disciplina, detalhes;

			database = Ti.Database.open(databaseName);
			database.execute('delete from MaterialApoio;');

			for (i = 0; i < json.disciplinas.length; i++) {
				disciplina = json.disciplinas[i];
				Ti.API.info(disciplina.nome);

				for(j = 0; j < disciplina.materiais.length; j++){
					detalhe = disciplina.materiais[j];
					database.execute('insert into MaterialApoio (nomeDisciplina, publicacao, nome, descricao, url) values (?,?,?,?,?);', disciplina.nome, detalhe.publicacao, detalhe.nome, detalhe.descricao, detalhe.url);
				}
			}

			database.close();

     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	var extrairNotasGraduacao = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
    		var json = JSON.parse(this.responseText);
    		var i, disciplinas, detalhes;

    		for (i = 0; i < json.disciplinas.length; i++) {
				Ti.API.info(json.disciplinas[i].nome);
			}

     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	var extrairHorariosSemestre = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
     		var json = JSON.parse(this.responseText);
     		var i, disciplinas, detalhes;

			for (i = 0; i < json.disciplinas.length; i++) {

			}

     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	this.extrairInformacoes = function(_EventoFimExtracao)
 	{
 		var urlMaterialApoio = urlBase + '&info=materiais';
 		var urlNotasGraduacao = urlBase + '&info=notas';
 		var urlHorariosSemestre = urlBase + '&info=horarios';

 		inicializarDatabase();

 		validarLogin(function(){
 			Ti.API.info('Login Accepted! Começou a extracao de dados.');
 			extrairMaterialApoio(urlMaterialApoio, extrairHorariosSemestre(urlHorariosSemestre, extrairNotasGraduacao(urlNotasGraduacao, _EventoFimExtracao)));
 		});
 	}

};

<commit_msg>Terminada a comunicação com o Servidor<commit_after>
var ConexaoServidor = function(_Usuario, _Senha)
{
	var urlBase = "http://192.168.1.200:90?usuario=" + _Usuario + "&senha=" + _Senha;
	var database, databaseName = 'MinhaUnoDB';

 	var validarLogin = function(_EventoLoginValido)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
     		if(this.responseText == '1')
     		   _EventoLoginValido();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", urlBase);
 		// Send the request.
 		client.send();
 	}

 	var inicializarDatabase = function()
 	{
 		Ti.API.info("Inicializando Base de Dados");
		database = Ti.Database.open(databaseName);

		/*
		 * Código de Emergencia... Use com sabedoria!
		 */
		/*
		database.execute('DROP TABLE HorarioSemestre;');
		database.execute('DROP TABLE HorarioSemestreDisciplina;');
		database.execute('DROP TABLE NotaGraduacao;');
		database.execute('DROP TABLE NotaGraduacaoAvaliacao;');
		database.execute('DROP TABLE MaterialApoio;');
		*/

		//Criação das tabelas feitas desta forma pois não funcionou a passagem de variáveis com o SQL para a função execute.
		database.execute('CREATE TABLE IF NOT EXISTS HorarioSemestre(codigo TEXT, turma TEXT, nome TEXT, curso TEXT, dataG2 TEXT, dataG3 TEXT, professor TEXT, creditos INTEGER, turno TEXT, grade INTEGER, periodo INTEGER);');
		database.execute('CREATE TABLE IF NOT EXISTS HorarioSemestreDisciplina(codigo TEXT, turma TEXT, hora TEXT, diasemana TEXT, data TEXT, ocorreu TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS NotaGraduacao(nome TEXT, notaG3 FLOAT, mediaFinal FLOAT, notaG2 FLOAT, notaG1 FLOAT, estadoMateria TEXT, statusAcademico TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS NotaGraduacaoAvaliacao(nomeDisciplina TEXT, peso TEXT, nota FLOAT, data TEXT, nome TEXT);');
		database.execute('CREATE TABLE IF NOT EXISTS MaterialApoio(nomeDisciplina TEXT, publicacao TEXT, nome TEXT, descricao TEXT, url TEXT);');

		database.close();

		Ti.API.info('Chegou ao fim da criacao da base');
 	}

 	var extrairMaterialApoio = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
     		var json = JSON.parse(this.responseText);
			var i, j, disciplina, detalhes;

			database = Ti.Database.open(databaseName);
			database.execute('delete from MaterialApoio;');

			for (i = 0; i < json.disciplinas.length; i++) {
				disciplina = json.disciplinas[i];

				for(j = 0; j < disciplina.materiais.length; j++){
					detalhe = disciplina.materiais[j];
					database.execute('insert into MaterialApoio (nomeDisciplina, publicacao, nome, descricao, url) values (?,?,?,?,?);', disciplina.nome, detalhe.publicacao, detalhe.nome, detalhe.descricao, detalhe.url);
				}
			}

			database.close();

     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	var extrairNotasGraduacao = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
    		var json = JSON.parse(this.responseText);
			var i, j, disciplina, detalhes;

			database = Ti.Database.open(databaseName);
			database.execute('delete from NotaGraduacao;');
			database.execute('delete from NotaGraduacaoAvaliacao');

			for (i = 0; i < json.disciplinas.length; i++) {
				disciplina = json.disciplinas[i];

				if(disciplina.dados.estado == 'fechada')
				{
					database.execute('insert into NotaGraduacao (nome, notaG3, mediaFinal, notaG2, notaG1, estadoMateria, statusAcademico) values (?,?,?,?,?,?,?);', disciplina.nome, disciplina.dados.G3, disciplina.dados.MF, disciplina.dados.G2, disciplina.dados.G1, disciplina.dados.estado, disciplina.dados.status);
				}
				else
				{
					database.execute('insert into NotaGraduacao (nome, notaG3, mediaFinal, notaG2, notaG1, estadoMateria, statusAcademico) values (?,?,?,?,?,?,?);', disciplina.nome, 0, 0, disciplina.dados.mediaG2, disciplina.dados.mediaG1, disciplina.dados.estado, "");

					for (j = 0; j < disciplina.dados.avaliacoes.length; j++)
					{
						database.execute('insert into NotaGraduacaoAvaliacao (nomeDisciplina, peso, nota, data, nome) values (?,?,?,?,?);', disciplina.nome, disciplina.dados.avaliacoes[j].peso, disciplina.dados.avaliacoes[j].nota, disciplina.dados.avaliacoes[j].data, disciplina.dados.avaliacoes[j].nome);
					}
				}

			}

			database.close();

     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	var extrairHorariosSemestre = function(_url, _proximaFuncao)
 	{
 		var client = Ti.Network.createHTTPClient({
     	// function called when the response data is available
    	onload : function(e) {
			var json = JSON.parse(this.responseText);
     		var i, j, disciplina, detalhes;

			database = Ti.Database.open(databaseName);
			database.execute('delete from HorarioSemestre;');
			database.execute('delete from HorarioSemestreDisciplina');

			for (i = 0; i < json.disciplinas.length; i++) {
				disciplina = json.disciplinas[i];

				database.execute('insert into HorarioSemestre(codigo, turma, nome, curso, dataG2, dataG3, professor, creditos, turno, grade, periodo) values (?,?,?,?,?,?,?,?,?,?,?);', disciplina.codigo, disciplina.turma, disciplina.nome, disciplina.dados.detalhes.curso, disciplina.dados.detalhes.g2, disciplina.dados.detalhes.g3, disciplina.dados.detalhes.professor, disciplina.dados.detalhes.creditos, disciplina.dados.detalhes.turno, disciplina.dados.detalhes.grade, disciplina.dados.detalhes.periodo);

				for(j = 0; j < disciplina.dados.horarios.length; j++)
				{
					var horario = disciplina.dados.horarios[j];

					database.execute('insert into HorarioSemestreDisciplina(codigo, turma, hora, diasemana, data, ocorreu) values (?,?,?,?,?,?);', disciplina.codigo, disciplina.turma, horario.hora, horario.semana, horario.dia, horario.ocorreu);
				}

			}

			database.close();

			activityIndicator.show();
     		if(_proximaFuncao)
     			_proximaFuncao();
    	},
    	// function called when an error occurs, including a timeout
     	onerror : function(e) {
     		msgBox('Atenção', 'Ocorreu um problema na comunicação com o servidor. Verifique sua conexão com a internet ou tente novamente mais tarde.');
         	Ti.API.debug(e.error);
    	},
     	timeout : 50000  // in milliseconds
 		});

 		// Prepare the connection.
		client.open("GET", _url);
 		// Send the request.
 		client.send();
 	}

 	this.extrairInformacoes = function(_EventoFimExtracao)
 	{
 		var urlMaterialApoio = urlBase + '&info=materiais';
 		var urlNotasGraduacao = urlBase + '&info=notas';
 		var urlHorariosSemestre = urlBase + '&info=horarios';

 		inicializarDatabase();

 		validarLogin(function(){
 			extrairMaterialApoio(urlMaterialApoio, extrairHorariosSemestre(urlHorariosSemestre, extrairNotasGraduacao(urlNotasGraduacao, _EventoFimExtracao)));
 		});
 	}

};

<|endoftext|>


<commit_before>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var dimsum = global.dimsum = module.exports = exports = {};

var punct = [',','.',';',':','?'];
	punct.regexp = new RegExp('[' + punct.join('') + ']*','g');

var grammar = {
	sentences_per_paragraph: [3,5],
	questions_per_paragraph: [0,2],
	words_per_sentence: [10,31],
	commas_per_sentence: [0,4]
};

var config = {
	'format': 'text'
};

var classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

var cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?";

var cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.";

dimsum.latin = dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') );

dimsum.classic = function() { return classic; };

dimsum.cicero32 = function() { return cicero_1_10_32; };

dimsum.cicero33 = function() { return cicero_1_10_33; };

dimsum.sentence = function() {

	var word = '';
	var words = [];
	var num_words = range(grammar.words_per_sentence[0], grammar.words_per_sentence[1]);
	var num_commas = range(grammar.commas_per_sentence[0], grammar.commas_per_sentence[1]);

	// Get some words
	while (words.length < num_words) {
		word = dimsum.latin[ range(0, dimsum.latin.length -1) ];
		words.push(word);
	}

	// Add some commas
	for (var i = 0; i < num_commas; i++) {
		word = range(4, words.length - 3);
		if (words[word].match(',')) {
			i--;
		}
		else {
			words[word] += ',';
		}
	}

	// Capitalize the first word
	words = words.join(' ');
	words = words.replace(/^[a-z]/i, words[0].toUpperCase());

	// Punctuate and return
	return words + '.';
};

dimsum.paragraph = function() {
	var sentences = [];
	var num_sentences = range(grammar.sentences_per_paragraph[0], grammar.sentences_per_paragraph[1]);
	while (sentences.length < num_sentences) {
		sentences.push(this.sentence());
	}
	return sentences.join(' ');
};

dimsum.configure = function(options) {
	for (key in options) {
		config[key] = options[key];
	}
	return this;
};

/**
 * Create a random chunk of lipsum. Returns an array containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs How many paragraphs to generate.
 */
dimsum.generate = function(num_paragraphs, options) {
	var configuration = options || config;
	var sentences = [];
	var paragraphs = [];
	num_paragraphs = num_paragraphs || 1;
	while (paragraphs.length < num_paragraphs) {
		paragraphs.push(this.paragraph());
	}
	switch(configuration.format) {
		case 'text':
			return paragraphs.join("\r\n\r\n");
			break;
		case 'html':
			return '
' + paragraphs.join('

') + '
';
			break;
	}
};

/** Utils **/
function normify(strings) {
	return strings.join(' ')
			.toLowerCase()
			.replace(punct.regexp, '');
};

function dedupe(array) {
	var obj = {};
	var result = [];
	for (var i = 0; i < array.length; i++) {
		obj[array[i]] = null;
	}
	for (key in obj) {
		result.push(key);
	}
	return result;
}

function range(min, max) {
	return min + Math.random() * (max - min - 1) << 0;
}

}(this));<commit_msg>Adding bounds to config<commit_after>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var dimsum = global.dimsum = module.exports = exports = {},

	classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

	cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",

	cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",

	config = {
		'format': 'text',
		'bounds': {
			'per_paragraph': {
				sentences: [3, 5]
			},
			'per_sentence': {
				words: [10, 31],
				commas: [0, 4]
			}
		}
	},

	punct = [',','.',';',':','?'];
	punct.regexp = new RegExp('[' + punct.join('') + ']*','g');

dimsum.latin = dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') );

dimsum.classic = function() { return classic; };

dimsum.cicero32 = function() { return cicero_1_10_32; };

dimsum.cicero33 = function() { return cicero_1_10_33; };

dimsum.sentence = function() {

	var word = '',
		words = [],
		num_words = range(config.bounds.per_sentence.words[0], config.bounds.per_sentence.words[1]),
		num_commas = range(config.bounds.per_sentence.commas[0], config.bounds.per_sentence.commas[1]);

	// Get some words
	while (words.length < num_words) {
		word = dimsum.latin[ range(0, dimsum.latin.length -1) ];
		words.push(word);
	}

	// Add some commas
	for (var i = 0; i < num_commas; i++) {
		word = range(4, words.length - 3);
		if (words[word].match(',')) {
			i--;
		}
		else {
			words[word] += ',';
		}
	}

	// Capitalize the first word
	words = words.join(' ');
	words = words.replace(/^[a-z]/i, words[0].toUpperCase());

	// Punctuate and return
	return words + '.';
};

dimsum.paragraph = function() {
	var sentences = [],
		num_sentences = range(config.bounds.per_paragraph.sentences[0], config.bounds.per_paragraph.sentences[1]);
	while (sentences.length < num_sentences) {
		sentences.push(this.sentence());
	}
	return sentences.join(' ');
};

dimsum.configure = function(options) {
	for (key in options) {
		config[key] = options[key];
	}
	return this;
};

/**
 * Create a random chunk of lipsum. Returns an array containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs How many paragraphs to generate.
 */
dimsum.generate = function(num_paragraphs, options) {
	var configuration = options || config,
		sentences = [],
		paragraphs = [];
	num_paragraphs = num_paragraphs || 1;
	while (paragraphs.length < num_paragraphs) {
		paragraphs.push(this.paragraph());
	}
	switch(configuration.format) {
		case 'text':
			return paragraphs.join("\r\n\r\n");
			break;
		case 'html':
			return '
' + paragraphs.join('

') + '
';
			break;
	}
};

/** Utils **/
function normify(strings) {
	return strings.join(' ')
			.toLowerCase()
			.replace(punct.regexp, '');
};

function dedupe(array) {
	var obj = {},
		result = [];
	for (var i = 0; i < array.length; i++) {
		obj[array[i]] = null;
	}
	for (key in obj) {
		result.push(key);
	}
	return result;
}

function range(min, max) {
	return min + Math.random() * (max - min - 1) << 0;
}

}(this));<|endoftext|>


<commit_before>Divvy.Preview = {};

Divvy.Preview.init = function ()
{
	this.win = Ti.UI.createWindow({
		barColor: Divvy.winBarColor,
		backButtonTitle: 'Thumbnails', // Changes the back button title, because the bucket name is too long.
		orientationModes: [ // clearly defines the orientations that this window can be at.
			Titanium.UI.PORTRAIT,
    		Titanium.UI.LANDSCAPE_LEFT,
    		Titanium.UI.LANDSCAPE_RIGHT,
		],
		translucent: true, // this makes the navBar, opaque and allows us to use the space behind the navBar.
		fullscreen: true, // allows us to use height of 480 instead of 460
		navBarHidden: true // hides the bar when it first opens.
	});

	Titanium.Gesture.addEventListener('orientationchange', function(e)
	{
	    if (e.orientation == Titanium.UI.PORTRAIT)
	    {
	    	Divvy.Preview.scrollView.width = Divvy.deviceWidth;
	    	Divvy.Preview.scrollView.height = Divvy.deviceHeight;

	    }
	    else if (e.orientation == Titanium.UI.LANDSCAPE_LEFT || e.orientation == Titanium.UI.LANDSCAPE_RIGHT)
	    {
	    	Divvy.Preview.scrollView.height = Divvy.deviceWidth;
	    	Divvy.Preview.scrollView.width = Divvy.deviceHeight;
	    }
	});

	// when the window "closes", we run our "deconstruction" methods to save memory.
	this.win.addEventListener('close', function(e) {
		Divvy.Preview.close();
	});

	// pop-over dialog
	this.saveToGalleryDialog = Ti.UI.createOptionDialog({
		options: ['Save To Gallery', 'Cancel'],
		cancel: 1
	});

	// when something is clicked in the dialog
	this.saveToGalleryDialog.addEventListener('click', function(e)
	{
		// if it isn't "Save To Gallery", then we just stop here.
		if (e.index != 0)
			return;

		// method to saving the curretn photo
		Ti.Media.saveToPhotoGallery(Divvy.Preview.photo.toImage(), { //TODO: FIX THIS
			success: function(e)
			{
				alert("Saved to your photo gallery!");
			},
			error: function(e)
			{
				alert("Couldn't save to your photo gallery.");
			}
		});
	});

	// the folder looking icon on the top right
	this.saveButton = Ti.UI.createButton({
		systemButton: Ti.UI.iPhone.SystemButton.ORGANIZE
	});

	// open the dialog view if the folder looking icon button is clicked
	this.saveButton.addEventListener('click', function(e){
		Divvy.Preview.saveToGalleryDialog.show();
	});

	// this just adds the button window navBar.
	this.win.rightNavButton = this.saveButton;

	// this is essentially a coverflow view.
	this.scrollView = Ti.UI.createScrollableView({
//		top: -20,
		views: [],
		backgroundColor: '#000',
		height: this.deviceHeight, width: this.deviceWidth,
//		contentWidth: Divvy.Preview.contentWidth, contentHeight: Divvy.Preview.contentHeight,
		showPagingControl: false, // this hides the little dots
		maxZoomScale: 2, // this just allows us to pinch and zoom
		minZoomScale: 1,
		isFullScreen: true, // this is not an element to the function itself, but a variable we'll use (just our own data).
	});

	this.currentView = null; // we want to keep track what is being viewed at the moment.

	// if the view is "tapped", hide/show the navigation bar and status bar.
	this.scrollView.addEventListener('singletap', function(e) {
		if (Divvy.Preview.scrollView.isFullScreen) {
			Ti.UI.iPhone.showStatusBar({animated: false});
//			Divvy.Preview.scrollView.animate({top: -20});
			Divvy.Preview.win.showNavBar({animated: false});
		} else {
			Ti.UI.iPhone.hideStatusBar({animated: false});
//			Divvy.Preview.scrollView.animate({top: 0});
			Divvy.Preview.win.hideNavBar({animated: false});
		}

		Divvy.Preview.scrollView.isFullScreen = !Divvy.Preview.scrollView.isFullScreen; // we call upon our custom var here.
	});

	// if we change "pages", identified as a scroll action,
	// we want to dynamically load the next images.
	this.scrollView.addEventListener('scroll', function(e)
	{
		// this causes the current viewset to stay the same
		// if we didn't actually move to another page.
		if (e.view.index == Divvy.Preview.currentView.index)
			return;

		Divvy.Preview.currentView.hide(); // since we moved on, this fixes the "flashing" image bug

		Divvy.Preview.loadViews(e.view.index, Divvy.View.imageArray); //borrowed from other pages.
	});
/*
	this.scrollView.addEventListener('doubletap', function(e) {
		clearInterval(Divvy.Preview.scrollAnimation);

		if (Divvy.Preview.scrollView.scaled)
		{
			Divvy.Preview.scrollAnimation = setInterval(function() {
				if (Divvy.Preview.scrollView.zoomScale >= 2.0)
					clearInterval(Divvy.Preview.scrollAnimation);
				Divvy.Preview.scrollView.zoomScale += 0.1;
			}, 20);
		}
		else
		{
			Divvy.Preview.scrollAnimation = setInterval(function() {
				if (Divvy.Preview.scrollView.zoomScale <= 1.0)
					clearInterval(Divvy.Preview.scrollAnimation);
				Divvy.Preview.scrollView.zoomScale -= 0.1;
			}, 20);
		}

    	Divvy.Preview.scrollView.scaled = !Divvy.Preview.scrollView.scaled;
	});
/*
	this.toolbar = Ti.UI.createToolbar({

	});

	this.win.add(this.toolbar);
*/
	this.activityIndicator = Ti.UI.createActivityIndicator({
		width: 50, height: 50,
	});

	this.activityIndicator.show();

	this.win.add(this.scrollView);
};

Divvy.Preview.open = function (index)
{
	this.loadViews(index, Divvy.View.imageArray); //borrowed from other pages.

	Divvy.open(this.win);
	setTimeout(function(e) {
		if (Divvy.Preview.scrollView.isFullScreen)
		{
			Ti.UI.iPhone.showStatusBar({animated: false});
			Divvy.Preview.win.showNavBar({animated: false});
		}
	}, 2000);
};

Divvy.Preview.close = function()
{
	Divvy.Preview.win.hideNavBar({animated: false});
	Divvy.Preview.scrollView.isFullScreen = true;
	Divvy.Preview.scrollView.views = [];
	Divvy.Preview.scrollView.height = Divvy.deviceHeight;
	Divvy.PReview.scrollView.width = Divvy.deviceWidth;
};

Divvy.Preview.loadViews = function(index, dataset)
{
	this.win.title = (index+1) + ' of ' + dataset.length;

	var loadedViews = [];
	var selectedPage = 0;
	var i = 0;

	if (index > 0)
	{
		i = index - 1;
		var v1 = Ti.UI.createView({index: i});
		var a1 = Ti.UI.createActivityIndicator({width: 50, height: 50});
		a1.show();
		v1.add(a1);
		loadedViews.push(v1);
		selectedPage = 1;
	}

	i = index;
	var v2 = Ti.UI.createView({index: i});
	this.addImageToView(v2, dataset[i].imageId);
	loadedViews.push(v2);

	if (index < dataset.length - 1)
	{
		i = index + 1;
		var v3 = Ti.UI.createView({index: i});
		var a3 = Ti.UI.createActivityIndicator({width: 50, height: 50});
		a3.show();
		v3.add(a3);
		loadedViews.push(v3);
	}
	else
	{
		selectedPage = 1;
	}

	Divvy.Preview.scrollView.currentPage = selectedPage; // we set the selected page index
	Divvy.Preview.scrollView.views = loadedViews; // we put the new viewset into the scrollView

	this.currentView = loadedViews[Divvy.Preview.scrollView.currentPage];
};

Divvy.Preview.addImageToView = function(view, imageId)
{
	var imageView = Ti.UI.createImageView({
		backgroundColor: '#000',
	});

	Network.cache.run(
		Divvy.url + 'image/'+imageId,
		Network.CACHE_INVALIDATE,
		Divvy.Preview.onImageUrlSuccess,
		Divvy.Preview.onImageUrlError,
		{imageView: imageView, viewContainer: view}
	);

	view.add(imageView);
	view.add(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageUrlSuccess = function(data, date, status, user, xhr)
{
	try
	{
		data = JSON.parse(data);
	}
	catch (excp)
	{
		Divvy.Preview.onImageUrlError(Network.PARSE_ERROR, 0);
		return;
	}

	if (data.status == 'error')
	{
		Divvy.Preview.onImageUrlError(data.error, 0);
		return;
	}

	Network.cache.run(
		data.url,
		168, //1 week
		Divvy.Preview.onImageSuccess,
		Divvy.Preview.onImageError,
		user
	);
};

Divvy.Preview.onImageUrlError = function(status, httpStatus)
{
	// do nothing
};

Divvy.Preview.onImageSuccess = function(data, date, status, user, xhr)
{
	user.viewContainer.remove(Divvy.Preview.activityIndicator);
	user.imageView.image = data;
};

Divvy.Preview.onImageError = function(status, httpStatus)
{
	//do nothing
};
<commit_msg>Syntax issue fix.<commit_after>Divvy.Preview = {};

Divvy.Preview.init = function ()
{
	this.win = Ti.UI.createWindow({
		barColor: Divvy.winBarColor,
		backButtonTitle: 'Thumbnails', // Changes the back button title, because the bucket name is too long.
		orientationModes: [ // clearly defines the orientations that this window can be at.
			Titanium.UI.PORTRAIT,
    		Titanium.UI.LANDSCAPE_LEFT,
    		Titanium.UI.LANDSCAPE_RIGHT,
		],
		translucent: true, // this makes the navBar, opaque and allows us to use the space behind the navBar.
		fullscreen: true, // allows us to use height of 480 instead of 460
		navBarHidden: true // hides the bar when it first opens.
	});

	Titanium.Gesture.addEventListener('orientationchange', function(e)
	{
	    if (e.orientation == Titanium.UI.PORTRAIT)
	    {
	    	Divvy.Preview.scrollView.width = Divvy.deviceWidth;
	    	Divvy.Preview.scrollView.height = Divvy.deviceHeight;

	    }
	    else if (e.orientation == Titanium.UI.LANDSCAPE_LEFT || e.orientation == Titanium.UI.LANDSCAPE_RIGHT)
	    {
	    	Divvy.Preview.scrollView.height = Divvy.deviceWidth;
	    	Divvy.Preview.scrollView.width = Divvy.deviceHeight;
	    }
	});

	// when the window "closes", we run our "deconstruction" methods to save memory.
	this.win.addEventListener('close', function(e) {
		Divvy.Preview.close();
	});

	// pop-over dialog
	this.saveToGalleryDialog = Ti.UI.createOptionDialog({
		options: ['Save To Gallery', 'Cancel'],
		cancel: 1
	});

	// when something is clicked in the dialog
	this.saveToGalleryDialog.addEventListener('click', function(e)
	{
		// if it isn't "Save To Gallery", then we just stop here.
		if (e.index != 0)
			return;

		// method to saving the curretn photo
		Ti.Media.saveToPhotoGallery(Divvy.Preview.photo.toImage(), { //TODO: FIX THIS
			success: function(e)
			{
				alert("Saved to your photo gallery!");
			},
			error: function(e)
			{
				alert("Couldn't save to your photo gallery.");
			}
		});
	});

	// the folder looking icon on the top right
	this.saveButton = Ti.UI.createButton({
		systemButton: Ti.UI.iPhone.SystemButton.ORGANIZE
	});

	// open the dialog view if the folder looking icon button is clicked
	this.saveButton.addEventListener('click', function(e){
		Divvy.Preview.saveToGalleryDialog.show();
	});

	// this just adds the button window navBar.
	this.win.rightNavButton = this.saveButton;

	// this is essentially a coverflow view.
	this.scrollView = Ti.UI.createScrollableView({
//		top: -20,
		views: [],
		backgroundColor: '#000',
		height: this.deviceHeight, width: this.deviceWidth,
//		contentWidth: Divvy.Preview.contentWidth, contentHeight: Divvy.Preview.contentHeight,
		showPagingControl: false, // this hides the little dots
		maxZoomScale: 2, // this just allows us to pinch and zoom
		minZoomScale: 1,
		isFullScreen: true, // this is not an element to the function itself, but a variable we'll use (just our own data).
	});

	this.currentView = null; // we want to keep track what is being viewed at the moment.

	// if the view is "tapped", hide/show the navigation bar and status bar.
	this.scrollView.addEventListener('singletap', function(e) {
		if (Divvy.Preview.scrollView.isFullScreen) {
			Ti.UI.iPhone.showStatusBar({animated: false});
//			Divvy.Preview.scrollView.animate({top: -20});
			Divvy.Preview.win.showNavBar({animated: false});
		} else {
			Ti.UI.iPhone.hideStatusBar({animated: false});
//			Divvy.Preview.scrollView.animate({top: 0});
			Divvy.Preview.win.hideNavBar({animated: false});
		}

		Divvy.Preview.scrollView.isFullScreen = !Divvy.Preview.scrollView.isFullScreen; // we call upon our custom var here.
	});

	// if we change "pages", identified as a scroll action,
	// we want to dynamically load the next images.
	this.scrollView.addEventListener('scroll', function(e)
	{
		// this causes the current viewset to stay the same
		// if we didn't actually move to another page.
		if (e.view.index == Divvy.Preview.currentView.index)
			return;

		Divvy.Preview.currentView.hide(); // since we moved on, this fixes the "flashing" image bug

		Divvy.Preview.loadViews(e.view.index, Divvy.View.imageArray); //borrowed from other pages.
	});
/*
	this.scrollView.addEventListener('doubletap', function(e) {
		clearInterval(Divvy.Preview.scrollAnimation);

		if (Divvy.Preview.scrollView.scaled)
		{
			Divvy.Preview.scrollAnimation = setInterval(function() {
				if (Divvy.Preview.scrollView.zoomScale >= 2.0)
					clearInterval(Divvy.Preview.scrollAnimation);
				Divvy.Preview.scrollView.zoomScale += 0.1;
			}, 20);
		}
		else
		{
			Divvy.Preview.scrollAnimation = setInterval(function() {
				if (Divvy.Preview.scrollView.zoomScale <= 1.0)
					clearInterval(Divvy.Preview.scrollAnimation);
				Divvy.Preview.scrollView.zoomScale -= 0.1;
			}, 20);
		}

    	Divvy.Preview.scrollView.scaled = !Divvy.Preview.scrollView.scaled;
	});
/*
	this.toolbar = Ti.UI.createToolbar({

	});

	this.win.add(this.toolbar);
*/
	this.activityIndicator = Ti.UI.createActivityIndicator({
		width: 50, height: 50,
	});

	this.activityIndicator.show();

	this.win.add(this.scrollView);
};

Divvy.Preview.open = function (index)
{
	this.loadViews(index, Divvy.View.imageArray); //borrowed from other pages.

	Divvy.open(this.win);
	setTimeout(function(e) {
		if (Divvy.Preview.scrollView.isFullScreen)
		{
			Ti.UI.iPhone.showStatusBar({animated: false});
			Divvy.Preview.win.showNavBar({animated: false});
		}
	}, 2000);
};

Divvy.Preview.close = function()
{
	Divvy.Preview.win.hideNavBar({animated: false});
	Divvy.Preview.scrollView.isFullScreen = true;
	Divvy.Preview.scrollView.views = [];
	Divvy.Preview.scrollView.height = Divvy.deviceHeight;
	Divvy.Preview.scrollView.width = Divvy.deviceWidth;
};

Divvy.Preview.loadViews = function(index, dataset)
{
	this.win.title = (index+1) + ' of ' + dataset.length;

	var loadedViews = [];
	var selectedPage = 0;
	var i = 0;

	if (index > 0)
	{
		i = index - 1;
		var v1 = Ti.UI.createView({index: i});
		var a1 = Ti.UI.createActivityIndicator({width: 50, height: 50});
		a1.show();
		v1.add(a1);
		loadedViews.push(v1);
		selectedPage = 1;
	}

	i = index;
	var v2 = Ti.UI.createView({index: i});
	this.addImageToView(v2, dataset[i].imageId);
	loadedViews.push(v2);

	if (index < dataset.length - 1)
	{
		i = index + 1;
		var v3 = Ti.UI.createView({index: i});
		var a3 = Ti.UI.createActivityIndicator({width: 50, height: 50});
		a3.show();
		v3.add(a3);
		loadedViews.push(v3);
	}
	else
	{
		selectedPage = 1;
	}

	Divvy.Preview.scrollView.currentPage = selectedPage; // we set the selected page index
	Divvy.Preview.scrollView.views = loadedViews; // we put the new viewset into the scrollView

	this.currentView = loadedViews[Divvy.Preview.scrollView.currentPage];
};

Divvy.Preview.addImageToView = function(view, imageId)
{
	var imageView = Ti.UI.createImageView({
		backgroundColor: '#000',
	});

	Network.cache.run(
		Divvy.url + 'image/'+imageId,
		Network.CACHE_INVALIDATE,
		Divvy.Preview.onImageUrlSuccess,
		Divvy.Preview.onImageUrlError,
		{imageView: imageView, viewContainer: view}
	);

	view.add(imageView);
	view.add(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageUrlSuccess = function(data, date, status, user, xhr)
{
	try
	{
		data = JSON.parse(data);
	}
	catch (excp)
	{
		Divvy.Preview.onImageUrlError(Network.PARSE_ERROR, 0);
		return;
	}

	if (data.status == 'error')
	{
		Divvy.Preview.onImageUrlError(data.error, 0);
		return;
	}

	Network.cache.run(
		data.url,
		168, //1 week
		Divvy.Preview.onImageSuccess,
		Divvy.Preview.onImageError,
		user
	);
};

Divvy.Preview.onImageUrlError = function(status, httpStatus)
{
	// do nothing
};

Divvy.Preview.onImageSuccess = function(data, date, status, user, xhr)
{
	user.viewContainer.remove(Divvy.Preview.activityIndicator);
	user.imageView.image = data;
};

Divvy.Preview.onImageError = function(status, httpStatus)
{
	//do nothing
};
<|endoftext|>


<commit_before>module.exports = [
    {key: 5597, val: 'H » TENNISKENTTÄ'},
    {key: 5607, val: 'H2 » TENNISKENTTÄ'},
    {key: 5609, val: 'HUOM1 » ULKOTENNIS'},
    {key: 5610, val: 'HUOM2 » ULKOTENNIS'},
    {key: 5611, val: 'HUOM3 » ULKOTENNIS'},
    {key: 5612, val: 'HUOM4 » ULKOTENNIS'},
    {key: 5598, val: 'HUOMIO » SULKAPALLOHALLI'},
    {key: 5608, val: 'HUOMIO » ULKOTENNIS'},
    {key: 5585, val: 'K 1 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5586, val: 'K 2 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5587, val: 'K 3 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5588, val: 'K 4 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5589, val: 'K 5 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5590, val: 'K 6 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5519, val: 'K1 » TENNISKENTTÄ'},
    {key: 5516, val: 'K10 » TENNISKENTTÄ'},
    {key: 5526, val: 'K11 » TENNISKENTTÄ'},
    {key: 5527, val: 'K12 » TENNISKENTTÄ'},
    {key: 5515, val: 'K13 » TENNISKENTTÄ'},
    {key: 5573, val: 'K14 » TENNISKENTTÄ'},
    {key: 5574, val: 'K15 » TENNISKENTTÄ'},
    {key: 5575, val: 'K16 » TENNISKENTTÄ'},
    {key: 5576, val: 'K17 » TENNISKENTTÄ'},
    {key: 5577, val: 'K18 » TENNISKENTTÄ'},
    {key: 5578, val: 'K19 » TENNISKENTTÄ'},
    {key: 5520, val: 'K2 » TENNISKENTTÄ'},
    {key: 5620, val: 'K20 » TENNISKENTTÄ'},
    {key: 5621, val: 'K21 » TENNISKENTTÄ'},
    {key: 5622, val: 'K22 » TENNISKENTTÄ'},
    {key: 5521, val: 'K3 » TENNISKENTTÄ'},
    {key: 5522, val: 'K4 » TENNISKENTTÄ'},
    {key: 5523, val: 'K5 » TENNISKENTTÄ'},
    {key: 5524, val: 'K6 » TENNISKENTTÄ'},
    {key: 5525, val: 'K7 » TENNISKENTTÄ'},
    {key: 5518, val: 'K8 » TENNISKENTTÄ'},
    {key: 5517, val: 'K9 » TENNISKENTTÄ'},
    {key: 5533, val: 'KENTTÄ 1 » SULKAPALLOHALLI'},
    {key: 5534, val: 'KENTTÄ 2 » SULKAPALLOHALLI'},
    {key: 5535, val: 'KENTTÄ 3 » SULKAPALLOHALLI'},
    {key: 5536, val: 'KENTTÄ 4 » SULKAPALLOHALLI'},
    {key: 5604, val: 'MASSA 10 » ULKOTENNIS'},
    {key: 5605, val: 'MASSA 11 » ULKOTENNIS'},
    {key: 5542, val: 'MASSA 6 » ULKOTENNIS'},
    {key: 5601, val: 'MASSA 7 » ULKOTENNIS'},
    {key: 5602, val: 'MASSA 8 » ULKOTENNIS'},
    {key: 5603, val: 'MASSA 9 » ULKOTENNIS'},
    {key: 5591, val: 'MASSAKENTTÄ » TAIVALLAHTI ULKOTENNIS'},
    {key: 5571, val: 'SULKAPALLO 1 » KESÄSULKA'},
    {key: 5543, val: 'SULKAPALLO 1 » KESÄSULKA'},
    {key: 5544, val: 'SULKAPALLO 2 » KESÄSULKA'},
    {key: 5572, val: 'SULKAPALLO 2 » KESÄSULKA'},
    {key: 5545, val: 'SULKAPALLO 3 » KESÄSULKA'},
    {key: 5546, val: 'SULKAPALLO 4 » KESÄSULKA'},
    {key: 5551, val: 'TK 1 » KESÄTENNIS'},
    {key: 5548, val: 'TK 10 » KESÄTENNIS'},
    {key: 5557, val: 'TK 11 » KESÄTENNIS'},
    {key: 5558, val: 'TK 12 » KESÄTENNIS'},
    {key: 5547, val: 'TK 13 » KESÄTENNIS'},
    {key: 5579, val: 'TK 14 » KESÄTENNIS'},
    {key: 5580, val: 'TK 15 » KESÄTENNIS'},
    {key: 5581, val: 'TK 16 » KESÄTENNIS'},
    {key: 5582, val: 'TK 17 » KESÄTENNIS'},
    {key: 5583, val: 'TK 18 » KESÄTENNIS'},
    {key: 5584, val: 'TK 19 » KESÄTENNIS'},
    {key: 5552, val: 'TK 2 » KESÄTENNIS'},
    {key: 5564, val: 'TK 2 » KESÄTENNIS'},
    {key: 5623, val: 'TK 20 » KESÄTENNIS'},
    {key: 5624, val: 'TK 21 » KESÄTENNIS'},
    {key: 5625, val: 'TK 22 » KESÄTENNIS'},
    {key: 5553, val: 'TK 4 » KESÄTENNIS'},
    {key: 5554, val: 'TK 5 » KESÄTENNIS'},
    {key: 5555, val: 'TK 6 » KESÄTENNIS'},
    {key: 5556, val: 'TK 7 » KESÄTENNIS'},
    {key: 5550, val: 'TK 8 » KESÄTENNIS'},
    {key: 5549, val: 'TK 9 » KESÄTENNIS'},
    {key: 5537, val: 'ULKO 1 » ULKOTENNIS'},
    {key: 5538, val: 'ULKO 2 » ULKOTENNIS'},
    {key: 5539, val: 'ULKO 3 » ULKOTENNIS'},
    {key: 5540, val: 'ULKO 4 » ULKOTENNIS'},
    {key: 5541, val: 'ULKO 5 » ULKOTENNIS'},
    {key: 5626, val: 'VARASTO » TAIVALLAHTI SISÄTENNIS'},
    {key: 5615, val: 'VARASTO 1 » TENNISKENTTÄ'},
    {key: 5616, val: 'VARASTO 2 » TENNISKENTTÄ'},
    {key: 5627, val: 'VARASTO 2 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5628, val: 'VARASTO 3 » TAIVALLAHTI SISÄTENNIS'},
    {key: 5617, val: 'VARASTO 3 » TENNISKENTTÄ'},
    {key: 5618, val: 'VARASTO 3 » SULKAPALLOHALLI'}
]
<commit_msg>Transform resources to map format<commit_after>module.exports = {
    5597: 'H » TENNISKENTTÄ',
    5607: 'H2 » TENNISKENTTÄ',
    5609: 'HUOM1 » ULKOTENNIS',
    5610: 'HUOM2 » ULKOTENNIS',
    5611: 'HUOM3 » ULKOTENNIS',
    5612: 'HUOM4 » ULKOTENNIS',
    5598: 'HUOMIO » SULKAPALLOHALLI',
    5608: 'HUOMIO » ULKOTENNIS',
    5585: 'K 1 » TAIVALLAHTI SISÄTENNIS',
    5586: 'K 2 » TAIVALLAHTI SISÄTENNIS',
    5587: 'K 3 » TAIVALLAHTI SISÄTENNIS',
    5588: 'K 4 » TAIVALLAHTI SISÄTENNIS',
    5589: 'K 5 » TAIVALLAHTI SISÄTENNIS',
    5590: 'K 6 » TAIVALLAHTI SISÄTENNIS',
    5519: 'K1 » TENNISKENTTÄ',
    5516: 'K10 » TENNISKENTTÄ',
    5526: 'K11 » TENNISKENTTÄ',
    5527: 'K12 » TENNISKENTTÄ',
    5515: 'K13 » TENNISKENTTÄ',
    5573: 'K14 » TENNISKENTTÄ',
    5574: 'K15 » TENNISKENTTÄ',
    5575: 'K16 » TENNISKENTTÄ',
    5576: 'K17 » TENNISKENTTÄ',
    5577: 'K18 » TENNISKENTTÄ',
    5578: 'K19 » TENNISKENTTÄ',
    5520: 'K2 » TENNISKENTTÄ',
    5620: 'K20 » TENNISKENTTÄ',
    5621: 'K21 » TENNISKENTTÄ',
    5622: 'K22 » TENNISKENTTÄ',
    5521: 'K3 » TENNISKENTTÄ',
    5522: 'K4 » TENNISKENTTÄ',
    5523: 'K5 » TENNISKENTTÄ',
    5524: 'K6 » TENNISKENTTÄ',
    5525: 'K7 » TENNISKENTTÄ',
    5518: 'K8 » TENNISKENTTÄ',
    5517: 'K9 » TENNISKENTTÄ',
    5533: 'KENTTÄ 1 » SULKAPALLOHALLI',
    5534: 'KENTTÄ 2 » SULKAPALLOHALLI',
    5535: 'KENTTÄ 3 » SULKAPALLOHALLI',
    5536: 'KENTTÄ 4 » SULKAPALLOHALLI',
    5604: 'MASSA 10 » ULKOTENNIS',
    5605: 'MASSA 11 » ULKOTENNIS',
    5542: 'MASSA 6 » ULKOTENNIS',
    5601: 'MASSA 7 » ULKOTENNIS',
    5602: 'MASSA 8 » ULKOTENNIS',
    5603: 'MASSA 9 » ULKOTENNIS',
    5591: 'MASSAKENTTÄ » TAIVALLAHTI ULKOTENNIS',
    5571: 'SULKAPALLO 1 » KESÄSULKA',
    5543: 'SULKAPALLO 1 » KESÄSULKA',
    5544: 'SULKAPALLO 2 » KESÄSULKA',
    5572: 'SULKAPALLO 2 » KESÄSULKA',
    5545: 'SULKAPALLO 3 » KESÄSULKA',
    5546: 'SULKAPALLO 4 » KESÄSULKA',
    5551: 'TK 1 » KESÄTENNIS',
    5548: 'TK 10 » KESÄTENNIS',
    5557: 'TK 11 » KESÄTENNIS',
    5558: 'TK 12 » KESÄTENNIS',
    5547: 'TK 13 » KESÄTENNIS',
    5579: 'TK 14 » KESÄTENNIS',
    5580: 'TK 15 » KESÄTENNIS',
    5581: 'TK 16 » KESÄTENNIS',
    5582: 'TK 17 » KESÄTENNIS',
    5583: 'TK 18 » KESÄTENNIS',
    5584: 'TK 19 » KESÄTENNIS',
    5552: 'TK 2 » KESÄTENNIS',
    5564: 'TK 2 » KESÄTENNIS',
    5623: 'TK 20 » KESÄTENNIS',
    5624: 'TK 21 » KESÄTENNIS',
    5625: 'TK 22 » KESÄTENNIS',
    5553: 'TK 4 » KESÄTENNIS',
    5554: 'TK 5 » KESÄTENNIS',
    5555: 'TK 6 » KESÄTENNIS',
    5556: 'TK 7 » KESÄTENNIS',
    5550: 'TK 8 » KESÄTENNIS',
    5549: 'TK 9 » KESÄTENNIS',
    5537: 'ULKO 1 » ULKOTENNIS',
    5538: 'ULKO 2 » ULKOTENNIS',
    5539: 'ULKO 3 » ULKOTENNIS',
    5540: 'ULKO 4 » ULKOTENNIS',
    5541: 'ULKO 5 » ULKOTENNIS',
    5626: 'VARASTO » TAIVALLAHTI SISÄTENNIS',
    5615: 'VARASTO 1 » TENNISKENTTÄ',
    5616: 'VARASTO 2 » TENNISKENTTÄ',
    5627: 'VARASTO 2 » TAIVALLAHTI SISÄTENNIS',
    5628: 'VARASTO 3 » TAIVALLAHTI SISÄTENNIS',
    5617: 'VARASTO 3 » TENNISKENTTÄ',
    5618: 'VARASTO 3 » SULKAPALLOHALLI'
}
<|endoftext|>


<commit_before>(window.gloader || glow).module({
	name: "glow.widgets.Mask",
	library: ["glow", "@VERSION@"],
	depends: [[
		"glow", "@VERSION@",
		'glow.dom',
		'glow.events',
		'glow.widgets'
	]],
	builder: function(glow) {
		var dom = glow.dom,
			$ = dom.get,
			events = glow.events,
			widgets = glow.widgets,
			bodyProperties, //this is a holding place for body padding & margins
			htmlStr = '<div class="glowNoMask" style="margin:0;padding:0;position:absolute;width:100%;top:0;left:0;overflow:auto;', //reusable html string
			noScrollContainer,
			// javascript:false stops IE complaining over SSL
			iframeSrc = '';
/**
@name glow.widgets.Mask
@class
@description A semi transparent layer covering the page

Use this if you're wanting to block out the main content of the page.
Anything you want to be on top of the mask needs to have a higher z-index (default: 9990).

Widgets must be called in a glow.ready() call.

@see Mask user guide

@param {Object} opts Object containing the attributes specified below.
@param {Number} [opts.opacity=0.7] The opacity of the mask (from 0 to 1).
@param {String} [opts.color=black] The colour of the mask
@param {Function} [opts.onClick] Shortcut to attach an event listener that is called when the user clicks on the mask.
@param {Number} [opts.zIndex=9990] The z-index of mask layer

@example
	var mask = new glow.widget.Mask({
		onClick : function () {
			this.remove();
		}
	});
	mask.add();

*/

/*
Deprecated glow.widgets.Mask() param

@param {Boolean} [opts.disableScroll=false] If set to true, scrolling is disabled in the main document.

This feature is experimental. It works by moving
the document into a new container, offsetting it and setting overflow
to none. Because this adds a new element between body and your document,
you may have problems if your scripts rely on certain elements. Children
of <body> which have class "glowNoMask" will be left as children of
<body>.

*/

/**
    @name glow.widgets.Mask#maskElement
    @type glow.dom.NodeList
    @description The node overlayed to create the mask.
    @example
		//create mask instance
		var myMask = new glow.widgets.Mask();

		//display mask
		myMask.maskElement.css("background", "url(stripe.png)");
 */

		function Mask(opts) {
			this.opts = glow.lang.apply({
				color: '#000',
				opacity: 0.7,
				zIndex: 9900,
				disableScroll: false
			}, opts || {});

			/*
			Property: maskElement
				The node overlayed to create the mask. Access this if you want to
				change its properties on the fly
			*/
			var docBody = document.body,
				mask = this.maskElement = dom.create(
				htmlStr + 'z-index:' + this.opts.zIndex + ';background:' + this.opts.color + ';visibility:hidden">
'
			).appendTo(docBody),
				that = this;

			mask.css("opacity", this.opts.opacity);

			if (glow.env.ie < 7) {
				this._iframe = dom.create(iframeSrc).css("z-index", this.opts.zIndex - 1).appendTo(docBody);
			}

			//add mask node click event, route it through to a Mask event
			events.addListener(mask, "click", function() {
				events.fire(that, "click");
			});
			if (this.opts.onClick) {
				events.addListener(this, "click", opts.onClick);
			}
		}

		Mask.prototype = {
			/**
			@name glow.widgets.Mask#add
			@function
			@description Displays the mask.
			@example

				// create the mask
				var myMask = new glow.widgets.Mask();

				// add the mask over the screen
				myMask.add()
			*/
			add: function () {
				var doc = $(document),
					body = $(document.body),
					win = $(window),
					that = this;

				if (this.opts.disableScroll && !noScrollContainer) { //avoid blocking scrolling twice
					noScrollContainer = glow.dom.create(
						htmlStr + 'height:100%;overflow:hidden;">' + htmlStr + '">

'
					);

					var scrollVals = widgets._scrollPos(),
						bodyStyle = body[0].style,
						clientHeight = win.height(),
						clientWidth = win.width(),
						noScroll = noScrollContainer.get("div"),
						//get children which don't have class "glowNoMask"
						bodyChildren = body.children().filter(function() { return (' ' + this.className + ' ').indexOf("glowNoMask") == -1 });

					bodyProperties = {
						margin: [body.css("margin-top"), body.css("margin-right"), body.css("margin-bottom"), body.css("margin-left")],
						padding: [body.css("padding-top"), body.css("padding-right"), body.css("padding-bottom"), body.css("padding-left")],
						height: body.css("height")
					};

					bodyStyle.margin = bodyStyle.padding = 0;

					bodyStyle.height = "100%";
					noScroll[0].style.zIndex = this.opts.zIndex - 1;

					noScrollContainer.appendTo(body);

					noScroll.css("margin", bodyProperties.margin.join(" ")).
							 css("padding", bodyProperties.padding.join(" ")).
							 css("top", -scrollVals.y - parseFloat(bodyProperties.margin[0]) + "px").
							 css("left", -scrollVals.x + "px").
							 append(bodyChildren);
				}

				function resizeMask() {
					var bodyHeight = body.height();
					// hide the mask so it's not included in our measurement of width / height
					that.maskElement.hide();
					// Work out the required width to set the mask (this is basically the width of the content but without the mask)
					that.maskElement.css("width", doc.width() + "px")
						.css("height", ( that.opts.disableScroll ? noScrollContainer.height() : Math.max(bodyHeight, win.height()) ) + "px");
					that.maskElement.show();
					if (glow.env.ie < 7) {
						var maskStyle = that.maskElement[0].style;
						that._iframe.css("width", maskStyle.width).css("height", maskStyle.height);
					}
				}

				this.maskElement.css("visibility", "visible").css("display", "block");
				if (glow.env.ie < 7) {
					this._iframe.css("display", "block");
				}
				resizeMask();
				this._resizeListener = events.addListener(window, "resize", resizeMask);
			},
			/**
			@name glow.widgets.Mask#remove
			@function
			@description Removes the mask.
			@example

				// create the mask
				var myMask = new glow.widgets.Mask();

				// add the mask over the screen
				myMask.add()

				// remove the mask from over the screen
				myMask.remove()
			*/
			remove : function () {
				this.maskElement.css("visibility", "hidden").css("display", "none");
				if (glow.env.ie < 7) {
					this._iframe.css("display", "none");
				}
				events.removeListener(this._resizeListener);

				if (this.opts.disableScroll) {
					var body = $(document.body),
						noScroll = noScrollContainer.children();

					noScroll.children().appendTo(body);
					window.scroll(-parseInt(noScroll.css("left")), -parseInt(noScroll.css("top")));
					noScrollContainer.remove();
					body.css("margin", bodyProperties.margin.join(" ")).
						 css("padding", bodyProperties.padding.join(" ")).
						 css("height", bodyProperties.height);

					delete noScrollContainer;
					noScrollContainer = undefined;
				}

			}
		};

		glow.widgets.Mask = Mask;
	}
});
<commit_msg>Mask: Tidying up resize, fixing an issue I reintroduced for IE<commit_after>(window.gloader || glow).module({
	name: "glow.widgets.Mask",
	library: ["glow", "@VERSION@"],
	depends: [[
		"glow", "@VERSION@",
		'glow.dom',
		'glow.events',
		'glow.widgets'
	]],
	builder: function(glow) {
		var dom = glow.dom,
			$ = dom.get,
			events = glow.events,
			widgets = glow.widgets,
			bodyProperties, //this is a holding place for body padding & margins
			htmlStr = '<div class="glowNoMask" style="margin:0;padding:0;position:absolute;width:100%;top:0;left:0;overflow:auto;', //reusable html string
			noScrollContainer,
			// javascript:false stops IE complaining over SSL
			iframeSrc = '';
/**
@name glow.widgets.Mask
@class
@description A semi transparent layer covering the page

Use this if you're wanting to block out the main content of the page.
Anything you want to be on top of the mask needs to have a higher z-index (default: 9990).

Widgets must be called in a glow.ready() call.

@see Mask user guide

@param {Object} opts Object containing the attributes specified below.
@param {Number} [opts.opacity=0.7] The opacity of the mask (from 0 to 1).
@param {String} [opts.color=black] The colour of the mask
@param {Function} [opts.onClick] Shortcut to attach an event listener that is called when the user clicks on the mask.
@param {Number} [opts.zIndex=9990] The z-index of mask layer

@example
	var mask = new glow.widget.Mask({
		onClick : function () {
			this.remove();
		}
	});
	mask.add();

*/

/*
Deprecated glow.widgets.Mask() param

@param {Boolean} [opts.disableScroll=false] If set to true, scrolling is disabled in the main document.

This feature is experimental. It works by moving
the document into a new container, offsetting it and setting overflow
to none. Because this adds a new element between body and your document,
you may have problems if your scripts rely on certain elements. Children
of <body> which have class "glowNoMask" will be left as children of
<body>.

*/

/**
    @name glow.widgets.Mask#maskElement
    @type glow.dom.NodeList
    @description The node overlayed to create the mask.
    @example
		//create mask instance
		var myMask = new glow.widgets.Mask();

		//display mask
		myMask.maskElement.css("background", "url(stripe.png)");
 */

		function Mask(opts) {
			this.opts = glow.lang.apply({
				color: '#000',
				opacity: 0.7,
				zIndex: 9900,
				disableScroll: false
			}, opts || {});

			/*
			Property: maskElement
				The node overlayed to create the mask. Access this if you want to
				change its properties on the fly
			*/
			var docBody = document.body,
				mask = this.maskElement = dom.create(
				htmlStr + 'z-index:' + this.opts.zIndex + ';background:' + this.opts.color + ';visibility:hidden">
'
			).appendTo(docBody),
				that = this;

			mask.css("opacity", this.opts.opacity);

			if (glow.env.ie < 7) {
				this._iframe = dom.create(iframeSrc).css("z-index", this.opts.zIndex - 1).appendTo(docBody);
			}

			//add mask node click event, route it through to a Mask event
			events.addListener(mask, "click", function() {
				events.fire(that, "click");
			});
			if (this.opts.onClick) {
				events.addListener(this, "click", opts.onClick);
			}
		}

		Mask.prototype = {
			/**
			@name glow.widgets.Mask#add
			@function
			@description Displays the mask.
			@example

				// create the mask
				var myMask = new glow.widgets.Mask();

				// add the mask over the screen
				myMask.add()
			*/
			add: function () {
				var doc = $(document),
					body = $(document.body),
					win = $(window),
					that = this;

				if (this.opts.disableScroll && !noScrollContainer) { //avoid blocking scrolling twice
					noScrollContainer = glow.dom.create(
						htmlStr + 'height:100%;overflow:hidden;">' + htmlStr + '">

'
					);

					var scrollVals = widgets._scrollPos(),
						bodyStyle = body[0].style,
						clientHeight = win.height(),
						clientWidth = win.width(),
						noScroll = noScrollContainer.get("div"),
						//get children which don't have class "glowNoMask"
						bodyChildren = body.children().filter(function() { return (' ' + this.className + ' ').indexOf("glowNoMask") == -1 });

					bodyProperties = {
						margin: [body.css("margin-top"), body.css("margin-right"), body.css("margin-bottom"), body.css("margin-left")],
						padding: [body.css("padding-top"), body.css("padding-right"), body.css("padding-bottom"), body.css("padding-left")],
						height: body.css("height")
					};

					bodyStyle.margin = bodyStyle.padding = 0;

					bodyStyle.height = "100%";
					noScroll[0].style.zIndex = this.opts.zIndex - 1;

					noScrollContainer.appendTo(body);

					noScroll.css("margin", bodyProperties.margin.join(" ")).
							 css("padding", bodyProperties.padding.join(" ")).
							 css("top", -scrollVals.y - parseFloat(bodyProperties.margin[0]) + "px").
							 css("left", -scrollVals.x + "px").
							 append(bodyChildren);
				}

				function resizeMask() {
					// hide the mask so our measurement doesn't include the mask
					that.maskElement.hide();

					var newHeight = that.opts.disableScroll ? noScrollContainer.height() : Math.max( body.height(), win.height() ),
						// doc.width() doesn't work here, that value includes the maskElement in IE7 (and below), even though it's hidden
						newWidth  = that.opts.disableScroll ? noScrollContainer.width()  : Math.max( win.width(), doc[0].documentElement.scrollWidth, body[0].scrollWidth );

					// Work out the required width to set the mask (this is basically the width of the content but without the mask)
					that.maskElement.width(newWidth).height(newHeight);

					// resize the iframe if we're using it
					if (that._iframe) {
						that._iframe.width(newWidth).height(newHeight);
					}

					// show the mask again
					that.maskElement.show();
				}

				this.maskElement.css("visibility", "visible").css("display", "block");
				if (this._iframe) {
					this._iframe.css("display", "block");
				}
				resizeMask();
				this._resizeListener = events.addListener(window, "resize", resizeMask);
			},
			/**
			@name glow.widgets.Mask#remove
			@function
			@description Removes the mask.
			@example

				// create the mask
				var myMask = new glow.widgets.Mask();

				// add the mask over the screen
				myMask.add()

				// remove the mask from over the screen
				myMask.remove()
			*/
			remove : function () {
				this.maskElement.css("visibility", "hidden").css("display", "none");
				if (this._iframe) {
					this._iframe.css("display", "none");
				}
				events.removeListener(this._resizeListener);

				if (this.opts.disableScroll) {
					var body = $(document.body),
						noScroll = noScrollContainer.children();

					noScroll.children().appendTo(body);
					window.scroll(-parseInt(noScroll.css("left")), -parseInt(noScroll.css("top")));
					noScrollContainer.remove();
					body.css("margin", bodyProperties.margin.join(" ")).
						 css("padding", bodyProperties.padding.join(" ")).
						 css("height", bodyProperties.height);

					delete noScrollContainer;
					noScrollContainer = undefined;
				}

			}
		};

		glow.widgets.Mask = Mask;
	}
});
<|endoftext|>


<commit_before>import React, { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getTypes from './get-types'
import getContentRect from './get-content-rect'

function withContentRect(types) {
  return WrappedComponent =>
    class WithContentRect extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.func,
        onResize: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      componentWillMount() {
        this._resizeObserver = new ResizeObserver(this.measure)
      }

      componentWillUnmount() {
        if (this._resizeObserver && this._node) {
          this._resizeObserver.disconnect(this._node);
        }
        this._resizeObserver = null;
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this.setState({ contentRect })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = node => {
        if (this._resizeObserver) {
          if (node) {
            this._resizeObserver.observe(node)
          } else {
            this._resizeObserver.disconnect(this._node)
          }
        }
        this._node = node

        if (typeof this.props.innerRef === 'function') {
          this.props.innerRef(node)
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measureRef: this._handleRef,
          measure: this.measure,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<commit_msg>call setState within requestAnimationFrame to prevent inifinite loop Fixes #104<commit_after>import React, { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'
import getTypes from './get-types'
import getContentRect from './get-content-rect'

function withContentRect(types) {
  return WrappedComponent =>
    class WithContentRect extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.func,
        onResize: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      componentWillMount() {
        this._resizeObserver = new ResizeObserver(this.measure)
        this.animationFrameID = null;
      }

      componentWillUnmount() {
        if (this._resizeObserver && this._node) {
          this._resizeObserver.disconnect(this._node);
        }
        this._resizeObserver = null;
        window.cancelAnimationFrame(this.animationFrameID);
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this.animationFrameID = window.requestAnimationFrame(() => {
          if (this._resizeObserver) {
            this.setState({ contentRect })
          }
        })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = node => {
        if (this._resizeObserver) {
          if (node) {
            this._resizeObserver.observe(node)
          } else {
            this._resizeObserver.disconnect(this._node)
          }
        }
        this._node = node

        if (typeof this.props.innerRef === 'function') {
          this.props.innerRef(node)
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measureRef: this._handleRef,
          measure: this.measure,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import wrapDisplayName from 'recompose/wrapDisplayName'

const startAnimationName = 'onAutofillStart'
const endAnimationName = 'onAutofillCancel'
const styleElementId = 'autofill-style'

const isWebkit = () => navigator.userAgent.indexOf('WebKit') !== -1

function emptyAnimation(animationName) {
  return `
    @keyframes ${animationName} {
      from {/**/}
      to {/**/}
    }
  `
}

function injectStyle(style) {
  let styleElement = document.getElementById(styleElementId)

  if (!styleElement) {
    styleElement = document.createElement('style')
    styleElement.id = styleElementId
    document.head.appendChild(styleElement)
  }

  let styleSheet = styleElement.sheet

  styleSheet.insertRule(style, styleSheet.cssRules.length)
}

function injectKeyFrames() {
  const autofillStartEmptyKeyframesStyle = emptyAnimation(startAnimationName)
  const autofillEndEmptyKeyframesStyle = emptyAnimation(endAnimationName)

  injectStyle(autofillStartEmptyKeyframesStyle)
  injectStyle(autofillEndEmptyKeyframesStyle)
}

function injectAutofillHook() {
  const autofillHook = `
    input:-webkit-autofill {
      // Expose a hook for JavaScript when autofill is shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${startAnimationName};

      // Make the backgound color become yellow _really slowly_
      transition: background-color 50000s ease-in-out 0s;
    }
  `

  const notAutofillHook = `
    input:not(:-webkit-autofill) {
      // Expose a hook for JavaScript when autofill is no longer shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${endAnimationName};
    }`

  injectStyle(autofillHook)
  injectStyle(notAutofillHook)
}

function registerAutofill() {
  const autofillInjected =
    window.__klarna_ui_components && window.__klarna_ui_components.isAutofillInjected

  if (!autofillInjected && isWebkit()) {
    injectKeyFrames()
    injectAutofillHook()

    if (window.__klarna_ui_components) {
      window.__klarna_ui_components.isAutofillInjected = true
    } else {
      window.__klarna_ui_components = { isAutofillInjected: true }
    }
  }
}

export default autofillProps => Target => {
  class WithAutofillProps extends Component {
    constructor() {
      super()

      registerAutofill()

      this.state = { autofill: false }
    }

    handleAnimation(animationName) {
      switch (animationName) {
        case startAnimationName:
          return this.setState({ autofill: true })

        case endAnimationName:
          return this.setState({ autofill: false })
      }
    }

    render() {
      const { autofill } = this.state

      return (
        <Target
          onAnimationStart={this.handleAnimation.bind(this)}
          {...this.props}
          {...autofill && autofillProps}
        />
      )
    }
  }

  WithAutofillProps.displayName = wrapDisplayName(Target, 'withAutofillProps')

  return WithAutofillProps
}
<commit_msg>handle autofill regustration<commit_after>import React, { Component } from 'react'
import wrapDisplayName from 'recompose/wrapDisplayName'

const startAnimationName = 'onAutofillStart'
const endAnimationName = 'onAutofillCancel'
const styleElementId = 'autofill-style'
const counterAttribute = 'data-counter'

const isWebkit = () => navigator.userAgent.indexOf('WebKit') !== -1

function emptyAnimation(animationName) {
  return `
    @keyframes ${animationName} {
      from {/**/}
      to {/**/}
    }
  `
}

function injectStyle(style) {
  let styleSheet = document.getElementById(styleElementId).sheet

  styleSheet.insertRule(style, styleSheet.cssRules.length)
}

function injectKeyFrames() {
  const autofillStartEmptyKeyframesStyle = emptyAnimation(startAnimationName)
  const autofillEndEmptyKeyframesStyle = emptyAnimation(endAnimationName)

  injectStyle(autofillStartEmptyKeyframesStyle)
  injectStyle(autofillEndEmptyKeyframesStyle)
}

function injectAutofillHook() {
  const autofillHook = `
    input:-webkit-autofill {
      // Expose a hook for JavaScript when autofill is shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${startAnimationName};

      // Make the backgound color become yellow _really slowly_
      transition: background-color 50000s ease-in-out 0s;
    }
  `

  const notAutofillHook = `
    input:not(:-webkit-autofill) {
      // Expose a hook for JavaScript when autofill is no longer shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${endAnimationName};
    }`

  injectStyle(autofillHook)
  injectStyle(notAutofillHook)
}

function registerAutofill() {
  let autofillStyle = document.getElementById(styleElementId)

  if (!autofillStyle && isWebkit()) {
    autofillStyle = document.createElement('style')
    autofillStyle.id = styleElementId
    autofillStyle.setAttribute(counterAttribute, 0)
    document.head.appendChild(autofillStyle)

    injectKeyFrames()
    injectAutofillHook()
  }

  let usageCounter = autofillStyle.getAttribute(counterAttribute)
  usageCounter++
  autofillStyle.setAttribute(counterAttribute, usageCounter)
}

function unregisterAutofill() {
  let autofillStyle = document.getElementById(styleElementId)
  let usageCounter = autofillStyle.getAttribute(counterAttribute)
  usageCounter--
  autofillStyle.setAttribute(counterAttribute, usageCounter)

  if (usageCounter === 0) {
    autofillStyle.outerHTML = ''
  }
}

export default autofillProps => Target => {
  class WithAutofillProps extends Component {
    constructor() {
      super()

      this.state = { autofill: false }
    }

    onComponentDidMount() {
      registerAutofill()
    }

    onComponentWillUnmount() {
      unregisterAutofill()
    }

    handleAnimation(animationName) {
      switch (animationName) {
        case startAnimationName:
          return this.setState({ autofill: true })

        case endAnimationName:
          return this.setState({ autofill: false })
      }
    }

    render() {
      const { autofill } = this.state

      return (
        <Target
          onAnimationStart={this.handleAnimation.bind(this)}
          {...this.props}
          {...autofill && autofillProps}
        />
      )
    }
  }

  WithAutofillProps.displayName = wrapDisplayName(Target, 'withAutofillProps')

  return WithAutofillProps
}
<|endoftext|>