<commit_before>$(function () {
	'use strict';
	FastClick.attach(document.body);
	Goodnight.css('stylesheets/dark.css');
	var y, newtab;
	$(document).on("click", ".toggle", function() {
		$(this).parent().children('.toggle').toggle();
	});
	$('input').keydown(function (e) {
		if (e.which === 13 && $(this).val() !== '') {
			y = $(this).val().charAt(0).toUpperCase() + $(this).val().slice(1);
			y.split('<').join('<');
			$(this).val('').blur();
			$('
' + y + '
').appendTo('#conversation-box').fadeIn('slow', function () {
				y.split('<').join('<');
				app(y);
			});
		}
	});
	function say (r) {
		$('
' + r + '
').appendTo('#conversation-box').fadeIn('slow');
	}
	function app (y) {
		parse(y);
		$('html, body').animate({scrollTop: $(document).height()}, 'slow');
	}
	function parse (y) {
		y = y.toLowerCase();
		y = y.split('?').join('');
		y = y.split('!').join('');
		y = y.split('what\'s').join('what is');
		y = y.split('you\'re').join('you are');
		if (y.slice(-1) === '.') {
			y = y.slice(0, y.length - 1);
		}
		random(y);
	}
	function random (y) {
		if (y === 'flip a coin') {
			say(['Heads', 'Tails'][Math.floor(Math.random() * 2)] + '.');
		} else if (y === 'roll a die') {
			say(['One', 'Two', 'Three', 'Four', 'Five', 'Six'][Math.floor(Math.random() * 6)] + '.');
		} else if (y.startsWith('give me a random integer between ') || y.startsWith('give me a random number between ') || y.startsWith('generate a random integer between ') || y.startsWith('generate a random number between ')) {
			if (y.indexOf('give') !== -1) {
				if (y.indexOf('integer') !== -1) {
					y = y.slice(33);
				} else {
					y = y.slice(32);
				}
			} else {
				if (y.indexOf('integer') !== -1) {
					y = y.slice(34);
				} else {
					y = y.slice(33);
				}
			}
			y = y.split(' and ');
			y[0] = parseInt(y[0], 10);
			y[1] = parseInt(y[1], 10);
			if (y[0] !== NaN || y[1] !== NaN) {
				say(Math.floor(Math.random() * (Math.max(y[0], y[1]) - Math.min(y[0], y[1]) + 1) + Math.min(y[0], y[1])));
			} else {
				say('Those aren\'t both integers!');
			}
		} else {
			core(y);
		}
	}
	function core (y) {
		if (y === 'clear' || y === 'clear log' || y === 'clear logs') {
			say('Clearing log…');
			setTimeout(function () {
				$('#conversation-box').fadeOut('slow', function () {
					$('#conversation-box').empty().show();
				});
			}, 1000);
		} else if (y === 'hi' || y === 'hello' || y === 'hey' || y === 'greetings') {
			say(['Hi', 'Hello', 'Hey', 'Greetings'][Math.floor(Math.random() * 4)] + ['.', '!'][Math.floor(Math.random() * 2)]);
		} else if (y === 'what are you' || y === 'who are you' || y === 'what do you do') {
			say('I am Fuchsia. An intelligient virtual personal assistant for the web. I\'m based off of Jared Cubilla\'s Jarvis, but I\'m not voice-powered, which means that I can say write anything I want. You can find my documentation at https://github.com/355over113/fuchsia.');
		} else if (y === 'how are you' || y === 'how do you do' || y === 'how are you doing') {
			say(['I\'m fine.', 'I\'m okay.', 'I\'m great; thanks for asking!', 'I could be doing better.'][Math.floor(Math.random() * 4)]);
		} else if (y.startsWith('you')) {
			say(['Thank you', 'That\'s what I thought', 'We should be talking more about you'][Math.floor(Math.random() * 3)] + ['.', '!'][Math.floor(Math.random() * 2)]);
		} else if (y === 'what is the time' || y === 'what time is it' || y === 'give me the time' || y.split('day').join('date') === 'what is the date' || y.split('day').join('date') === 'what date is it' || y.split('day').join('date') === 'give me the date' || y.split('day').join('date') === 'what is the time and date' || y.split('day').join('date') === 'what is the date and time' || y.split('day').join('date') === 'what is the time and the date' || y.split('day').join('date') === 'what is the date and the time' || y.split('day').join('date') === 'what time and date is it' || y.split('day').join('date') === 'what date and time is it' || y.split('day').join('date') === 'give me the time and date' || y.split('day').join('date') === 'give me the date and time' || y.split('day').join('date') === 'give me the time and the date' || y.split('day').join('date') === 'give me the date and the time' || y.split('day').join('date') === 'when am i') {
			var now = new Date();
			var date, time, suffix;
			y = (y === 'when am i') ? 'tid' : y;
			if (y.indexOf('ti') !== -1) {
				time = [now.getHours(), now.getMinutes(), now.getSeconds()];
				suffix = (time[0] < 12) ? ' AM' : ' PM';
				time[0] = (time[0] <= 12) ? time[0] : time[0] - 12;
				time[1] = (time[1] >= 10) ? time[1] : '0' + time[1];
				time[2] = (time[2] >= 10) ? time[2] : '0' + time[2];
				time = time.join(':');
			}
			if (y.indexOf('d') !== -1) {
				var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
				var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
				var chron = ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
				var tempdate;
				date = [now.getDay(), now.getMonth(), now.getDate(), now.getFullYear()];
				date[0] = days[date[0]];
				date[1] = months[date[1]];
				tempdate = date[2];
				tempdate = (tempdate >= 10) ? tempdate.toString() : '0' + tempdate;
				console.log(tempdate);
				if (tempdate[0] === '1') {
					date[2] += 'th,';
					console.log(date[2]);
				} else {
					date[2] += chron[parseInt(tempdate[1], 10) - 1] + ',';
				}
				date = date.join(' ');
			}
			if (y.indexOf('ti') !== -1 && y.indexOf('d') !== -1) {
				say('It is currently ' + date + ' ' + time + suffix + '.');
			} else if (y.indexOf('time') !== -1) {
				say('The time is ' + time + suffix + '.');
			} else {
				say('The date is ' + date + '.');
			}
		} else if (y === 'toggle goodnight' || y === 'flip goodnight' || y === 'switch goodnight' || y === 'goodnight.toggle();' || y === 'goodnight.toggle()') {
			say('Toggling Goodnight—brace yourself…');
			setTimeout(function () {
				Goodnight.toggle();
			}, 2000);
		} else if (y.startsWith('go to ') || y.startsWith('open ')) {
			if (y.startsWith('go to')) {
				newtab = y.slice(6);
			} else {
				newtab = y.slice(5);
			}
			if (newtab.indexOf('.') === -1) {
				say('Opening ' + newtab + '.com…');
				setTimeout(function () {
					window.open('https://' + newtab + '.com', '_blank');
				}, 1000);
			} else {
				say('Opening ' + newtab + '…');
				setTimeout(function () {
					window.open('https://' + newtab, '_blank');
				}, 1000);
			}
		} else if (y.startsWith('search for ')){
			newtab = y.slice(11);
			say('Searching Google for "' + newtab + '"…');
			setTimeout(function () {
				window.open('https://www.google.ca/search?q=' + newtab.split(' ').join('+'), '_blank');
			}, 1000);
		} else if (y.startsWith('should i watch ') || y.startsWith('should i listen to ')) {
			if (y.startsWith('should i watch ')) {
				y = y.slice(15).split(' ').join('+');
				$.getJSON('https://www.omdbapi.com/?t=' + y + '&y=&plot=full&r=json&tomatoes=true', function (d) {
					var image;
					if (d.Poster !== undefined) {
						image = '
[Show Poster]
';
					}
					if (d.Error === undefined) {
						var reviews = '', sum = 0, count = 0;
						if (d.Type === 'movie') {
							d.Type = 'Film';
						} else if (d.Type === 'series') {
							d.Type = 'TV Series';
						}
						if (d.imdbRating !== 'N/A') {
							reviews += 'IMDb: ' + d.imdbRating + '/10
';
							sum += parseFloat(d.imdbRating, 10) * 10;
							count++;
						}
						if (d.tomatoRating !== 'N/A') {
							reviews += 'Rotten Tomatoes: ' + d.tomatoRating + '/10
';
							sum += parseFloat(d.tomatoRating, 10) * 10;
							count++;
						}
						if (d.Metascore !== 'N/A') {
							reviews += 'Metacritic: ' + d.Metascore + '/100
';
							sum += parseInt(d.Metascore, 10);
							count++;
						}
						reviews += '
Average: ' + Math.round(sum / count) + '%';
						say('Here is what I could find:');
						$('

' + d.Title + '

Starring ' + d.Actors + '

' + d.Rated + '

' + d.Year + ' ' + d.Type + '

' + d.Plot + '
' + image + '
' + reviews + '

').appendTo('#conversation-box').fadeIn('slow');
					} else {
						say('I apologize, but I couldn\'t find that film. I\'ll perform a Google search instead.');
						setTimeout(function () {
							say('Searching Google for "' + y + '"…');
							setTimeout(function () {
								window.open('https://www.google.ca/search?q=' + y.split(' ').join('+'), '_blank');
							}, 2000);
						}, 2000);
					}
				});
			} else {
				$.getJSON('https://api.spotify.com/v1/search?q=' + y.slice(19).split(' ').join('+') + '&type=artist&limit=1', function (d) {
					var image;
					var genres = '';
					if (d.artists.total) {
						for (var i = 0;i < d.artists.items[0].genres.length;i++) {
							d.artists.items[0].genres[i] = d.artists.items[0].genres[i].replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
						}
						if (d.artists.items[0].genres[0] !== undefined) {
							genres = 'Genres: ';
						}
						if (d.artists.items[0].images[0].url !== undefined) {
							image = '
[Show Image]
';
						}
						say('Here is what I could find:');
						$('

' + d.artists.items[0].name + '

Music Artist

' + genres + d.artists.items[0].genres.join(', ') + '
' + image + '
Popularity on Spotify: ' + d.artists.items[0].popularity + '
Followers on Spotify: ' + d.artists.items[0].followers.total + '

').appendTo('#conversation-box').fadeIn('slow');
					} else {
						say('I couldn\'t find that artist. I\'ll perform a Google search for them instead.');
						setTimeout(function () {
							say('Searching Google for "' + y.slice(19) + '"…');
							setTimeout(function () {
								window.open('https://www.google.ca/search?q=' + y.slice(19).split(' ').join('+'), '_blank');
							}, 2000);
						}, 2000);
					}
				});
			}
		} else if (y === 'ayy') {
			say('lmao');
		} else if (y === 'tell me a joke' || y.indexOf('chuck norris') !== -1 || y === 'be funny' || y === 'make me laugh') {
			$.getJSON('http://api.icndb.com/jokes/random', function (d) {
				say(d.value.joke);
			});
		} else {
			fallback(y);
		}
	}
	function fallback (y) {
		say('I apologize, but I wasn\'t sure what you were asking of me. I\'ll perform a Google search instead.');
		setTimeout(function () {
			say('Searching Google for "' + y + '"…');
			setTimeout(function () {
				window.open('https://www.google.ca/search?q=' + y.split(' ').join('+'), '_blank');
			}, 2000);
		}, 2000);
	}
	setTimeout(function () {
		$('#container').fadeIn('slow');
	}, 1000);
});
<commit_msg>Fixed "Should I watch"<commit_after>$(function () {
	'use strict';
	FastClick.attach(document.body);
	Goodnight.css('stylesheets/dark.css');
	var y, newtab;
	$(document).on("click", ".toggle", function() {
		$(this).parent().children('.toggle').toggle();
	});
	$('input').keydown(function (e) {
		if (e.which === 13 && $(this).val() !== '') {
			y = $(this).val().charAt(0).toUpperCase() + $(this).val().slice(1);
			y.split('<').join('<');
			$(this).val('').blur();
			$('
' + y + '
').appendTo('#conversation-box').fadeIn('slow', function () {
				y.split('<').join('<');
				app(y);
			});
		}
	});
	function say (r) {
		$('
' + r + '
').appendTo('#conversation-box').fadeIn('slow');
	}
	function app (y) {
		parse(y);
		$('html, body').animate({scrollTop: $(document).height()}, 1500);
	}
	function parse (y) {
		y = y.toLowerCase();
		y = y.split('?').join('');
		y = y.split('!').join('');
		y = y.split('what\'s').join('what is');
		y = y.split('you\'re').join('you are');
		if (y.slice(-1) === '.') {
			y = y.slice(0, y.length - 1);
		}
		random(y);
	}
	function random (y) {
		if (y === 'flip a coin') {
			say(['Heads', 'Tails'][Math.floor(Math.random() * 2)] + '.');
		} else if (y === 'roll a die') {
			say(['One', 'Two', 'Three', 'Four', 'Five', 'Six'][Math.floor(Math.random() * 6)] + '.');
		} else if (y.startsWith('give me a random integer between ') || y.startsWith('give me a random number between ') || y.startsWith('generate a random integer between ') || y.startsWith('generate a random number between ')) {
			if (y.indexOf('give') !== -1) {
				if (y.indexOf('integer') !== -1) {
					y = y.slice(33);
				} else {
					y = y.slice(32);
				}
			} else {
				if (y.indexOf('integer') !== -1) {
					y = y.slice(34);
				} else {
					y = y.slice(33);
				}
			}
			y = y.split(' and ');
			y[0] = parseInt(y[0], 10);
			y[1] = parseInt(y[1], 10);
			if (y[0] !== NaN || y[1] !== NaN) {
				say(Math.floor(Math.random() * (Math.max(y[0], y[1]) - Math.min(y[0], y[1]) + 1) + Math.min(y[0], y[1])));
			} else {
				say('Those aren\'t both integers!');
			}
		} else {
			core(y);
		}
	}
	function core (y) {
		if (y === 'clear' || y === 'clear log' || y === 'clear logs') {
			say('Clearing log…');
			setTimeout(function () {
				$('#conversation-box').fadeOut('slow', function () {
					$('#conversation-box').empty().show();
				});
			}, 1000);
		} else if (y === 'hi' || y === 'hello' || y === 'hey' || y === 'greetings') {
			say(['Hi', 'Hello', 'Hey', 'Greetings'][Math.floor(Math.random() * 4)] + ['.', '!'][Math.floor(Math.random() * 2)]);
		} else if (y === 'what are you' || y === 'who are you' || y === 'what do you do') {
			say('I am Fuchsia. An intelligient virtual personal assistant for the web. I\'m based off of Jared Cubilla\'s Jarvis, but I\'m not voice-powered, which means that I can say write anything I want. You can find my documentation at https://github.com/355over113/fuchsia.');
		} else if (y === 'how are you' || y === 'how do you do' || y === 'how are you doing') {
			say(['I\'m fine.', 'I\'m okay.', 'I\'m great; thanks for asking!', 'I could be doing better.'][Math.floor(Math.random() * 4)]);
		} else if (y.startsWith('you')) {
			say(['Thank you', 'That\'s what I thought', 'We should be talking more about you'][Math.floor(Math.random() * 3)] + ['.', '!'][Math.floor(Math.random() * 2)]);
		} else if (y === 'what is the time' || y === 'what time is it' || y === 'give me the time' || y.split('day').join('date') === 'what is the date' || y.split('day').join('date') === 'what date is it' || y.split('day').join('date') === 'give me the date' || y.split('day').join('date') === 'what is the time and date' || y.split('day').join('date') === 'what is the date and time' || y.split('day').join('date') === 'what is the time and the date' || y.split('day').join('date') === 'what is the date and the time' || y.split('day').join('date') === 'what time and date is it' || y.split('day').join('date') === 'what date and time is it' || y.split('day').join('date') === 'give me the time and date' || y.split('day').join('date') === 'give me the date and time' || y.split('day').join('date') === 'give me the time and the date' || y.split('day').join('date') === 'give me the date and the time' || y.split('day').join('date') === 'when am i') {
			var now = new Date();
			var date, time, suffix;
			y = (y === 'when am i') ? 'tid' : y;
			if (y.indexOf('ti') !== -1) {
				time = [now.getHours(), now.getMinutes(), now.getSeconds()];
				suffix = (time[0] < 12) ? ' AM' : ' PM';
				time[0] = (time[0] <= 12) ? time[0] : time[0] - 12;
				time[1] = (time[1] >= 10) ? time[1] : '0' + time[1];
				time[2] = (time[2] >= 10) ? time[2] : '0' + time[2];
				time = time.join(':');
			}
			if (y.indexOf('d') !== -1) {
				var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
				var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
				var chron = ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
				var tempdate;
				date = [now.getDay(), now.getMonth(), now.getDate(), now.getFullYear()];
				date[0] = days[date[0]];
				date[1] = months[date[1]];
				tempdate = date[2];
				tempdate = (tempdate >= 10) ? tempdate.toString() : '0' + tempdate;
				console.log(tempdate);
				if (tempdate[0] === '1') {
					date[2] += 'th,';
					console.log(date[2]);
				} else {
					date[2] += chron[parseInt(tempdate[1], 10) - 1] + ',';
				}
				date = date.join(' ');
			}
			if (y.indexOf('ti') !== -1 && y.indexOf('d') !== -1) {
				say('It is currently ' + date + ' ' + time + suffix + '.');
			} else if (y.indexOf('time') !== -1) {
				say('The time is ' + time + suffix + '.');
			} else {
				say('The date is ' + date + '.');
			}
		} else if (y === 'toggle goodnight' || y === 'flip goodnight' || y === 'switch goodnight' || y === 'goodnight.toggle();' || y === 'goodnight.toggle()') {
			say('Toggling Goodnight—brace yourself…');
			setTimeout(function () {
				Goodnight.toggle();
			}, 2000);
		} else if (y.startsWith('go to ') || y.startsWith('open ')) {
			if (y.startsWith('go to')) {
				newtab = y.slice(6);
			} else {
				newtab = y.slice(5);
			}
			if (newtab.indexOf('.') === -1) {
				say('Opening ' + newtab + '.com…');
				setTimeout(function () {
					window.open('https://' + newtab + '.com', '_blank');
				}, 1000);
			} else {
				say('Opening ' + newtab + '…');
				setTimeout(function () {
					window.open('https://' + newtab, '_blank');
				}, 1000);
			}
		} else if (y.startsWith('search for ')){
			newtab = y.slice(11);
			say('Searching Google for "' + newtab + '"…');
			setTimeout(function () {
				window.open('https://www.google.ca/search?q=' + newtab.split(' ').join('+'), '_blank');
			}, 1000);
		} else if (y.startsWith('should i watch ') || y.startsWith('should i listen to ')) {
			if (y.startsWith('should i watch ')) {
				y = y.slice(15);
				$.getJSON('https://www.omdbapi.com/?t=' + y + '&y=&plot=full&r=json&tomatoes=true', function (d) {
					var image;
					if (d.Poster !== undefined) {
						image = '
[Show Poster]
';
					}
					if (d.Error === undefined) {
						var reviews = '', sum = 0, count = 0;
						if (d.Type === 'movie') {
							d.Type = 'Film';
						} else if (d.Type === 'series') {
							d.Type = 'TV Series';
						}
						if (d.imdbRating !== 'N/A') {
							reviews += 'IMDb: ' + d.imdbRating + '/10
';
							sum += parseFloat(d.imdbRating, 10) * 10;
							count++;
						}
						if (d.tomatoRating !== 'N/A') {
							reviews += 'Rotten Tomatoes: ' + d.tomatoRating + '/10
';
							sum += parseFloat(d.tomatoRating, 10) * 10;
							count++;
						}
						if (d.Metascore !== 'N/A') {
							reviews += 'Metacritic: ' + d.Metascore + '/100
';
							sum += parseInt(d.Metascore, 10);
							count++;
						}
						reviews += '
Average: ' + Math.round(sum / count) + '%';
						say('Here is what I could find:');
						$('

' + d.Title + '

Starring ' + d.Actors + '

' + d.Rated + '

' + d.Year + ' ' + d.Type + '

' + d.Plot + '
' + image + '
' + reviews + '

').appendTo('#conversation-box').fadeIn('slow');
					} else {
						say('I apologize, but I couldn\'t find that film. I\'ll perform a Google search instead.');
						setTimeout(function () {
							say('Searching Google for "' + y + '"…');
							setTimeout(function () {
								window.open('https://www.google.ca/search?q=' + y.split(' ').join('+'), '_blank');
							}, 2000);
						}, 2000);
					}
				});
			} else {
				$.getJSON('https://api.spotify.com/v1/search?q=' + y.slice(19).split(' ').join('+') + '&type=artist&limit=1', function (d) {
					var image;
					var genres = '';
					if (d.artists.total) {
						for (var i = 0;i < d.artists.items[0].genres.length;i++) {
							d.artists.items[0].genres[i] = d.artists.items[0].genres[i].replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
						}
						if (d.artists.items[0].genres[0] !== undefined) {
							genres = 'Genres: ';
						}
						if (d.artists.items[0].images[0].url !== undefined) {
							image = '
[Show Image]
';
						}
						say('Here is what I could find:');
						$('

' + d.artists.items[0].name + '

Music Artist

' + genres + d.artists.items[0].genres.join(', ') + '
' + image + '
Popularity on Spotify: ' + d.artists.items[0].popularity + '
Followers on Spotify: ' + d.artists.items[0].followers.total + '

').appendTo('#conversation-box').fadeIn('slow');
					} else {
						say('I couldn\'t find that artist. I\'ll perform a Google search for them instead.');
						setTimeout(function () {
							say('Searching Google for "' + y.slice(19) + '"…');
							setTimeout(function () {
								window.open('https://www.google.ca/search?q=' + y.slice(19).split(' ').join('+'), '_blank');
							}, 2000);
						}, 2000);
					}
				});
			}
		} else if (y === 'ayy') {
			say('lmao');
		} else if (y === 'tell me a joke' || y.indexOf('chuck norris') !== -1 || y === 'be funny' || y === 'make me laugh') {
			$.getJSON('http://api.icndb.com/jokes/random', function (d) {
				say(d.value.joke);
			});
		} else {
			fallback(y);
		}
	}
	function fallback (y) {
		say('I apologize, but I wasn\'t sure what you were asking of me. I\'ll perform a Google search instead.');
		setTimeout(function () {
			say('Searching Google for "' + y + '"…');
			setTimeout(function () {
				window.open('https://www.google.ca/search?q=' + y.split(' ').join('+'), '_blank');
			}, 2000);
		}, 2000);
	}
	setTimeout(function () {
		$('#container').fadeIn('slow');
	}, 1000);
});
<|endoftext|>


<commit_before>function execute(params)
{
  if(params.transaction)
  {
    $("#challenge_context").hide();
  }
  else
  {
    // ...
  }

  updateConnections();
  addLinks(params);

  /*
  $(".transaction").each(function(i, obj)
  {
    $(obj).hover(function() {
      updateConnections($(obj).data('id'));
      }
    );
  }
  );
  */

  $("#challenge .transaction.current").attr('style', 'width: 680px').pin();

}

function addLinks(params)
{
  $("#challenge_commands").hide();

  $("#challenge_icon").attr('title', params.i18n.icon_title_toggles);

  $("#challenge_commands").html(
    [
      '' + params.i18n.toggle_firm + '',
      '' + params.i18n.toggle_context + '',
      '' + params.i18n.toggle_transactions + '',
    ].join(" - ")
    );

  $("#challenge_icon").click(function()
  {
     $("#challenge_commands").toggle(200);
  }
  );

  $("#toggle_context").click(function()
    {
      $("#challenge_context").toggle(500);
    }
  );
  $("#toggle_firm").click(function()
    {
      $("#challenge_firm").toggle(500);
    }
  );
  $("#toggle_transactions").click(function()
    {
      $("#challenge_transactions").toggle(500);
    }
  );
  /*
  $(".showjournalentries").click(function()
    {
      $("#journalenties_shown").toggle(200);
      return false;
    }
  );
  */
}

function updateConnections(id)
{
  $(".journalentryrow").each(function(i, obj)
  {
    //console.log("working on " + i);
    if (params.transaction && $(obj).data("transaction-id")==params.transaction && !$(obj).hasClass("excluded"))
    {
      $(obj).addClass('connected');
      $(obj).css('background-color',  $(obj).hasClass('even') ? '#FFFFCC':'#FFFF99');
    }
    else
    {
      $(obj).removeClass('connected');
      $(obj).css('background-color', '');
    }
  }
  );
}

<commit_msg>Fix: added way to remove checks from view (challenges)<commit_after>function execute(params)
{
  if(params.transaction)
  {
    $("#challenge_context").hide();
  }
  else
  {
    // ...
  }

  updateConnections();
  addLinks(params);

  /*
  $(".transaction").each(function(i, obj)
  {
    $(obj).hover(function() {
      updateConnections($(obj).data('id'));
      }
    );
  }
  );
  */

  $("#challenge .transaction.current").attr('style', 'width: 680px').pin();

}

function addLinks(params)
{
  $("#challenge_commands").hide();

  $("#challenge_icon").attr('title', params.i18n.icon_title_toggles);

  $("#challenge_commands").html(
    [
      '' + params.i18n.toggle_firm + '',
      '' + params.i18n.toggle_context + '',
      '' + params.i18n.toggle_transactions + '',
    ].join(" - ")
    );

  $("#challenge_icon").click(function()
  {
     $("#challenge_commands").toggle(200);
  }
  );

  $("#toggle_context").click(function()
    {
      $("#challenge_context").toggle(500);
    }
  );
  $("#toggle_firm").click(function()
    {
      $("#challenge_firm").toggle(500);
    }
  );
  $("#toggle_transactions").click(function()
    {
      $("#challenge_transactions").toggle(500);
    }
  );
  $(".checks").click(function()
	{
	  $(".checks").hide(500);
	  return false;
	}
  );
  $(".transaction").click(function()
	{
	  $(".checks").show(500);
	}
  );

  /*
  $(".showjournalentries").click(function()
    {
      $("#journalenties_shown").toggle(200);
      return false;
    }
  );
  */
}

function updateConnections(id)
{
  $(".journalentryrow").each(function(i, obj)
  {
    //console.log("working on " + i);
    if (params.transaction && $(obj).data("transaction-id")==params.transaction && !$(obj).hasClass("excluded"))
    {
      $(obj).addClass('connected');
      $(obj).css('background-color',  $(obj).hasClass('even') ? '#FFFFCC':'#FFFF99');
    }
    else
    {
      $(obj).removeClass('connected');
      $(obj).css('background-color', '');
    }
  }
  );
}

<|endoftext|>


<commit_before>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	require(["jquery"], function(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}, function(err) {
		alert('Error: ' . err);
	});
};

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if(msg.length === 0) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	update_events();
	return false;
}

/* */
function update_events() {
	require(["jquery"], function(jquery) {
		jquery.get('backend.php', {'msgs':'1', 'start':''+(INFODESK_GLOBAL.last_id+1)}, function(data) {
			var events = JSON.parse(data), event, div;
			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				event = events[i];
				if(event.log_id > INFODESK_GLOBAL.last_id) {
					INFODESK_GLOBAL.last_id = event.log_id;
				}
				div = jquery('#elements .event_container').clone();
				div.find('.log_id').text(''+event.log_id);
				div.find('.date').text(''+event.updated);
				div.find('.msg').text(''+event.msg);
				div.prependTo('#events');
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	INFODESK_GLOBAL.last_id = 0;
	update_events();

	// TODO: Start fetching new events
	function update_events_timer() {
		update_events();
		setTimeout(update_events_timer, 1000);
	}
	update_events_timer();
};

/* EOF */
<commit_msg>Updated<commit_after>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	require(["jquery"], function(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}, function(err) {
		alert('Error: ' . err);
	});
};

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if(msg.length === 0) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	return false;
}

/* */
function update_events() {
	require(["jquery"], function(jquery) {
		jquery.get('backend.php', {'msgs':'1', 'start':''+(INFODESK_GLOBAL.last_id+1)}, function(data) {
			var events = JSON.parse(data), event, div;
			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				event = events[i];
				if(event.log_id > INFODESK_GLOBAL.last_id) {
					INFODESK_GLOBAL.last_id = event.log_id;
				}
				div = jquery('#elements .event_container').clone();
				div.find('.log_id').text(''+event.log_id);
				div.find('.date').text(''+event.updated);
				div.find('.msg').text(''+event.msg);
				div.prependTo('#events');
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	INFODESK_GLOBAL.last_id = 0;
	update_events();

	// TODO: Start fetching new events
	function update_events_timer() {
		update_events();
		setTimeout(update_events_timer, 1000);
	}
	update_events_timer();
};

/* EOF */
<|endoftext|>


<commit_before>/**
 * Created by Owner on 8/25/2015.
 */

var map = null;
var visible = null;
var groundObjects;
var itemObjects;
var monsterObjects;
var structureObjects;
var player = {xPos:0, yPos: 0, symbol: "@", color: "green"};
var menuState = false;
const viewWidth = 51;
const viewHeight = 31;
const mapWidth = 250;
const mapHeight = 250;
const entityViewerName = "entities";

Array.prototype.peek = function() {
    return this[this.length-1];
};

document.addEventListener("keydown", function(e) {
    if (menuState == false)
        move(e);
});

function move(e){
    var keyValue = e.keyCode - 96;
    var xChange = 0;
    var yChange = 0;
    switch (keyValue) {
        case 1:

            xChange -= 1;
            yChange -= 1;
            break;
        case 2:
            yChange -= 1;
            break;
        case 3:
            xChange += 1;
            yChange -= 1;
            break;
        case 4:
            xChange -= 1;
            break;
        case 5:
            break;
        case 6:
            xChange += 1;
            break;
        case 7:
            xChange -= 1;
            yChange += 1;
            break;
        case 8:
            yChange += 1;
            break;
        case 9:
            xChange += 1;
            yChange += 1;
            break;
        default:
            break;
    }

if(map[player.xPos+xChange][player.yPos+yChange].peek().type == "structure" && !checkFlag("pathable", map[player.xPos+xChange][player.yPos+yChange].peek()))
    {
        vision();
        console.log("well fuck");
        return 0;
    }
        map[player.xPos][player.yPos].pop();
        player.xPos += xChange;
        player.yPos += yChange;
        map[player.xPos][player.yPos].push(player);
        vision();

}

function getObjectById(collection, value){
    for(var i = 0; i < collection.length; i++){
        if (collection[i].id == value)
            return collection[i];
    }
    return collection[0];
}

function checkFlag(flag, ob){
    for (var prop in ob.flag){
        if (prop == flag)
            return true;
    }
    return false;
}

function init() {

    $.ajaxSetup({
        async: false
    });

    $.getJSON("json/ground.json", function (json) {
        groundObjects = json;
    });

    $.getJSON("json/items.json", function (json) {
        itemObjects = json;
    });
    $.getJSON("json/monsters.json", function (json) {
        monsterObjects = json;
    });
    $.getJSON("json/structures.json", function (json) {
        structureObjects = json;
    });

    map = [];
    visible = [viewWidth][viewHeight];
    player.xPos = mapWidth/2;
    player.yPos = mapHeight/2;
    var dirt =  getObjectById(groundObjects, "dirt");
    var wall = getObjectById(structureObjects, "wall");
    for (var i = 0; i < 250; i++) {
        map[i]= new Array();
        for (var j = 0; j < 250; j++) {
            map[i][j] = new Array();
            map[i][j].push(dirt);
        }
    }
    map[player.xPos][player.yPos].push(player);
    map[0][0].push(wall);
    map[0][249].push(wall);
    map[249][0].push(wall);
    map[249][249].push(wall);
    //map[130][130].push(wall);
    for(i = 1; i < 249; i++){
        map[i][0].push(wall);
        map[i][249].push(wall);
        map[0][i].push(wall);
        map[249][i].push(wall);
    }
    for(i=10; i < 240; i+=10){
        for(j=10; j < 240; j+=10){
            map[i][j].push(getObjectById(structureObjects, "debug_wall"));
        }
    }

vision();
}

function vision(){
    var leftX, botY;

    if(player.xPos - Math.floor(viewWidth/2) < 0)
    leftX = 0;
    else if(player.xPos + Math.floor(viewWidth/2) >= mapWidth)
    leftX = mapWidth - viewWidth;
    else
    leftX = player.xPos - Math.floor(viewWidth/2);

    if(player.yPos - Math.floor(viewHeight/2) <= 0)
        botY = 0;
    else if(player.yPos + Math.floor(viewHeight/2) >= mapHeight)
        botY = mapHeight - viewHeight -1 ;
    else
        botY = player.yPos - Math.floor(viewHeight/2) -1;
    var buffer = "";
    var prevColor = "";
    for(var y=botY+viewHeight; y>=botY;y--){
        for(var x=leftX; x<leftX+viewWidth; x++){
            if(map[x][y].peek().color == prevColor){
                buffer += map[x][y].peek().symbol;
            }
            else{
                if (prevColor != ""){
                    buffer += "
";
                }
                buffer +=  "
" + map[x][y].peek().symbol;
                prevColor = map[x][y].peek().color;
            }
        }
        buffer += "
";
    }
    document.getElementById(entityViewerName).innerHTML = buffer;
}<commit_msg>Added arrow key support<commit_after>/**
 * Created by Owner on 8/25/2015.
 */

//Global variables
var map = null;
var visible = null;
var groundObjects;
var itemObjects;
var monsterObjects;
var structureObjects;
var player = {xPos:0, yPos: 0, symbol: "@", color: "green"};
var menuState = false;

//Constants (move to separate file eventually)
const viewWidth = 51;
const viewHeight = 31;
const mapWidth = 250;
const mapHeight = 250;
const entityViewerName = "entities";

Array.prototype.peek = function() {
    return this[this.length-1];
};

document.addEventListener("keydown", function(e) {

    //If not in menu, move (only state as of now)
    if (menuState == false)
        move(e);
});

function move(e){

    //ONLY PASS KEYPAD OR ARROWS
    var keyValue = e.keyCode;

    var xChange = 0;
    var yChange = 0;
    switch (keyValue) {
        case 97:
            xChange -= 1;
            yChange -= 1;
            break;
        case 40:
        case 98:
            yChange -= 1;
            break;
        case 99:
            xChange += 1;
            yChange -= 1;
            break;
        case 37:
        case 100:
            xChange -= 1;
            break;
        case 101:
            break;
        case 39:
        case 102:
            xChange += 1;
            break;
        case 103:
            xChange -= 1;
            yChange += 1;
            break;
        case 38:
        case 104:
            yChange += 1;
            break;
        case 105:
            xChange += 1;
            yChange += 1;
            break;
        default:
            break;
    }

if(map[player.xPos+xChange][player.yPos+yChange].peek().type == "structure" && !checkFlag("pathable", map[player.xPos+xChange][player.yPos+yChange].peek()))
    {
        vision();
        console.log("well fuck");
        return 0;
    }
        map[player.xPos][player.yPos].pop();
        player.xPos += xChange;
        player.yPos += yChange;
        map[player.xPos][player.yPos].push(player);
        vision();

}

function getObjectById(collection, value){
    for(var i = 0; i < collection.length; i++){
        if (collection[i].id == value)
            return collection[i];
    }
    return collection[0];
}

function checkFlag(flag, ob){
    for (var prop in ob.flag){
        if (prop == flag)
            return true;
    }
    return false;
}

function init() {

    $.ajaxSetup({
        async: false
    });

    $.getJSON("json/ground.json", function (json) {
        groundObjects = json;
    });

    $.getJSON("json/items.json", function (json) {
        itemObjects = json;
    });
    $.getJSON("json/monsters.json", function (json) {
        monsterObjects = json;
    });
    $.getJSON("json/structures.json", function (json) {
        structureObjects = json;
    });

    map = [];
    visible = [viewWidth][viewHeight];
    player.xPos = mapWidth/2;
    player.yPos = mapHeight/2;
    var dirt =  getObjectById(groundObjects, "dirt");
    var wall = getObjectById(structureObjects, "wall");
    for (var i = 0; i < 250; i++) {
        map[i]= new Array();
        for (var j = 0; j < 250; j++) {
            map[i][j] = new Array();
            map[i][j].push(dirt);
        }
    }
    map[player.xPos][player.yPos].push(player);
    map[0][0].push(wall);
    map[0][249].push(wall);
    map[249][0].push(wall);
    map[249][249].push(wall);
    //map[130][130].push(wall);
    for(i = 1; i < 249; i++){
        map[i][0].push(wall);
        map[i][249].push(wall);
        map[0][i].push(wall);
        map[249][i].push(wall);
    }
    for(i=10; i < 240; i+=10){
        for(j=10; j < 240; j+=10){
            map[i][j].push(getObjectById(structureObjects, "debug_wall"));
        }
    }

vision();
}

function vision(){
    var leftX, botY;

    if(player.xPos - Math.floor(viewWidth/2) < 0)
    leftX = 0;
    else if(player.xPos + Math.floor(viewWidth/2) >= mapWidth)
    leftX = mapWidth - viewWidth;
    else
    leftX = player.xPos - Math.floor(viewWidth/2);

    if(player.yPos - Math.floor(viewHeight/2) <= 0)
        botY = 0;
    else if(player.yPos + Math.floor(viewHeight/2) >= mapHeight)
        botY = mapHeight - viewHeight -1 ;
    else
        botY = player.yPos - Math.floor(viewHeight/2) -1;
    var buffer = "";
    var prevColor = "";
    for(var y=botY+viewHeight; y>=botY;y--){
        for(var x=leftX; x<leftX+viewWidth; x++){
            if(map[x][y].peek().color == prevColor){
                buffer += map[x][y].peek().symbol;
            }
            else{
                if (prevColor != ""){
                    buffer += "
";
                }
                buffer +=  "
" + map[x][y].peek().symbol;
                prevColor = map[x][y].peek().color;
            }
        }
        buffer += "
";
    }
    document.getElementById(entityViewerName).innerHTML = buffer;
}<|endoftext|>


<commit_before>/**
 * [loadJSON create a new instance of XMLHttpRequest and load synchronously]
 * @param  {[String]} url      [link to books.json]
 * @param  {Function} callback [Anonymous callback]
 * @return {[JSON String]}     [returns a JSON String]
 */
function loadJSON (url, callback) {
  // body...
  var xmlhttp = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
      : new ActiveXObject('Microsoft.XMLHTTP');

  if (xmlhttp.overrideMimeType) {
    xmlhttp.overrideMimeType("application/json");
  };

  xmlhttp.open('GET', url, false);

  // Stores a function that is called whenever the readyState property changes
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      /**
       * Required use of an anonymous callback as .open will NOT return a value
       * but simply returns undefined in asynchronous mode
       */
      callback(xmlhttp.responseText);
    };
  };
  xmlhttp.send(null);
};

/**
 * [load call loadJSON() with two argument a url and a callback]
 * @return {[Object]} [JSON Object]
 */
function load (url) {
  // body...
  // var url           = "http://localhost:8000/jasmine/books.json"
  var jsonresponse  = undefined;

  // call to loadJSON() with anonymous callback
  loadJSON(
    url,
    function (response) {
      // parse JSON string into object
      jsonresponse = JSON.parse(response);
    }
    // Arrow Function (ES6): parse JSON string into object
    // response => jsonresponse = JSON.parse(response)
  )
  return jsonresponse;
};

// Class definition / constructor
var Index = function () {
  // arguments.callee property contains the currently executing function.
  // The ‘if’ statement checks whether ‘this’ is an instance of the object and returns one if necessary
  if (!(this instanceof arguments.callee)) {
    return new Index();
  };

  this.index;
};

/**
 * [createIndex {{Method}} creates an index from the argument]
 * @param  {[JSON Object]} filePath [argument passed when this method is called]
 * @return {[Object]}       [returns list of words with indexes]
 */
Index.prototype.createIndex = function(filePath) {
  var file     = load(filePath)
    , posIndex = {}
    , posArr   = []
    , j        = 0
    , words
    , i;

  file.forEach(function(elem, index) {
    /**
     * converts value of elem to a string, removes Object key, whitespaces and other
     * text formatting.
     */
    words = JSON.stringify(elem)
      .replace(/\btitle\b|\btext\b|,(?=\s)|[:.{}""]/g, '')
      .replace(/,(?=\S)/g, ' ')
      .split(' ');
    for (i = 0; i < words.length; i++) {
      if (posIndex.hasOwnProperty(words[i])) {
        posArr = posIndex[words[i]];
        if (posArr.indexOf(index) === -1) {
          posArr.push(index);
          posIndex[words[i]] = posArr;
          console.log(posIndex[words[i]])
        }
      } else {
        posIndex[words[i]] = [index];
      }
    }
  });
  this.index = posIndex;
};
<commit_msg>feat (method): add getIndex and searchIndex method<commit_after>/**
 * [loadJSON create a new instance of XMLHttpRequest and load synchronously]
 * @param  {[String]} url      [link to books.json]
 * @param  {Function} callback [Anonymous callback]
 * @return {[JSON String]}     [returns a JSON String]
 */
function loadJSON (url, callback) {
  // body...
  var xmlhttp = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
      : new ActiveXObject('Microsoft.XMLHTTP');

  if (xmlhttp.overrideMimeType) {
    xmlhttp.overrideMimeType("application/json");
  };

  xmlhttp.open('GET', url, false);

  // Stores a function that is called whenever the readyState property changes
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      /**
       * Required use of an anonymous callback as .open will NOT return a value
       * but simply returns undefined in asynchronous mode
       */
      callback(xmlhttp.responseText);
    };
  };
  xmlhttp.send(null);
};

/**
 * [load call loadJSON() with two argument a url and a callback]
 * @return {[Object]} [JSON Object]
 */
function load (url) {
  // body...
  // var url           = "http://localhost:8000/jasmine/books.json"
  var jsonresponse  = undefined;

  // call to loadJSON() with anonymous callback
  loadJSON(
    url,
    function (response) {
      // parse JSON string into object
      jsonresponse = JSON.parse(response);
    }
    // Arrow Function (ES6): parse JSON string into object
    // response => jsonresponse = JSON.parse(response)
  )
  return jsonresponse;
};

// Class definition / constructor
var Index = function () {
  // arguments.callee property contains the currently executing function.
  // The ‘if’ statement checks whether ‘this’ is an instance of the object and returns one if necessary
  if (!(this instanceof arguments.callee)) {
    return new Index();
  };

  this.index;
};

/**
 * [createIndex {{Method}} creates an index from the argument]
 * @param  {[JSON Object]} filePath [argument passed when this method is called]
 * @return {[Object]}       [returns list of words with indexes]
 */
Index.prototype.createIndex = function(filePath) {
  var file     = load(filePath)
    , posIndex = {}
    , posArr   = []
    , j        = 0
    , words
    , i;

  file.forEach(function(elem, index) {
    /**
     * converts value of elem to a string, removes Object key, whitespaces and other
     * text formatting.
     */
    words = JSON.stringify(elem)
      .replace(/\btitle\b|\btext\b|,(?=\s)|[:.{}""]/g, '')
      .replace(/,(?=\S)/g, ' ')
      .split(' ');
    for (i = 0; i < words.length; i++) {
      if (posIndex.hasOwnProperty(words[i])) {
        posArr = posIndex[words[i]];
        if (posArr.indexOf(index) === -1) {
          posArr.push(index);
          posIndex[words[i]] = posArr;
          console.log(posIndex[words[i]])
        }
      } else {
        posIndex[words[i]] = [index];
      }
    }
  });
  this.index = posIndex;
};

/**
 * [getIndex contains words and indexes]
 * @return {[Object]} [returns words and indexes of 'filePath' argument]
 */
Index.prototype.getIndex = function() {
  return this.index;
};

Index.prototype.searchIndex = function(terms) {
  var fn
    , i
    , j
    , k
    , len
    , posArr = []
    , line_num
    , location
    , locations;

    fn = this.index;
    !(typeof terms === 'object')
      ? console.log(location = arguments)
        : console.log(location = terms)

    for (i in fn) {
      for (j = 0; j < location.length; j++) {
        if (i === location[j])
          for (k = 0; k < fn[i].length; k++) {
            posArr.push(fn[i][k]);
          };
      }
     // console.log(fn[i])
    }
    return posArr;
};

<|endoftext|>


<commit_before>#!/usr/bin/env node
const pkg = require('../package');
const { execSync } = require('child_process');

const nextVersion = `${pkg.version.split('-dev').shift()}-dev.${+new Date()}`;
execSync(`npm version ${nextVersion} --no-git-tag-version`);
<commit_msg>Adjusting date format<commit_after>#!/usr/bin/env node
const pkg = require('../package');
const moment = require('moment');
const { execSync } = require('child_process');

const nextVersion = `${pkg.version.split('-dev').shift()}-dev.${+moment().format('YYYYMMDD')}`;
execSync(`npm version ${nextVersion} --no-git-tag-version`);
<|endoftext|>


<commit_before>import game, { initialGameState } from "src/reducers/Game.js";
import { applyMoveAction } from "src/actions/GameActions.js";
import { computerMoveAction } from "src/actions/GameActions.js";
import { startNextMatchAction } from "src/actions/GameActions.js";
import { resetGameAction } from "src/actions/GameActions.js";
import { setGameModeAction } from "src/actions/GameActions.js";
import { VS_HUMAN, EASY, MEDIUM, HARD } from "src/reducers/Game.js";

import Immutable from "immutable";

describe("game reducer", () => {

  it("should exist", () => {
    game.should.exist;
  });

  it("should be a function", () => {
    game.should.be.function;
  });

  describe("action handling", () => {

    var state;

    beforeEach(function() {
      state = initialGameState().toJS();
      Math.random = () => 0.99;
    });

    it("should be able to hadle RESET_GAME action", () => {
      state.gameGrid = [["","o",""],
                        ["o","o","x"],
                        ["x","x","x"]];
      state.gameOver = true;
      state = game(Immutable.fromJS(state), resetGameAction());
      state.should.be.eql(initialGameState());
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(VS_HUMAN)).toJS();
      state.gameMode.should.be.equal(VS_HUMAN);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(EASY)).toJS();
      state.gameMode.should.be.equal(EASY);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(MEDIUM)).toJS();
      state.gameMode.should.be.equal(MEDIUM);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(HARD)).toJS();
      state.gameMode.should.be.equal(HARD);
    });

  });

  describe("gameplay handling", () => {

    var state,
        previousState;

    beforeEach(function() {
      state = initialGameState().toJS();
    });

    it("should change grid cell if specified", () => {
			previousState = state;
      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:0})).toJS();
      state.should.be.not.equal(previousState);
      state.currentTurn.should.be.equal("o");
      state.gameGrid.should.be.eql([["x","",""],
                                    ["","",""],
                                    ["","",""]]);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","x",""],
                        ["o","o",""],
                        ["","",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:2})).toJS();
      state.should.be.not.equal(previousState);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","x",""],
                        ["o","o",""],
                        ["x","",""]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
      });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","o",""],
                        ["o","o",""],
                        ["x","x",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","o",""],
                        ["","o","x"],
                        ["x","",""]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","o","o"],
                        ["","o","x"],
                        ["x","",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:0})).toJS();
      state.should.be.not.equal(previousState);
      state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","","o"],
                        ["","x",""],
                        ["x","","o"]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
      state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in diagonal", () => {
      state.gameGrid = [["x","o","o"],
                        ["o","",""],
                        ["x","","x"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in diagonal", () => {
      state.gameGrid = [["x","","o"],
                        ["x","",""],
                        ["o","","x"]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);
      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle tie", () => {
      state.gameGrid = [["x","o","x"],
                        ["o","x",""],
                        ["o","x","o"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o);
      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x);
    });

    it("should be able to handle tie", () => {
      state.gameGrid = [["x","o","x"],
                        ["o","x","x"],
                        ["o","","o"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o);
      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x);
    });

    it("should be able to start next match", () => {
      let initialState = initialGameState().toJS();
      initialState.victoryStatistics = state.victoryStatistics;
      initialState.gameMode = state.gameMode;
      initialState.AI.playingX = !state.AI.playingX;

      state = game(Immutable.fromJS(state), startNextMatchAction()).toJS();

      state.should.be.eql(initialState);
    });

  });

  describe("AI - best moves", () => {

    var state,
        originalMathRandom = Math.random;

    beforeEach(function() {
      state = initialGameState().toJS();
      Math.random = () => 0.99;
    });

    afterEach(function() {
      Math.random = originalMathRandom;
    });

    it("should be able to make turn", () => {

      state.gameMode = EASY;

      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:0})).toJS();
      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.currentTurn.should.be.equal("x");
      state.gameGrid.should.be.not.eql([["x","",""],
                                        ["","",""],
                                        ["","",""]]);
    });

    it("should be able to make turn", () => {
      state.gameMode = EASY;
      state.AI.playingX = true;
      state.gameGrid = [["x","",""],
                        ["","o","o"],
                        ["","","x"]];

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.currentTurn.should.be.equal("o");
      state.gameGrid.should.be.eql([["x","",""],
                                    ["x","o","o"],
                                    ["","","x"]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.gameGrid[0][0] = "x";
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","",""],
                                    ["","o",""],
                                    ["","",""]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.AI.playingX = true;
      state.gameGrid = [["x","",""],
                        ["","o",""],
                        ["x","o",""]];

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameOver.should.be.equal(true);
      state.gameGrid.should.be.eql([["x","",""],
                                    ["x","o",""],
                                    ["x","o",""]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.gameGrid = [["x","",""],
                        ["","o",""],
                        ["x","",""]];
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","",""],
                                    ["o","o",""],
                                    ["x","",""]]);
    });

  });

  describe("AI - random moves", () => {

    var state,
        originalMathRandom = Math.random;

    beforeEach(function() {
      state = initialGameState().toJS();
      Math.random = () => 0;
    });

    afterEach(function() {
      Math.random = originalMathRandom;
    });

    it("should make random turns sometimes", () => {
      state.gameMode = EASY;
      state.gameGrid[0][0] = "x";
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","o",""],
                                    ["","",""],
                                    ["","",""]]);
    });

    it("should make random turns sometimes", () => {
      state.gameMode = EASY;
      state.gameGrid = [["x","o","x"],
                        ["o","x",""],
                        ["","",""]];
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","o","x"],
                                    ["o","x","o"],
                                    ["","",""]]);
    });

  });

});
<commit_msg>Refactor: change functions to ES6 arrow functions<commit_after>import game, { initialGameState } from "src/reducers/Game.js";
import { applyMoveAction } from "src/actions/GameActions.js";
import { computerMoveAction } from "src/actions/GameActions.js";
import { startNextMatchAction } from "src/actions/GameActions.js";
import { resetGameAction } from "src/actions/GameActions.js";
import { setGameModeAction } from "src/actions/GameActions.js";
import { VS_HUMAN, EASY, MEDIUM, HARD } from "src/reducers/Game.js";

import Immutable from "immutable";

describe("game reducer", () => {

  it("should exist", () => {
    game.should.exist;
  });

  it("should be a function", () => {
    game.should.be.function;
  });

  describe("action handling", () => {

    var state;

    beforeEach(() => {
      state = initialGameState().toJS();
      Math.random = () => 0.99;
    });

    it("should be able to hadle RESET_GAME action", () => {
      state.gameGrid = [["","o",""],
                        ["o","o","x"],
                        ["x","x","x"]];
      state.gameOver = true;
      state = game(Immutable.fromJS(state), resetGameAction());
      state.should.be.eql(initialGameState());
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(VS_HUMAN)).toJS();
      state.gameMode.should.be.equal(VS_HUMAN);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(EASY)).toJS();
      state.gameMode.should.be.equal(EASY);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(MEDIUM)).toJS();
      state.gameMode.should.be.equal(MEDIUM);
    });

    it("should be able set game mode", () => {
      state = game(Immutable.fromJS(state), setGameModeAction(HARD)).toJS();
      state.gameMode.should.be.equal(HARD);
    });

  });

  describe("gameplay handling", () => {

    var state,
        previousState;

    beforeEach(() => {
      state = initialGameState().toJS();
    });

    it("should change grid cell if specified", () => {
			previousState = state;
      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:0})).toJS();
      state.should.be.not.equal(previousState);
      state.currentTurn.should.be.equal("o");
      state.gameGrid.should.be.eql([["x","",""],
                                    ["","",""],
                                    ["","",""]]);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","x",""],
                        ["o","o",""],
                        ["","",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:2})).toJS();
      state.should.be.not.equal(previousState);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","x",""],
                        ["o","o",""],
                        ["x","",""]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
      });

    it("should be able to handle victory if 3 'x' or 'o' in one row", () => {
      state.gameGrid = [["x","o",""],
                        ["o","o",""],
                        ["x","x",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","o",""],
                        ["","o","x"],
                        ["x","",""]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","o","o"],
                        ["","o","x"],
                        ["x","",""]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:0})).toJS();
      state.should.be.not.equal(previousState);
      state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in one column", () => {
      state.gameGrid = [["x","","o"],
                        ["","x",""],
                        ["x","","o"]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
      state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in diagonal", () => {
      state.gameGrid = [["x","o","o"],
                        ["o","",""],
                        ["x","","x"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x-1);
    });

    it("should be able to handle victory if 3 'x' or 'o' in diagonal", () => {
      state.gameGrid = [["x","","o"],
                        ["x","",""],
                        ["o","","x"]];
      state.currentTurn = "o";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);
      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o-1);
    });

    it("should be able to handle tie", () => {
      state.gameGrid = [["x","o","x"],
                        ["o","x",""],
                        ["o","x","o"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:1,y:2})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o);
      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x);
    });

    it("should be able to handle tie", () => {
      state.gameGrid = [["x","o","x"],
                        ["o","x","x"],
                        ["o","","o"]];
      state.currentTurn = "x";
			previousState = state;

      state = game(Immutable.fromJS(state), applyMoveAction({x:2,y:1})).toJS();
      state.should.be.not.equal(previousState);
			state.gameOver.should.be.equal(true);

      previousState.victoryStatistics.o
        .should.be.equal(state.victoryStatistics.o);
      previousState.victoryStatistics.x
        .should.be.equal(state.victoryStatistics.x);
    });

    it("should be able to start next match", () => {
      let initialState = initialGameState().toJS();
      initialState.victoryStatistics = state.victoryStatistics;
      initialState.gameMode = state.gameMode;
      initialState.AI.playingX = !state.AI.playingX;

      state = game(Immutable.fromJS(state), startNextMatchAction()).toJS();

      state.should.be.eql(initialState);
    });

  });

  describe("AI - best moves", () => {

    var state,
        originalMathRandom = Math.random;

    beforeEach(() => {
      state = initialGameState().toJS();
      Math.random = () => 0.99;
    });

    afterEach(() => {
      Math.random = originalMathRandom;
    });

    it("should be able to make turn", () => {

      state.gameMode = EASY;

      state = game(Immutable.fromJS(state), applyMoveAction({x:0,y:0})).toJS();
      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.currentTurn.should.be.equal("x");
      state.gameGrid.should.be.not.eql([["x","",""],
                                        ["","",""],
                                        ["","",""]]);
    });

    it("should be able to make turn", () => {
      state.gameMode = EASY;
      state.AI.playingX = true;
      state.gameGrid = [["x","",""],
                        ["","o","o"],
                        ["","","x"]];

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.currentTurn.should.be.equal("o");
      state.gameGrid.should.be.eql([["x","",""],
                                    ["x","o","o"],
                                    ["","","x"]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.gameGrid[0][0] = "x";
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","",""],
                                    ["","o",""],
                                    ["","",""]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.AI.playingX = true;
      state.gameGrid = [["x","",""],
                        ["","o",""],
                        ["x","o",""]];

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameOver.should.be.equal(true);
      state.gameGrid.should.be.eql([["x","",""],
                                    ["x","o",""],
                                    ["x","o",""]]);
    });

    it("should choose best turn possible", () => {
      state.gameMode = EASY;
      state.gameGrid = [["x","",""],
                        ["","o",""],
                        ["x","",""]];
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","",""],
                                    ["o","o",""],
                                    ["x","",""]]);
    });

  });

  describe("AI - random moves", () => {

    var state,
        originalMathRandom = Math.random;

    beforeEach(() => {
      state = initialGameState().toJS();
      Math.random = () => 0;
    });

    afterEach(() => {
      Math.random = originalMathRandom;
    });

    it("should make random turns sometimes", () => {
      state.gameMode = EASY;
      state.gameGrid[0][0] = "x";
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","o",""],
                                    ["","",""],
                                    ["","",""]]);
    });

    it("should make random turns sometimes", () => {
      state.gameMode = EASY;
      state.gameGrid = [["x","o","x"],
                        ["o","x",""],
                        ["","",""]];
      state.currentTurn = "o";

      state = game(Immutable.fromJS(state), computerMoveAction(state)).toJS();

      state.gameGrid.should.be.eql([["x","o","x"],
                                    ["o","x","o"],
                                    ["","",""]]);
    });

  });

});
<|endoftext|>


<commit_before>// Global killswitch
if (isJsEnabled()) {
  addLoadEvent(uploadAutoAttach);
}

/**
 * Attaches the upload behaviour to the upload form.
 */
function uploadAutoAttach() {
  var acdb = [];
  var inputs = document.getElementsByTagName('input');
  for (i = 0; input = inputs[i]; i++) {
    if (input && hasClass(input, 'upload')) {
      var uri = input.value;
      var button = input.id.substr(5);
      var wrapper = button + '-wrapper';
      var hide = button + '-hide';
      var upload = new jsUpload(uri, button, wrapper, hide);
    }
  }
}

/**
 * JS upload object.
 */
function jsUpload(uri, button, wrapper, hide) {
  var upload = this;
  this.button = button;
  this.wrapper = wrapper;
  this.hide = hide;
  redirectFormButton(uri, $(button), this);
}

/**
 * Handler for the form redirection submission.
 */
jsUpload.prototype.onsubmit = function () {
  var hide = $(this.hide);
  // Insert progressbar and stretch to take the same space.
  this.progress = new progressBar('uploadprogress');
  this.progress.setProgress(-1, 'Uploading file...');
  this.progress.element.style.width = '28em';
  this.progress.element.style.height = hide.offsetHeight +'px';
  hide.parentNode.insertBefore(this.progress.element, hide);
  // Hide file form (cannot use display: none, this mysteriously aborts form
  // submission in Konqueror)
  hide.style.position = 'absolute';
  hide.style.left = '-2000px';
}

/**
 * Handler for the form redirection completion.
 */
jsUpload.prototype.oncomplete = function (data) {
  // Remove progressbar
  removeNode(this.progress);
  this.progress = null;
  // Replace form and re-attach behaviour
  $(this.wrapper).innerHTML = data;
  uploadAutoAttach();
}
<commit_msg>- Patch #41385 by Thox: made the upload.module work again.<commit_after>// Global killswitch
if (isJsEnabled()) {
  addLoadEvent(uploadAutoAttach);
}

/**
 * Attaches the upload behaviour to the upload form.
 */
function uploadAutoAttach() {
  var acdb = [];
  var inputs = document.getElementsByTagName('input');
  for (i = 0; input = inputs[i]; i++) {
    if (input && hasClass(input, 'upload')) {
      var uri = input.value;
      // Extract the button ID based on a subtring of the input name: edit[foo][bar] -> foo-bar
      var button = input.name.substr(5, input.name.length - 6).replace('][', '-');
      var wrapper = button + '-wrapper';
      var hide = button + '-hide';
      var upload = new jsUpload(uri, button, wrapper, hide);
    }
  }
}

/**
 * JS upload object.
 */
function jsUpload(uri, button, wrapper, hide) {
  var upload = this;
  this.button = button;
  this.wrapper = wrapper;
  this.hide = hide;
  redirectFormButton(uri, $(button), this);
}

/**
 * Handler for the form redirection submission.
 */
jsUpload.prototype.onsubmit = function () {
  var hide = $(this.hide);
  // Insert progressbar and stretch to take the same space.
  this.progress = new progressBar('uploadprogress');
  this.progress.setProgress(-1, 'Uploading file...');
  this.progress.element.style.width = '28em';
  this.progress.element.style.height = hide.offsetHeight +'px';
  hide.parentNode.insertBefore(this.progress.element, hide);
  // Hide file form (cannot use display: none, this mysteriously aborts form
  // submission in Konqueror)
  hide.style.position = 'absolute';
  hide.style.left = '-2000px';
}

/**
 * Handler for the form redirection completion.
 */
jsUpload.prototype.oncomplete = function (data) {
  // Remove progressbar
  removeNode(this.progress);
  this.progress = null;
  // Replace form and re-attach behaviour
  $(this.wrapper).innerHTML = data;
  uploadAutoAttach();
}
<|endoftext|>


<commit_before>'use strict';
const assert = require('assert');

describe('Welcome page, button functionality', function () {
    browser.url('/');

  it('should be able to grab the page title', function () {
  	var title = browser.getTitle();
  	assert.equal(title, 'Pomodoro');
  });

  it('should have a paragraph tag to display the remaining countdown time', function () {
    var timer = browser.element('.display-count-down');
    assert(timer.isExisting(''));
  });

  it('start button should be hidden on click of start button', function () {
    browser.click('.start-button');
    assert.equal(('.start-button').isDisplayed(), false);
  });

  it('pause button should be hidden on click of pause button', function () {
    browser.click('.pause-button');
    assert.isVisible('.pause-button');
  });

  it('resume button should be hidden on click of resume button', function () {
    browser.click('.resume-button');
    assert.property(('.resume-button').hide(), true);
  });

  it('pause button enabled on click of start button', function () {
    browser.click('.start-button');
    var buttonStatus = browser.isEnabled('.pause-button');
    assert.equal(buttonStatus, true);
  });

  it('should have an input for setting break time', function () {
    var pomodoroTimeInput = browser.element('#focus-time-input');
    assert(pomodoroTimeInput.isExisting(''));
  });

  it('should have an input for setting break time', function () {
    var breakTimeInput = browser.element('#break-time-input');
    assert(breakTimeInput.isExisting(''));
  });

  it('should register the value of the input for setting pomodoro focus time', function () {
    var pomodoroTimeInput = browser.element('#focus-time-input');
    pomodoroTimeInput.setValue(25);
    assert.equal(pomodoroTimeInput.getValue(), 25);
  });

  it('should register the value of the input for setting pomodoro break time', function () {
    var breakTimeInput = browser.element('#break-time-input');
    breakTimeInput.setValue(5);
    assert.equal(breakTimeInput.getValue(), 5);
  });
});
<commit_msg>Update<commit_after>'use strict';

const assert = require('assert');

describe('Welcome page, button functionality', function () {
    browser.url('/');

  it('should be able to grab the page title', function () {
  	var title = browser.getTitle();
  	assert.equal(title, 'Pomodoro');
  });

  it('should have a paragraph tag to display the remaining countdown time', function () {
    var timer = browser.element('.display-count-down');
    assert(timer.isExisting(''));
  });

  it('start button should be hidden on click of start button', function () {
    browser.click('.start-button');
    assert.equal(('.start-button').isDisplayed(), false);
  });

  it('pause button should be hidden on click of pause button', function () {
    browser.click('.pause-button');
    assert.isVisible('.pause-button');
  });

  it('resume button should be hidden on click of resume button', function () {
    browser.click('.resume-button');
    assert.property(('.resume-button').hide(), true);
  });

  it('pause button enabled on click of start button', function () {
    browser.click('.start-button');
    var buttonStatus = browser.isEnabled('.pause-button');
    assert.equal(buttonStatus, true);
  });

  it('should have an input for setting break time', function () {
    var pomodoroTimeInput = browser.element('#focus-time-input');
    assert(pomodoroTimeInput.isExisting(''));
  });

  it('should have an input for setting break time', function () {
    var breakTimeInput = browser.element('#break-time-input');
    assert(breakTimeInput.isExisting(''));
  });

  it('should register the value of the input for setting pomodoro focus time', function () {
    var pomodoroTimeInput = browser.element('#focus-time-input');
    pomodoroTimeInput.setValue(25);
    assert.equal(pomodoroTimeInput.getValue(), 25);
  });

  it('should register the value of the input for setting pomodoro break time', function () {
    var breakTimeInput = browser.element('#break-time-input');
    breakTimeInput.setValue(5);
    assert.equal(breakTimeInput.getValue(), 5);
  });
});
<|endoftext|>


<commit_before>module.exports = Array.isArray
<commit_msg>* enhance the compatibility of isArray<commit_after>var toString = Object.prototype.toString;

module.exports = Array.isArray ? Array.isArray : function isArray(obj) {
    return toString.call(obj) === "[object Array]";
  };
<|endoftext|>


<commit_before>var require = function (file, cwd) {
    var resolved = require.resolve(file, cwd || '/');
    var mod = require.modules[resolved];
    if (!mod) throw new Error(
        'Failed to resolve module ' + file + ', tried ' + resolved
    );
    var res = mod._cached ? mod._cached : mod();
    return res;
}
var __require = require;

require.paths = [];
require.modules = {};
require.extensions = [".js",".coffee"];

require.resolve = (function () {
    var core = {
        'assert': true,
        'events': true,
        'fs': true,
        'path': true,
        'vm': true
    };

    return function (x, cwd) {
        if (!cwd) cwd = '/';

        if (core[x]) return x;
        var path = require.modules.path();
        var y = cwd || '.';

        if (x.match(/^(?:\.\.?\/|\/)/)) {
            var m = loadAsFileSync(path.resolve(y, x))
                || loadAsDirectorySync(path.resolve(y, x));
            if (m) return m;
        }

        var n = loadNodeModulesSync(x, y);
        if (n) return n;

        throw new Error("Cannot find module '" + x + "'");

        function loadAsFileSync (x) {
            if (require.modules[x]) {
                return x;
            }

            for (var i = 0; i < require.extensions.length; i++) {
                var ext = require.extensions[i];
                if (require.modules[x + ext]) return x + ext;
            }
        }

        function loadAsDirectorySync (x) {
            x = x.replace(/\/+$/, '');
            var pkgfile = x + '/package.json';
            if (require.modules[pkgfile]) {
                var pkg = require.modules[pkgfile]();
                var b = pkg.browserify;
                if (typeof b === 'object' && b.main) {
                    var m = loadAsFileSync(path.resolve(x, b.main));
                    if (m) return m;
                }
                else if (typeof b === 'string') {
                    var m = loadAsFileSync(path.resolve(x, b));
                    if (m) return m;
                }
                else if (pkg.main) {
                    var m = loadAsFileSync(path.resolve(x, pkg.main));
                    if (m) return m;
                }
            }

            return loadAsFileSync(x + '/index');
        }

        function loadNodeModulesSync (x, start) {
            var dirs = nodeModulesPathsSync(start);
            for (var i = 0; i < dirs.length; i++) {
                var dir = dirs[i];
                var m = loadAsFileSync(dir + '/' + x);
                if (m) return m;
                var n = loadAsDirectorySync(dir + '/' + x);
                if (n) return n;
            }

            var m = loadAsFileSync(x);
            if (m) return m;
        }

        function nodeModulesPathsSync (start) {
            var parts;
            if (start === '/') parts = [ '' ];
            else parts = path.normalize(start).split('/');

            var dirs = [];
            for (var i = parts.length - 1; i >= 0; i--) {
                if (parts[i] === 'node_modules') continue;
                var dir = parts.slice(0, i + 1).join('/') + '/node_modules';
                dirs.push(dir);
            }

            return dirs;
        }
    };
})();

require.alias = function (from, to) {
    var path = require.modules.path();
    var res = null;
    try {
        res = require.resolve(from + '/package.json', '/');
    }
    catch (err) {
        res = require.resolve(from, '/');
    }
    var basedir = path.dirname(res);

    var keys = Object_keys(require.modules);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (key.slice(0, basedir.length + 1) === basedir + '/') {
            var f = key.slice(basedir.length);
            require.modules[to + f] = require.modules[basedir + f];
        }
        else if (key === basedir) {
            require.modules[to] = require.modules[basedir];
        }
    }
};

var Object_keys = Object.keys || function (obj) {
    var res = [];
    for (var key in obj) res.push(key)
    return res;
};

if (typeof process === 'undefined') process = {};

if (!process.nextTick) process.nextTick = function (fn) {
    setTimeout(fn, 0);
};

if (!process.title) process.title = 'browser';

if (!process.binding) process.binding = function (name) {
    if (name === 'evals') return require('vm')
    else throw new Error('No such module')
};

if (!process.cwd) process.cwd = function () { return '.' };

require.modules["path"] = function () {
    var module = { exports : {} };
    var exports = module.exports;
    var __dirname = ".";
    var __filename = "path";

    var require = function (file) {
        return __require(file, ".");
    };

    require.resolve = function (file) {
        return __require.resolve(name, ".");
    };

    require.modules = __require.modules;
    __require.modules["path"]._cached = module.exports;

    (function () {
        function filter (xs, fn) {
    var res = [];
    for (var i = 0; i < xs.length; i++) {
        if (fn(xs[i], i, xs)) res.push(xs[i]);
    }
    return res;
}

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length; i >= 0; i--) {
    var last = parts[i];
    if (last == '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// Regex to split a filename into [*, dir, basename, ext]
// posix version
var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/;

// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
    resolvedAbsolute = false;

for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) {
  var path = (i >= 0)
      ? arguments[i]
      : process.cwd();

  // Skip empty and invalid entries
  if (typeof path !== 'string' || !path) {
    continue;
  }

  resolvedPath = path + '/' + resolvedPath;
  resolvedAbsolute = path.charAt(0) === '/';
}

// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)

// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};

// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = path.charAt(0) === '/',
    trailingSlash = path.slice(-1) === '/';

// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  if (path && trailingSlash) {
    path += '/';
  }

  return (isAbsolute ? '/' : '') + path;
};

// posix version
exports.join = function() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return exports.normalize(filter(paths, function(p, index) {
    return p && typeof p === 'string';
  }).join('/'));
};

exports.dirname = function(path) {
  var dir = splitPathRe.exec(path)[1] || '';
  var isWindows = false;
  if (!dir) {
    // No dirname
    return '.';
  } else if (dir.length === 1 ||
      (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) {
    // It is just a slash or a drive letter with a slash
    return dir;
  } else {
    // It is a full dirname, strip trailing slash
    return dir.substring(0, dir.length - 1);
  }
};

exports.basename = function(path, ext) {
  var f = splitPathRe.exec(path)[2] || '';
  // TODO: make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
};

exports.extname = function(path) {
  return splitPathRe.exec(path)[3] || '';
};
;
    }).call(module.exports);

    __require.modules["path"]._cached = module.exports;
    return module.exports;
};

(function () {
    var module = { exports : {} };
    var exports = module.exports;
    var __dirname = "/";
    var __filename = "//home/fs/work/jscode/knock-knock/src";

    var require = function (file) {
        return __require(file, "/");
    };
    require.modules = __require.modules;

    (function() {
  var Validation;
  var __slice = Array.prototype.slice, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  Validation = (function() {
    function Validation() {}
    Validation.prototype.addRules = function() {
      var observable, validators;
      observable = arguments[0], validators = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      observable.errors = ko.observableArray();
      observable.isValid = ko.dependentObservable(function() {
        return observable.errors().length === 0;
      });
      return observable.subscribe(__bind(function() {
        return this.subscription.apply(this, [observable].concat(__slice.call(validators)));
      }, this));
    };
    Validation.prototype.subscription = function() {
      var observable, validator, validators, _i, _len, _results;
      observable = arguments[0], validators = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      observable.errors.removeAll();
      _results = [];
      for (_i = 0, _len = validators.length; _i < _len; _i++) {
        validator = validators[_i];
        _results.push(!validator.validate(observable) ? observable.errors.push(validator.message) : void 0);
      }
      return _results;
    };
    return Validation;
  })();
  exports.Validation = Validation;
}).call(this);
;
})();
<commit_msg>removed old build file<commit_after><|endoftext|>