<commit_before>
const bets = [
    {
        "id": "simon",
        "name": "Simon Kruse",
        "deadpool": ["cersei", "theon", "mountain", "melisandre", "euron"]
    }, {
        "id": "anders",
        "name": "Anders",
        "deadpool": ["mountain", "cersei", "grey", "jorah", "tormund"]
    }, {
        "id": "jan",
        "name": "Jan",
        "deadpool": ["jorah", "euron", "melisandre", "tormund", "mountain"]
    }, {
        "id": "emil",
        "name": "Emil",
        "deadpool": ["petyr", "ellaria", "euron", "mountain", "melisandre"]
    }, {
        "id": "lone",
        "name": "Lone",
        "deadpool": ["cersei", "ilyn", "euron", "melisandre", "theon"]
    }, {
        "id": "tina",
        "name": "Tina",
        "deadpool": ["jamie", "petyr", "mountain", "sansa", "melisandre"]
    }, {
        "id": "namit",
        "name": "Namit",
        "deadpool": ["yara", "viserion", "euron", "petyr", "grey"]
    }
]

const characters = [
    {
        id: 'cersei',
        name: 'Cersei Lannister',
        picture: 'cersei.webp',
        status: 'alive'
    }, {
        id: 'mountain',
        name: 'Gregor Clegane
(The Mountain)',
        picture: 'gregor-clegane.jpg',
        status: 'alive'
    }, {
        id: 'theon',
        name: 'Theon Greyjoy',
        picture: 'theon-greyjoy.webp',
        status: 'alive'
    }, {
        id: 'melisandre',
        name: 'Melisandre',
        picture: 'melisandre.webp',
        status: 'alive'
    }, {
        id: 'euron',
        name: 'Euron Greyjoy',
        picture: 'euron-greyjoy.jpg',
        status: 'alive'
    }, {
        id: 'hound',
        name: 'Sandor Clegane
(The Hound)',
        picture: 'The_Hound.webp',
        status: 'alive'
    }, {
        id: 'grey',
        name: 'Grey Worm',
        picture: 'grey-worm.webp',
        status: 'alive'
    }, {
        id: 'jorah',
        name: 'Jorah Mormont',
        picture: 'jorah-mormont.webp',
        status: 'alive'
    }, {
        id: 'tormund',
        name: 'Tormund Giantsbane',
        picture: 'tormund-giantsbane.webp',
        status: 'alive'
    }, {
        id: 'petyr',
        name: 'Petyr Baelish',
        picture: 'petyr-baelish.webp',
        status: 'alive'
    }, {
        id: 'ellaria',
        name: 'Ellaria Sand',
        picture: 'ellaria-sand.webp',
        status: 'alive'
    }, {
        id: 'ilyn',
        name: 'Ilyn Payne',
        picture: 'ilyn-payne.jpg',
        status: 'alive'
    }, {
        id: 'jamie',
        name: 'Jaime Lannister',
        picture: 'jaime-lannister.webp',
        status: 'alive'
    }, {
        id: 'sansa',
        name: 'Sansa Stark',
        picture: 'sansa-stark.webp',
        status: 'alive'
    }, {
        id: 'viserion',
        name: 'Viserion',
        picture: 'viserion.jpg',
        status: 'alive'
    }, {
        id: 'yara',
        name: 'Yara Greyjoy',
        picture: 'yara-greyjoy.webp',
        status: 'alive'
    }
]

const container = document.getElementsByClassName("container")[0]

//Adds owners name and div's for persons in the deadpool
const addName = function (person) {
    const motherDiv = `

${person.name}

`
    container.insertAdjacentHTML('beforeend', motherDiv)
}

//Adds a person with pic and name, and colors the pic if the person is dead
const addPerson = function (person, ownerId) {
    const deadpoolCon = document.getElementById(ownerId)
    const motherDiv = `

${person.name}

`
    deadpoolCon.insertAdjacentHTML('beforeend', motherDiv)
}

//Creates a new array with the deadpool array filled with the full character objects
const fullBets = bets.map(bet => {
    return {
        id: bet.id,
        name: bet.name,
        deadpool: characters.filter((char) => bet.deadpool.find((deadpoolCharacter) => deadpoolCharacter === char.id))
    }
})

fullBets.forEach(bet => {
    addName(bet)
    const userDeadpool = document.getElementById(bet.name)
    bet
        .deadpool
        .forEach(deadpoolPerson => {
            addPerson(deadpoolPerson, bet.id)
        })
})
<commit_msg>bet update<commit_after>
const bets = [
    {
        "id": "simon",
        "name": "Simon Kruse",
        "deadpool": ["cersei", "theon", "mountain", "melisandre", "euron"]
    }, {
        "id": "anders",
        "name": "Anders",
        "deadpool": ["mountain", "cersei", "grey", "jorah", "tormund"]
    }, {
        "id": "jan",
        "name": "Jan",
        "deadpool": ["jorah", "euron", "melisandre", "tormund", "mountain"]
    }, {
        "id": "emil",
        "name": "Emil",
        "deadpool": ["petyr", "ellaria", "euron", "mountain", "melisandre"]
    }, {
        "id": "lone",
        "name": "Lone",
        "deadpool": ["cersei", "ilyn", "euron", "melisandre", "theon"]
    }, {
        "id": "tina",
        "name": "Tina",
        "deadpool": ["jamie", "petyr", "euron", "sansa", "melisandre"]
    }, {
        "id": "namit",
        "name": "Namit",
        "deadpool": ["yara", "viserion", "euron", "petyr", "grey"]
    }
]

const characters = [
    {
        id: 'cersei',
        name: 'Cersei Lannister',
        picture: 'cersei.webp',
        status: 'alive'
    }, {
        id: 'mountain',
        name: 'Gregor Clegane
(The Mountain)',
        picture: 'gregor-clegane.jpg',
        status: 'alive'
    }, {
        id: 'theon',
        name: 'Theon Greyjoy',
        picture: 'theon-greyjoy.webp',
        status: 'alive'
    }, {
        id: 'melisandre',
        name: 'Melisandre',
        picture: 'melisandre.webp',
        status: 'alive'
    }, {
        id: 'euron',
        name: 'Euron Greyjoy',
        picture: 'euron-greyjoy.jpg',
        status: 'alive'
    }, {
        id: 'hound',
        name: 'Sandor Clegane
(The Hound)',
        picture: 'The_Hound.webp',
        status: 'alive'
    }, {
        id: 'grey',
        name: 'Grey Worm',
        picture: 'grey-worm.webp',
        status: 'alive'
    }, {
        id: 'jorah',
        name: 'Jorah Mormont',
        picture: 'jorah-mormont.webp',
        status: 'alive'
    }, {
        id: 'tormund',
        name: 'Tormund Giantsbane',
        picture: 'tormund-giantsbane.webp',
        status: 'alive'
    }, {
        id: 'petyr',
        name: 'Petyr Baelish',
        picture: 'petyr-baelish.webp',
        status: 'alive'
    }, {
        id: 'ellaria',
        name: 'Ellaria Sand',
        picture: 'ellaria-sand.webp',
        status: 'alive'
    }, {
        id: 'ilyn',
        name: 'Ilyn Payne',
        picture: 'ilyn-payne.jpg',
        status: 'alive'
    }, {
        id: 'jamie',
        name: 'Jaime Lannister',
        picture: 'jaime-lannister.webp',
        status: 'alive'
    }, {
        id: 'sansa',
        name: 'Sansa Stark',
        picture: 'sansa-stark.webp',
        status: 'alive'
    }, {
        id: 'viserion',
        name: 'Viserion',
        picture: 'viserion.jpg',
        status: 'alive'
    }, {
        id: 'yara',
        name: 'Yara Greyjoy',
        picture: 'yara-greyjoy.webp',
        status: 'alive'
    }
]

const container = document.getElementsByClassName("container")[0]

//Adds owners name and div's for persons in the deadpool
const addName = function (person) {
    const motherDiv = `

${person.name}

`
    container.insertAdjacentHTML('beforeend', motherDiv)
}

//Adds a person with pic and name, and colors the pic if the person is dead
const addPerson = function (person, ownerId) {
    const deadpoolCon = document.getElementById(ownerId)
    const motherDiv = `

${person.name}

`
    deadpoolCon.insertAdjacentHTML('beforeend', motherDiv)
}

//Creates a new array with the deadpool array filled with the full character objects
const fullBets = bets.map(bet => {
    return {
        id: bet.id,
        name: bet.name,
        deadpool: characters.filter((char) => bet.deadpool.find((deadpoolCharacter) => deadpoolCharacter === char.id))
    }
})

fullBets.forEach(bet => {
    addName(bet)
    const userDeadpool = document.getElementById(bet.name)
    bet
        .deadpool
        .forEach(deadpoolPerson => {
            addPerson(deadpoolPerson, bet.id)
        })
})
<|endoftext|>


<commit_before>$(document).ready(function() {
	var apiEndpoint = "answers";
	var currentPage = 1;
	var pageSize = 100;
	var sort = ByCreationDate;
	$("#blaze-api-key-field").focus();

	InitSiteAPIKeyAutocomplete();

	$(".blaze-logo").click(function()
	{
		$("table tr").remove();
		$(".blaze-header").fadeIn();
		$(".site-api-key-form").fadeIn();
		$("nav").fadeOut();
	});
	$("#select-answers").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Answers");
		apiEndpoint = 'answers';
	});
	$("#select-comments").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Comments");
		apiEndpoint = 'comments';
	});
	$("#select-questions").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Questions");
		apiEndpoint = 'questions';
	});
	$(".blaze-fetch-items").click(function() {
		RefreshData();
	});
	$(".refresh-current-data-button").click(function()
	{
		var oldHTML = $(this).html();
		$(this).html("working...");

		$("table tr").remove();

		RefreshData(function()
			{
				$(".refresh-current-data-button").html(oldHTML);
			});
	});
	$(document).keypress(function(e) {
		if(e.which == 13) {
			RefreshData();
		}
	});
	function RefreshData(f)
	{
		var site = $("#blaze-api-key-field").val();

		var oldButtonText = $(".blaze-fetch-items").html();
		$(".blaze-fetch-items").html("Loading...");

		console.log(site);

		var argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!LeJQlFEfIbsDDTG1lReSJX";
		if (apiEndpoint == "questions") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q7pHZaD2SW58N2KuVqkwvB5";
		if (apiEndpoint == "comments") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q3IqX*j)mxF9SKNRz3tb5yK";
		var url = "https://api.stackexchange.com/2.2/" + apiEndpoint;
		$.ajax({
			type: "GET",
			url: url,
			data: argString,
			success: function(data)
			{
				console.log(data["items"]);

				$(".blaze-header").fadeOut();
				$(".site-api-key-form").fadeOut();

				$("nav").fadeIn();

				var items = data["items"];

				items.sort(sort);

				jQuery.each(items, function(index, item) {
					if (apiEndpoint == 'questions')
					{
						$("table").append(RenderQuestion(item));
					}
					else if (apiEndpoint == 'answers')
					{
						$("table").append(RenderAnswer(item));
					}
					else if (apiEndpoint == 'comments')
					{
						$("table").append(RenderComment(item));
					}

				});

				$(".blaze-fetch-items").html(oldButtonText);

				$("div.alert.alert-danger").remove();

				if (typeof f == "function") f();
			},
			error: function(data)
			{
				string = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
				string = string + data.responseJSON["error_message"].charAt(0).toUpperCase() + data.responseJSON["error_message"].slice(1);
				string = string + '
';
				$("div.alert.alert-danger").remove();
				$(".site-api-key-form").prepend(string);
				$(".blaze-fetch-items").html(oldButtonText);
			}
		});
	}

	// Array sorting functions:

	function ByLength(a, b){
		var aLength = a["body"].length;
		var bLength = b["body"].length;
		return ((aLength < bLength) ? -1 : ((aLength > bLength) ? 1 : 0));
	}
	function ByCreationDate(a, b){
		var aDate = a["creation_date"];
		var bDate = b["creation_date"];
		return ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));
	}

	$("#sort-by-newest-creation").click(function() {
		sort = ByCreationDate;
		$("table tr").remove();
		$("#current-sort-indicator").html("Working...");
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Newest");
			});
	});
	$("#sort-by-shortest-length").click(function() {
		sort = ByLength;
		console.log($("#current-sort-indicator"));
		$("table tr").remove();
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Shortest");
			});
	});
	$(".flag").click(function() {
		var postLink = $(this).attr("postLink");
		var argString = "url=" + postLink;
		$.ajax({
		        type: "POST",
		 	url: "http://erwaysoftware.com/posttochat.php",
		 	data: argString,
		 	success: function(data) {
		 		// worked, yay, maybe add success or something?
			},
		});
	});

	//Rendering things

	function RenderAnswer(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + '

';
		string = string + item["body"];
		string = string + 'flag';
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		string = string + '

'; //flag
		return string;
	}
	function RenderQuestion(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + "
";
		for (var i = 0; i < item["tags"].length; i++) {
			string = string + '' + item["tags"][i] + ' ';
		};
		string = string + "";
		string = string + '

';
		string = string + item["body"];
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		return string;
	}
	function RenderComment(item)
	{
		var string = '

';
		if (item["score"] != "0") string = string + item["score"];
		string = string + '

';
		string = string + '';
		string = string + item["body"];
		string = string + ' - ';
		string = string + item["owner"]["display_name"];
		if (item["owner"]["user_type"] == 'moderator') string = string + " ♦";
		string = string + ' ';
		string = string + '

';
		return string;
	}

	//Autocomplete things

	function InitSiteAPIKeyAutocomplete()
	{
		$.ajax({
			type: "GET",
			url: "https://api.stackexchange.com/2.2/sites",
			data: "pagesize=1000&filter=!mszzl.y_MC",
			success: function(data)
			{
				var items = data["items"];

				var siteApiKeys = [];

				jQuery.each(items, function(index, item) {
					siteApiKeys.push(item["api_site_parameter"]);
				});

				$("#blaze-api-key-field").autocomplete({
					source: siteApiKeys
				});
			},
			error: function(data) {}
		});
	}
});
<commit_msg>that'd do it...<commit_after>$(document).ready(function() {
	var apiEndpoint = "answers";
	var currentPage = 1;
	var pageSize = 100;
	var sort = ByCreationDate;
	$("#blaze-api-key-field").focus();

	InitSiteAPIKeyAutocomplete();

	$(".blaze-logo").click(function()
	{
		$("table tr").remove();
		$(".blaze-header").fadeIn();
		$(".site-api-key-form").fadeIn();
		$("nav").fadeOut();
	});
	$("#select-answers").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Answers");
		apiEndpoint = 'answers';
	});
	$("#select-comments").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Comments");
		apiEndpoint = 'comments';
	});
	$("#select-questions").click(function()
	{
		$(".blaze-fetch-items").html("Fetch Questions");
		apiEndpoint = 'questions';
	});
	$(".blaze-fetch-items").click(function() {
		RefreshData();
	});
	$(".refresh-current-data-button").click(function()
	{
		var oldHTML = $(this).html();
		$(this).html("working...");

		$("table tr").remove();

		RefreshData(function()
			{
				$(".refresh-current-data-button").html(oldHTML);
			});
	});
	$(document).keypress(function(e) {
		if(e.which == 13) {
			RefreshData();
		}
	});
	function RefreshData(f)
	{
		var site = $("#blaze-api-key-field").val();

		var oldButtonText = $(".blaze-fetch-items").html();
		$(".blaze-fetch-items").html("Loading...");

		console.log(site);

		var argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!LeJQlFEfIbsDDTG1lReSJX";
		if (apiEndpoint == "questions") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q7pHZaD2SW58N2KuVqkwvB5";
		if (apiEndpoint == "comments") argString = "page=" + currentPage + "&pagesize=" + pageSize + "&key=" + "p3YZ1qDutpcBd7Bte2mcDw((" + "&site=" + site + "&order=" + "desc" + "&sort=" + "creation" + "&filter=" + "!)Q3IqX*j)mxF9SKNRz3tb5yK";
		var url = "https://api.stackexchange.com/2.2/" + apiEndpoint;
		$.ajax({
			type: "GET",
			url: url,
			data: argString,
			success: function(data)
			{
				console.log(data["items"]);

				$(".blaze-header").fadeOut();
				$(".site-api-key-form").fadeOut();

				$("nav").fadeIn();

				var items = data["items"];

				items.sort(sort);

				jQuery.each(items, function(index, item) {
					if (apiEndpoint == 'questions')
					{
						$("table").append(RenderQuestion(item));
					}
					else if (apiEndpoint == 'answers')
					{
						$("table").append(RenderAnswer(item));
					}
					else if (apiEndpoint == 'comments')
					{
						$("table").append(RenderComment(item));
					}

				});

				$(".blaze-fetch-items").html(oldButtonText);

				$("div.alert.alert-danger").remove();

				if (typeof f == "function") f();
			},
			error: function(data)
			{
				string = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
				string = string + data.responseJSON["error_message"].charAt(0).toUpperCase() + data.responseJSON["error_message"].slice(1);
				string = string + '
';
				$("div.alert.alert-danger").remove();
				$(".site-api-key-form").prepend(string);
				$(".blaze-fetch-items").html(oldButtonText);
			}
		});
	}

	// Array sorting functions:

	function ByLength(a, b){
		var aLength = a["body"].length;
		var bLength = b["body"].length;
		return ((aLength < bLength) ? -1 : ((aLength > bLength) ? 1 : 0));
	}
	function ByCreationDate(a, b){
		var aDate = a["creation_date"];
		var bDate = b["creation_date"];
		return ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));
	}

	$("#sort-by-newest-creation").click(function() {
		sort = ByCreationDate;
		$("table tr").remove();
		$("#current-sort-indicator").html("Working...");
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Newest");
			});
	});
	$("#sort-by-shortest-length").click(function() {
		sort = ByLength;
		console.log($("#current-sort-indicator"));
		$("table tr").remove();
		RefreshData(function()
			{
				$("#current-sort-indicator").html("Shortest");
			});
	});
	$(".flag").click(function() {
		var postLink = $(this).attr("postLink");
		var argString = "url=" + postLink;
		$.ajax({
		    type: "POST",
		 	url: "http://erwaysoftware.com/blaze/posttochat.php",
		 	data: argString,
		 	success: function(data) {
		 		// worked, yay, maybe add success or something?
			},
		});
	});

	//Rendering things

	function RenderAnswer(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + '

';
		string = string + item["body"];
		string = string + 'flag';
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		string = string + '

'; //flag
		return string;
	}
	function RenderQuestion(item)
	{
		var string = '

';
		string = string + item["score"];
		string = string + '

';
		string = string + item["title"];
		string = string + '';
		string = string + "
";
		for (var i = 0; i < item["tags"].length; i++) {
			string = string + '' + item["tags"][i] + ' ';
		};
		string = string + "";
		string = string + '

';
		string = string + item["body"];
		string = string + '
posted by ';
		var owner = item["owner"];
		string = string + '';
		string = string + owner["display_name"];
		if (owner['user_type'] == 'moderator') string = string + ' ♦';
		string = string + ' '
		string = string + '';
		string = string + '

';
		return string;
	}
	function RenderComment(item)
	{
		var string = '

';
		if (item["score"] != "0") string = string + item["score"];
		string = string + '

';
		string = string + '';
		string = string + item["body"];
		string = string + ' - ';
		string = string + item["owner"]["display_name"];
		if (item["owner"]["user_type"] == 'moderator') string = string + " ♦";
		string = string + ' ';
		string = string + '

';
		return string;
	}

	//Autocomplete things

	function InitSiteAPIKeyAutocomplete()
	{
		$.ajax({
			type: "GET",
			url: "https://api.stackexchange.com/2.2/sites",
			data: "pagesize=1000&filter=!mszzl.y_MC",
			success: function(data)
			{
				var items = data["items"];

				var siteApiKeys = [];

				jQuery.each(items, function(index, item) {
					siteApiKeys.push(item["api_site_parameter"]);
				});

				$("#blaze-api-key-field").autocomplete({
					source: siteApiKeys
				});
			},
			error: function(data) {}
		});
	}
});
<|endoftext|>


<commit_before>var vger =  angular.module('vger', []);

vger.run(['$rootScope', function ($rootScope) {
    // set visibility state for elements
    $rootScope.loading = true;
    $rootScope.messageVisible = false;
    $rootScope.mapVisible = true;
    $rootScope.spreadMenu = false;

    // set map on screen
    $rootScope.screenMap = L.map('map', {zoomControl: false}).locate({setView: true, maxZoom: 15});
    L.control.zoom({position: 'bottomleft'}).addTo($rootScope.screenMap);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo($rootScope.screenMap);

    // check if running as phonegap app
    var phonegapApp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
    if (phonegapApp) {
        document.addEventListener("deviceready", onDeviceReady, false);

        function onDeviceReady() {
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }

        function onMenuKeyDown() {
            $rootScope.$apply(function(){
                $rootScope.spreadMenu = !$rootScope.spreadMenu;
            });
        }
    }
}]);

vger.controller('ListCtrl', ['$rootScope', '$scope', '$http', function ($rootScope, $scope, $http) {

    var markIcon = L.icon({
        iconUrl: 'icon.svg',
        iconSize:     [32, 48], // size of the icon
        shadowSize:   [40, 48], // size of the shadow
        iconAnchor:   [16, 48], // point of the icon which will correspond to marker's location
        popupAnchor:  [0, -52] // point from which the popup should open relative to the iconAnchor
    });

    $scope.currentLocationMarkers = new Array();

	// get wikipedia entries for given position
	var getWikipediaEntries = function(lat, lng) {
        // store bound limits to zoom the map and show all entries
        var southWestBound = [0, 0],
            northEastBound = [0, 0];

        $rootScope.loading = true;
        angular.forEach($scope.entries, function(value, index) {
            value.marker.closePopup().unbindPopup().setOpacity(0);
        });
        $scope.entries = [];
        //get list of closer entries
        $http.jsonp('http://en.wikipedia.org/w/api.php?format=json&action=query&list=geosearch&gsradius=10000&gscoord=' + lat + '|' + lng + '&gslimit=20&callback=JSON_CALLBACK').success(function(data) {
            $scope.entries = data.query.geosearch;
            var ids = "";
            angular.forEach($scope.entries, function(value, index) {
                ids += value.pageid + "|";
                value.popUp = L.popup().setContent('
' + value.title + '
');
                value.marker = L.marker([value.lat, value.lon], {icon: markIcon});
                value.marker.addTo($rootScope.screenMap).bindPopup(value.popUp);
                // update bound limits
                if (index == 0) {
                    southWestBound[0] = value.lat;
                    southWestBound[1] = value.lon;
                    northEastBound[0] = value.lat;
                    northEastBound[1] = value.lon;
                } else {
                    southWestBound[0] = value.lat < southWestBound[0] ? value.lat : southWestBound[0];
                    southWestBound[1] = value.lon < southWestBound[1] ? value.lon : southWestBound[1];
                    northEastBound[0] = value.lat > northEastBound[0] ? value.lat : northEastBound[0];
                    northEastBound[1] = value.lon > northEastBound[1] ? value.lon : northEastBound[1];
                }
            });
            ids = ids.slice(0, - 1);
            // get thumbnails
            $http.jsonp('http://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=thumbnail&pithumbsize=60&pilimit=20&pageids=' + ids + '&callback=JSON_CALLBACK').success(function(data) {
                angular.forEach($scope.entries, function(value, index) {
                    value.thumbnail = data.query.pages[value.pageid].thumbnail;
                });
                //get excerpts
                $http.jsonp('http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=250&exlimit=20&exintro=&pageids=' + ids + '&callback=JSON_CALLBACK').success(function(data) {
                    angular.forEach($scope.entries, function(entry, index) {
                        var content = '
' + entry.title + '
'
                                      + data.query.pages[entry.pageid].extract + '
'
                                      + 'Read more';
                        if (entry.thumbnail) {
                            content = '' + content;
                        }
                        entry.popUp.setContent(content);
                    });
                    $rootScope.loading = false;
                });
            });
            // set inital zoom to show all entries
            $rootScope.screenMap.fitBounds([southWestBound, northEastBound], {padding: [16, 24]});
        });
    };

    // load wikipedia entries for current location
    $scope.reload = function() {
        $rootScope.localization = $rootScope.screenMap.getCenter();
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
    };

    // set map to current location
    $scope.currentLocation = function() {
        $rootScope.screenMap.locate({setView: true, zoom: 14, maxZoom: 15});
    };

    // open pop-up of a selected entry
    $scope.openPopUp = function(index) {
        $scope.entries[index].marker.openPopup();
        $scope.showMap();
    };

    // locations to visit if current location not available
    var visitLocations = [
        { name: 'La Habana', position: [23.13986, -82.38445] },
        { name: 'Pompeii', position: [40.7512, 14.4869] },
        { name: 'Tiananmen Square', position: [39.9021, 116.3917] },
    ];

    // set the map to any of the visitLocations
    $scope.visitLocation = function() {
        $scope.location = visitLocations[Math.floor(Math.random() * visitLocations.length)];
        $scope.messages.redirect = true;
        $rootScope.screenMap.setView($scope.location.position, 14);
        $rootScope.localization = $rootScope.screenMap.getCenter();
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
        $rootScope.messageVisible = true;
    }
    $rootScope.screenMap.on('locationerror', function() {
        $scope.visitLocation();
    });

    // set the current location on the map
    var personIcon = L.icon({
        iconUrl: 'person.svg',
        iconSize:     [32, 48], // size of the icon
        iconAnchor:   [16, 48], // point of the icon which will correspond to marker's location
        popupAnchor:  [0, -52] // point from which the popup should open relative to the iconAnchor
    });
    $rootScope.screenMap.on('locationfound', function() {
        $rootScope.localization = $rootScope.screenMap.getCenter();
        // make the previous markers invisible
        if ($scope.currentLocationMarkers.length > 0) {
            $scope.currentLocationMarkers[$scope.currentLocationMarkers.length - 1].setOpacity(0);
        }
        var currentLocationMark = L.marker([$rootScope.localization.lat, $rootScope.localization.lng], {icon: personIcon});
        currentLocationMark.addTo($rootScope.screenMap);
        $scope.currentLocationMarkers.push(currentLocationMark);
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
    });

    $scope.showMap = function() {
        window.scrollTo(0,0);
        $rootScope.mapVisible = true;
    }

    $scope.showList = function() {
        window.scrollTo(0,0);
        $rootScope.mapVisible = false;
    }

    $scope.logo = function() {
        $scope.messages.about = true;
        $rootScope.messageVisible = true;
    }

    // user facing messages
    $scope.messages = {
        redirect: false,
        about: false
    };

    $scope.clearMessage = function() {
        $rootScope.messageVisible = false;
        angular.forEach($scope.messages, function(message){
            message = false;
        });
    }

}]);<commit_msg>scroll top on phonegap menu button<commit_after>var vger =  angular.module('vger', []);

vger.run(['$rootScope', function ($rootScope) {
    // set visibility state for elements
    $rootScope.loading = true;
    $rootScope.messageVisible = false;
    $rootScope.mapVisible = true;
    $rootScope.spreadMenu = false;

    // set map on screen
    $rootScope.screenMap = L.map('map', {zoomControl: false}).locate({setView: true, maxZoom: 15});
    L.control.zoom({position: 'bottomleft'}).addTo($rootScope.screenMap);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo($rootScope.screenMap);

    // check if running as phonegap app
    var phonegapApp = document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1;
    if (phonegapApp) {
        document.addEventListener("deviceready", onDeviceReady, false);

        function onDeviceReady() {
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }

        function onMenuKeyDown() {
            $rootScope.$apply(function(){
                !$rootScope.spreadMenu && window.scrollTo(0,0);
                $rootScope.spreadMenu = !$rootScope.spreadMenu;
            });
        }
    }
}]);

vger.controller('ListCtrl', ['$rootScope', '$scope', '$http', function ($rootScope, $scope, $http) {

    var markIcon = L.icon({
        iconUrl: 'icon.svg',
        iconSize:     [32, 48], // size of the icon
        shadowSize:   [40, 48], // size of the shadow
        iconAnchor:   [16, 48], // point of the icon which will correspond to marker's location
        popupAnchor:  [0, -52] // point from which the popup should open relative to the iconAnchor
    });

    $scope.currentLocationMarkers = new Array();

	// get wikipedia entries for given position
	var getWikipediaEntries = function(lat, lng) {
        // store bound limits to zoom the map and show all entries
        var southWestBound = [0, 0],
            northEastBound = [0, 0];

        $rootScope.loading = true;
        angular.forEach($scope.entries, function(value, index) {
            value.marker.closePopup().unbindPopup().setOpacity(0);
        });
        $scope.entries = [];
        //get list of closer entries
        $http.jsonp('http://en.wikipedia.org/w/api.php?format=json&action=query&list=geosearch&gsradius=10000&gscoord=' + lat + '|' + lng + '&gslimit=20&callback=JSON_CALLBACK').success(function(data) {
            $scope.entries = data.query.geosearch;
            var ids = "";
            angular.forEach($scope.entries, function(value, index) {
                ids += value.pageid + "|";
                value.popUp = L.popup().setContent('
' + value.title + '
');
                value.marker = L.marker([value.lat, value.lon], {icon: markIcon});
                value.marker.addTo($rootScope.screenMap).bindPopup(value.popUp);
                // update bound limits
                if (index == 0) {
                    southWestBound[0] = value.lat;
                    southWestBound[1] = value.lon;
                    northEastBound[0] = value.lat;
                    northEastBound[1] = value.lon;
                } else {
                    southWestBound[0] = value.lat < southWestBound[0] ? value.lat : southWestBound[0];
                    southWestBound[1] = value.lon < southWestBound[1] ? value.lon : southWestBound[1];
                    northEastBound[0] = value.lat > northEastBound[0] ? value.lat : northEastBound[0];
                    northEastBound[1] = value.lon > northEastBound[1] ? value.lon : northEastBound[1];
                }
            });
            ids = ids.slice(0, - 1);
            // get thumbnails
            $http.jsonp('http://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=thumbnail&pithumbsize=60&pilimit=20&pageids=' + ids + '&callback=JSON_CALLBACK').success(function(data) {
                angular.forEach($scope.entries, function(value, index) {
                    value.thumbnail = data.query.pages[value.pageid].thumbnail;
                });
                //get excerpts
                $http.jsonp('http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exchars=250&exlimit=20&exintro=&pageids=' + ids + '&callback=JSON_CALLBACK').success(function(data) {
                    angular.forEach($scope.entries, function(entry, index) {
                        var content = '
' + entry.title + '
'
                                      + data.query.pages[entry.pageid].extract + '
'
                                      + 'Read more';
                        if (entry.thumbnail) {
                            content = '' + content;
                        }
                        entry.popUp.setContent(content);
                    });
                    $rootScope.loading = false;
                });
            });
            // set inital zoom to show all entries
            $rootScope.screenMap.fitBounds([southWestBound, northEastBound], {padding: [16, 24]});
        });
    };

    // load wikipedia entries for current location
    $scope.reload = function() {
        $rootScope.localization = $rootScope.screenMap.getCenter();
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
    };

    // set map to current location
    $scope.currentLocation = function() {
        $rootScope.screenMap.locate({setView: true, zoom: 14, maxZoom: 15});
    };

    // open pop-up of a selected entry
    $scope.openPopUp = function(index) {
        $scope.entries[index].marker.openPopup();
        $scope.showMap();
    };

    // locations to visit if current location not available
    var visitLocations = [
        { name: 'La Habana', position: [23.13986, -82.38445] },
        { name: 'Pompeii', position: [40.7512, 14.4869] },
        { name: 'Tiananmen Square', position: [39.9021, 116.3917] },
    ];

    // set the map to any of the visitLocations
    $scope.visitLocation = function() {
        $scope.location = visitLocations[Math.floor(Math.random() * visitLocations.length)];
        $scope.messages.redirect = true;
        $rootScope.screenMap.setView($scope.location.position, 14);
        $rootScope.localization = $rootScope.screenMap.getCenter();
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
        $rootScope.messageVisible = true;
    }
    $rootScope.screenMap.on('locationerror', function() {
        $scope.visitLocation();
    });

    // set the current location on the map
    var personIcon = L.icon({
        iconUrl: 'person.svg',
        iconSize:     [32, 48], // size of the icon
        iconAnchor:   [16, 48], // point of the icon which will correspond to marker's location
        popupAnchor:  [0, -52] // point from which the popup should open relative to the iconAnchor
    });
    $rootScope.screenMap.on('locationfound', function() {
        $rootScope.localization = $rootScope.screenMap.getCenter();
        // make the previous markers invisible
        if ($scope.currentLocationMarkers.length > 0) {
            $scope.currentLocationMarkers[$scope.currentLocationMarkers.length - 1].setOpacity(0);
        }
        var currentLocationMark = L.marker([$rootScope.localization.lat, $rootScope.localization.lng], {icon: personIcon});
        currentLocationMark.addTo($rootScope.screenMap);
        $scope.currentLocationMarkers.push(currentLocationMark);
        getWikipediaEntries($rootScope.localization.lat, $rootScope.localization.lng);
    });

    $scope.showMap = function() {
        window.scrollTo(0,0);
        $rootScope.mapVisible = true;
    }

    $scope.showList = function() {
        window.scrollTo(0,0);
        $rootScope.mapVisible = false;
    }

    $scope.logo = function() {
        $scope.messages.about = true;
        $rootScope.messageVisible = true;
    }

    // user facing messages
    $scope.messages = {
        redirect: false,
        about: false
    };

    $scope.clearMessage = function() {
        $rootScope.messageVisible = false;
        angular.forEach($scope.messages, function(message){
            message = false;
        });
    }

}]);<|endoftext|>


<commit_before> function Ctrl($scope) {
   $scope.templates =
     [ { name: 'template1.html', url: 'template1.html'},
       { name: 'template2.html', url: 'template2.html'} ];
   $scope.template = $scope.templates[0];
 }<commit_msg>kerpow<commit_after> function Ctrl($scope) {
   $scope.templates =
     [ { name: 'template1.html', url: 'pages/about.html'},
       { name: 'template2.html', url: 'template2.html'} ];
   $scope.template = $scope.templates[0];
 }<|endoftext|>


<commit_before>(function(){

/******************************************
             Audio player
******************************************/

function createPlayer(file){
    $('#audio').remove();
    $('#player-hook').append('<audio id="audio" src=""></audio>');
    if (window.webkitURL) {
        console.log('webkit');
        var url = window.webkitURL.createObjectURL(file);
    } else {
        var url = window.URL.createObjectURL(file);
    }
    console.log(url);
    $('#audio')[0].src = url;
    console.log(file.name);
}

// play/pause
function playPause(){
    var playing = !document.getElementById('audio').paused
    if (playing == true){
        document.getElementById('audio').pause();
        $('.play-pause').removeClass('playing');
    } else {
        document.getElementById('audio').play();
        $('.play-pause').addClass('playing');
    };
};

// skip forward
function skip(direction){
    var audio = document.getElementById('audio');
    if (direction == "forwards"){
        audio.currentTime = audio.currentTime+1.5;
    } else if (direction == "backwards") {
        audio.currentTime = audio.currentTime-1.5;
    }
}

// speed
function speed(newSpeed){
    console.log(typeof newSpeed);
    var min = 0.5;
    var max = 2;
    var step = 0.25;
    var newSpeedNumber;
    var currentSpeed = document.getElementById('audio').playbackRate;
    if ((newSpeed == "up") && (currentSpeed < max)){
        newSpeedNumber = currentSpeed+step;
    } else if ((newSpeed == "down") && (currentSpeed > min)){
        newSpeedNumber = currentSpeed-step;
    } else if (newSpeed == "reset"){
        newSpeedNumber = 1;
    } else if (typeof newSpeed == 'number') {
        newSpeedNumber = newSpeed;
    }
    if (typeof(newSpeedNumber) != "undefined") {
        document.getElementById('audio').playbackRate = newSpeedNumber;
        document.getElementById('slider3').value = newSpeedNumber;
    }
}

function initAudioJS(){
    audiojs.events.ready(function() {
      audiojs.createAll();
    });
}

function resetPlayer(){
    location.reload();
}

/******************************************
               Text editor
******************************************/

function adjustPlayerWidth(){
    var cntrls = $('.controls');
    console.log ("Window width: "+$(window).width()+"\nControls offset: "+cntrls.offset().left+"\nControls width: "+cntrls.width()+"\nTitle width: "+$('.title').width() );

    var gap = $(window).width() - (cntrls.offset().left + cntrls.width() + $('.title').outerWidth() );
    $('.scrubber').width( $('.scrubber').width()+gap );
   console.log(gap);
}

function toggleAbout(){
    $('.title').toggleClass('active');
    $('.about').toggleClass('active');
}

function adjustEditorHeight(){
    $('.textbox-container').height( window.innerHeight - 36 );
}

/******************************************
                Timestamp
******************************************/

// get timestamp
// var timestamp;
function getTimestamp(){
    // get timestap
    var time = document.getElementById('audio').currentTime
    var minutes = Math.floor(time / 60);
    var seconds = ("0" + Math.round( time - minutes * 60 ) ).slice(-2);
    return minutes+":"+seconds;
};

function insertTimestamp(){
    insertAtCaret('textbox',"["+getTimestamp()+"]" );
}

// insert text at cursor
function insertAtCaret(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart;

	var front = (txtarea.value).substring(0,strPos);
	var back = (txtarea.value).substring(strPos,txtarea.value.length);
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function saveText(){
    // autosave every second
    var field = document.getElementById("textbox");
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    setInterval(function(){
       localStorage.setItem("autosave", field.innerHTML);
    }, 1000);

}

function loadFileName(){
    // load existing file name
    if ( localStorage.getItem("lastfile") ) {
       document.getElementById("lastfile").innerHTML = "Last file: "+localStorage.getItem("lastfile");
       toggleAbout();
    }
}

function dragListener(){
    var button = $('.file-input-wrapper')[0];
    button.addEventListener('dragover', function(){
        $('.file-input-wrapper').addClass('hover');
    }, false);
    button.addEventListener('dragleave', function(){
        $('.file-input-wrapper').removeClass('hover');
    }, false);

}

/******************************************
                Other
******************************************/

function detectFormats(format){
    var a = document.createElement('audio');
    return !!(a.canPlayType && a.canPlayType('audio/'+format+';').replace(/no/, ''));
}

function listSupportedFormats(){
    var supportedFormats = [];
    var formats = ['mp3', 'ogg', 'webm', 'wav'];
    var i = 0;
    formats.forEach(function(format, index) {
        if (detectFormats(format) == true){
            supportedFormats[i] = format;
            i++;
        }
    });
    return supportedFormats.join(', ');
}

function checkTypeSupport(file){
  var a = document.createElement('audio');
  return !!(a.canPlayType && a.canPlayType(file.type).replace(/no/, ''));
}

function reactToFile(input){
    var file = input.files[0];
    if ( checkTypeSupport( file ) === true ){
        createPlayer( file );
        initAudioJS();
        adjustPlayerWidth();
        toggleControls();
        localStorage.setItem("lastfile", file.name);
        $('.scrubber .loaded').html( file.name );
        console.log('Loading complete.') ;
    } else {
        var msg = "Your browser does not support " + file.type.split("/")[1] + " files. Switch to a different browser or convert your file to another format.";
        $('#formats').html(msg).addClass('warning');
    }

}

function toggleControls(){
    $('.topbar').toggleClass('inputting');
    $('.input').toggleClass('active');
};

function setFormatsMessage(){
    document.getElementById("formats").innerHTML = "Your browser supports the following formats: "+listSupportedFormats()+". You may need to convert your file.";
}

function setStartButton(){
    $('.start').html('Start transcribing').addClass('ready');
}

/******************************************
             Initialisation
******************************************/

function init(){
    saveText();
    loadFileName();
    setFormatsMessage();
    adjustEditorHeight();
    dragListener();
    setStartButton();
}

init();

$(window).resize(function() {
    adjustEditorHeight();
    adjustPlayerWidth();
});

/******************************************
             User Interaction
******************************************/

    // keyboard shortcuts
    Mousetrap.bind('escape', function(e) {
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            // internet explorer
            e.returnValue = false;
        }
        playPause();
        return false;
    });
    Mousetrap.bind('f1', function(e) {
        skip('backwards');
        return false;
    });
    Mousetrap.bind('f2', function(e) {
        skip('forwards');
        return false;
    });
    Mousetrap.bind('f3', function(e) {
        speed('down');
        return false;
    });
    Mousetrap.bind('f4', function(e) {
        speed('up');
        return false;
    });
    Mousetrap.bind('mod+j', function(e) {
        document.execCommand('insertHTML',false,
        '[' + getTimestamp() + '] '
        );
        console.log(tsHTML);
        return false;
    });
    Mousetrap.bind('mod+s', function(e) {
        alert("No need to manually save - your transcript is automatically backed up continuously.")
        return false;
    });

    Mousetrap.bind('mod+b', function(e) {
        document.execCommand('bold',false,null);
        return false;
    });

    Mousetrap.bind('mod+i', function(e) {
        document.execCommand('italic',false,null);
        return false;
    });

    $('.play-pause').click(function(){
        playPause();
    });

    $('.skip-backwards').click(function(){
        skip('backwards');
    });
    $('.skip-forwards').click(function(){
        skip('forwards');
    });

    $( ".speed" ).click(function() {
        if ($('.speed-box').not(':hover').length) {
            $(this).toggleClass('fixed');
            console.log ($('.speed-box').not(':hover').length);
        }
    });

    $('.button.refresh').click(function(){
        resetPlayer();
    });

    $( "#slider3" ).change(function() {
      speed(this.valueAsNumber);
    });

    $('.title').click(function(){
        toggleAbout();
    });

    $('.about .start.ready').click(function(){
        toggleAbout();
    });

    $('#attach').change(function() {
        reactToFile(this);
    });
    // $('.timestamp').click(function(){
    //     setFromTimestamp( $(this) );
    // });

// End UI

})(); // end script

function splitTimestamp(hms){
    var a = hms.split(':');
    var seconds = (+a[0]) * 60 + (+a[1]);
    return seconds;
}

$('.timestamp *:not(:has("*"))').click(function(){
    var clickts = $(this).data('timestamp');
});

function setFromTimestamp(clickts, element){
    console.log(element.childNodes.length);
    if (element.childNodes.length == 1) {
        document.getElementById('audio').currentTime = splitTimestamp(clickts);
    }
}
<commit_msg>Update<commit_after>(function(){

/******************************************
             Audio player
******************************************/

function createPlayer(file){
    $('#audio').remove();
    $('#player-hook').append('<audio id="audio" src=""></audio>');
    if (window.webkitURL) {
        console.log('webkit');
        var url = window.webkitURL.createObjectURL(file);
    } else {
        var url = window.URL.createObjectURL(file);
    }
    console.log(url);
    $('#audio')[0].src = url;
    console.log(file.name);
}

// play/pause
function playPause(){
    var playing = !document.getElementById('audio').paused
    if (playing == true){
        document.getElementById('audio').pause();
        $('.play-pause').removeClass('playing');
    } else {
        document.getElementById('audio').play();
        $('.play-pause').addClass('playing');
    };
};

// skip forward
function skip(direction){
    var audio = document.getElementById('audio');
    if (direction == "forwards"){
        audio.currentTime = audio.currentTime+1.5;
    } else if (direction == "backwards") {
        audio.currentTime = audio.currentTime-1.5;
    }
}

// speed
function speed(newSpeed){
    console.log(typeof newSpeed);
    var min = 0.5;
    var max = 2;
    var step = 0.25;
    var newSpeedNumber;
    var currentSpeed = document.getElementById('audio').playbackRate;
    if ((newSpeed == "up") && (currentSpeed < max)){
        newSpeedNumber = currentSpeed+step;
    } else if ((newSpeed == "down") && (currentSpeed > min)){
        newSpeedNumber = currentSpeed-step;
    } else if (newSpeed == "reset"){
        newSpeedNumber = 1;
    } else if (typeof newSpeed == 'number') {
        newSpeedNumber = newSpeed;
    }
    if (typeof(newSpeedNumber) != "undefined") {
        document.getElementById('audio').playbackRate = newSpeedNumber;
        document.getElementById('slider3').value = newSpeedNumber;
    }
}

function initAudioJS(){
    audiojs.events.ready(function() {
      audiojs.createAll();
    });
}

function resetPlayer(){
    location.reload();
}

/******************************************
               Text editor
******************************************/

function adjustPlayerWidth(){
    var cntrls = $('.controls');
    console.log ("Window width: "+$(window).width()+"\nControls offset: "+cntrls.offset().left+"\nControls width: "+cntrls.width()+"\nTitle width: "+$('.title').width() );

    var gap = $(window).width() - (cntrls.offset().left + cntrls.width() + $('.title').outerWidth() );
    $('.scrubber').width( $('.scrubber').width()+gap );
   console.log(gap);
}

function toggleAbout(){
    $('.title').toggleClass('active');
    $('.about').toggleClass('active');
}

function adjustEditorHeight(){
    $('.textbox-container').height( window.innerHeight - 36 );
}

/******************************************
                Timestamp
******************************************/

// get timestamp
// var timestamp;
function getTimestamp(){
    // get timestap
    var time = document.getElementById('audio').currentTime
    var minutes = Math.floor(time / 60);
    var seconds = ("0" + Math.round( time - minutes * 60 ) ).slice(-2);
    return minutes+":"+seconds;
};

function insertTimestamp(){
    insertAtCaret('textbox',"["+getTimestamp()+"]" );
}

// insert text at cursor
function insertAtCaret(areaId,text) {
	var txtarea = document.getElementById(areaId);
	var scrollPos = txtarea.scrollTop;
	var strPos = 0;
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
		"ff" : (document.selection ? "ie" : false ) );
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		strPos = range.text.length;
	}
	else if (br == "ff") strPos = txtarea.selectionStart;

	var front = (txtarea.value).substring(0,strPos);
	var back = (txtarea.value).substring(strPos,txtarea.value.length);
	txtarea.value=front+text+back;
	strPos = strPos + text.length;
	if (br == "ie") {
		txtarea.focus();
		var range = document.selection.createRange();
		range.moveStart ('character', -txtarea.value.length);
		range.moveStart ('character', strPos);
		range.moveEnd ('character', 0);
		range.select();
	}
	else if (br == "ff") {
		txtarea.selectionStart = strPos;
		txtarea.selectionEnd = strPos;
		txtarea.focus();
	}
	txtarea.scrollTop = scrollPos;
}

function saveText(){
    // autosave every second
    var field = document.getElementById("textbox");
    if ( localStorage.getItem("autosave")) {
       field.innerHTML = localStorage.getItem("autosave");
    }
    setInterval(function(){
       localStorage.setItem("autosave", field.innerHTML);
    }, 1000);

}

function loadFileName(){
    // load existing file name
    if ( localStorage.getItem("lastfile") ) {
       document.getElementById("lastfile").innerHTML = "Last file: "+localStorage.getItem("lastfile");
       toggleAbout();
    }
}

function dragListener(){
    var button = $('.file-input-wrapper')[0];
    button.addEventListener('dragover', function(){
        $('.file-input-wrapper').addClass('hover');
    }, false);
    button.addEventListener('dragleave', function(){
        $('.file-input-wrapper').removeClass('hover');
    }, false);

}

/******************************************
                Other
******************************************/

function detectFormats(format){
    var a = document.createElement('audio');
    return !!(a.canPlayType && a.canPlayType('audio/'+format+';').replace(/no/, ''));
}

function listSupportedFormats(){
    var supportedFormats = [];
    var formats = ['mp3', 'ogg', 'webm', 'wav'];
    var i = 0;
    formats.forEach(function(format, index) {
        if (detectFormats(format) == true){
            supportedFormats[i] = format;
            i++;
        }
    });
    return supportedFormats.join(', ');
}

function checkTypeSupport(file){
  var a = document.createElement('audio');
  return !!(a.canPlayType && a.canPlayType(file.type).replace(/no/, ''));
}

function reactToFile(input){
    var file = input.files[0];
    if ( checkTypeSupport( file ) === true ){
        createPlayer( file );
        initAudioJS();
        adjustPlayerWidth();
        toggleControls();
        localStorage.setItem("lastfile", file.name);
        $('.scrubber .loaded').html( file.name );
        console.log('Loading complete.') ;
    } else {
        var msg = "Your browser does not support " + file.type.split("/")[1] + " files. Switch to a different browser or convert your file to another format.";
        $('#formats').html(msg).addClass('warning');
    }

}

function toggleControls(){
    $('.topbar').toggleClass('inputting');
    $('.input').toggleClass('active');
};

function setFormatsMessage(){
    document.getElementById("formats").innerHTML = "Your browser supports the following formats: "+listSupportedFormats()+". You may need to convert your file.";
}

function setStartButton(){
    $('.start').html('Start transcribing').addClass('ready');
}

/******************************************
             Initialisation
******************************************/

function init(){
    saveText();
    loadFileName();
    setFormatsMessage();
    adjustEditorHeight();
    dragListener();
    setStartButton();
}

init();

$(window).resize(function() {
    adjustEditorHeight();
    adjustPlayerWidth();
});

/******************************************
             User Interaction
******************************************/

    // keyboard shortcuts
    function pd(e){
        if (e.preventDefault) {
            e.preventDefault();
        } else {
            // internet explorer
            e.returnValue = false;
        }
    }

    Mousetrap.bind('escape', function(e) {
        pd(e);
        playPause();
        return false;
    });
    Mousetrap.bind('f1', function(e) {
        pd(e);
        skip('backwards');
        return false;
    });
    Mousetrap.bind('f2', function(e) {
        pd(e);
        skip('forwards');
        return false;
    });
    Mousetrap.bind('f3', function(e) {
        pd(e);
        speed('down');
        return false;
    });
    Mousetrap.bind('f4', function(e) {
        pd(e);
        speed('up');
        return false;
    });
    Mousetrap.bind('mod+j', function(e) {
        pd(e);
        document.execCommand('insertHTML',false,
        '[' + getTimestamp() + '] '
        );
        console.log(tsHTML);
        return false;
    });
    Mousetrap.bind('mod+s', function(e) {
        pd(e);
        alert("No need to manually save - your transcript is automatically backed up continuously.")
        return false;
    });

    Mousetrap.bind('mod+b', function(e) {
        pd(e);
        document.execCommand('bold',false,null);
        return false;
    });

    Mousetrap.bind('mod+i', function(e) {
        pd(e);
        document.execCommand('italic',false,null);
        return false;
    });

    $('.play-pause').click(function(){
        playPause();
    });

    $('.skip-backwards').click(function(){
        skip('backwards');
    });
    $('.skip-forwards').click(function(){
        skip('forwards');
    });

    $( ".speed" ).click(function() {
        if ($('.speed-box').not(':hover').length) {
            $(this).toggleClass('fixed');
            console.log ($('.speed-box').not(':hover').length);
        }
    });

    $('.button.refresh').click(function(){
        resetPlayer();
    });

    $( "#slider3" ).change(function() {
      speed(this.valueAsNumber);
    });

    $('.title').click(function(){
        toggleAbout();
    });

    $('.about .start.ready').click(function(){
        toggleAbout();
    });

    $('#attach').change(function() {
        reactToFile(this);
    });
    // $('.timestamp').click(function(){
    //     setFromTimestamp( $(this) );
    // });

// End UI

})(); // end script

function splitTimestamp(hms){
    var a = hms.split(':');
    var seconds = (+a[0]) * 60 + (+a[1]);
    return seconds;
}

$('.timestamp *:not(:has("*"))').click(function(){
    var clickts = $(this).data('timestamp');
});

function setFromTimestamp(clickts, element){
    console.log(element.childNodes.length);
    if (element.childNodes.length == 1) {
        document.getElementById('audio').currentTime = splitTimestamp(clickts);
    }
}
<|endoftext|>


<commit_before>var mapcanvas = document.getElementById("map");
var canvas = document.getElementById("particles");
var mapctx = mapcanvas.getContext('2d');
var ctx = canvas.getContext('2d');
var goal = {'x':10, 'y':4};
map_width = 60;
block_size = Math.floor(canvas.width / map_width);
height = Math.floor(canvas.height / block_size);

map = [];
particles = [];
var particle_size = 2;

function random_range(min, max) {
    return Math.random() * (max - min) + min;
}

function angle(x1, y1, x2, y2) {
    // Return angle in radians, with 'North' being 0,
    // increasing clockwise to 3pi/2 at 'East', pi at 'South', etc.
    var dx = x2 - x1;
    var dy = y2 - y1;
    var theta = Math.atan2(dy, dx);
    // atan2 returns results in the range -pi...pi. Convert results
    // to the range 0...2pi
    if (theta < 0) {
        theta += (2 * Math.PI);
    }
    return theta;
}

function Particle(x,y) {
    this.x = x;
    this.y = y;
    this.vel = {'x':0, 'y':0};
    this.ang = 0;
    this.speed = 1;
    this.path = [];
    this.move = function() {
        // Update velocity. When the angle the particle is moving in changes we don't
        // want the velocity to change instantly, so just nudge it towards where it belongs.
        // This is meant to be a very crude implementation of inertia.
        var inertia = 0.05;
        var dx = this.speed * Math.cos(this.ang);
        var dy = this.speed * Math.sin(this.ang);
        if (this.vel.x < dx) {
            this.vel.x += inertia;
        } else {
            this.vel.x -= inertia;
        }
        if (this.vel.y < dy) {
            this.vel.y += inertia;
        } else {
            this.vel.y -= inertia;
        }
        // Randomness
        this.vel.x += random_range(-inertia, inertia);
        this.vel.y += random_range(-inertia, inertia);

        var newx = Math.round(this.vel.x + this.x);
        var newy = Math.round(this.vel.y + this.y );
        // Move if path unobstructed
        if (newx > 0 && newx < canvas.width - 1 &&
            newy > 0 && newy< canvas.height - 1 &&
            !collides(newx, newy)) {
            this.x = newx;
            this.y = newy;
        }
    };
    this.set_path = function() {
        this.ang = angle(this.x, this.y, goal.x, goal.y);
    };
}

function init_map(width) {
    for(var x = 0; x < width; x++){
        map[x] = [];
        for(var y = 0; y < height; y++) {
            if(Math.random() * 10 > 8){
                map[x][y] = {'x' : x, 'y' : y, 'barrier' : true};
                mapctx.fillStyle = 'red';
            } else{
                map[x][y] = {'x' : x, 'y' : y, 'barrier' : false};
                mapctx.fillStyle = 'black';
            }
            mapctx.fillRect(x * block_size, y * block_size, block_size, block_size);
        }
    }
}

function collides(x,y) {
    // If a particle at x,y collides with a barrier on the map, return true
    // Check all four corners to see if any corner is within a barrier
    for (var i = 0; i < 1; i++) {
        for (var j = 0; j < 1; j++) {
             var mloc = map_location(x+(i*particle_size), y+(j*particle_size));
             if (map[mloc.x] === undefined || map[mloc.x][mloc.y] === undefined || map[mloc.x][mloc.y].barrier === true) {
                return true;
             }
        }
    }
    return false;
}

function map_location(x,y) {
    // Returns map coordinates for a given x,y on the canvas
    return {'x': Math.floor(x/block_size), 'y': Math.floor(y/block_size)};
}

function init_particles(n) {
    var added = 0;
    while (added < n) {
        var x = Math.floor(random_range(1, canvas.width - 2));
        var y = Math.floor(random_range(1, canvas.height - 2));
        if (!collides(x, y)) {
            var coords = map_location(x,y);
            particles.push( new Particle(x,y) );
            added += 1;
        }
    }
}

init_map(map_width);
init_particles(20);

function update_paths() {
    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
        p.set_path();
    }
}

function update() {
    var image = ctx.createImageData(canvas.width, canvas.height);

    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
        p.move();
        draw_particle(p.x, p.y, 0, 255, 0, 100);
    }

    ctx.putImageData(image, 0, 0);

    function draw_particle(x, y, r, g, b, a) {
        px_per_node = 2;
        for (var ypx = y; ypx < y + px_per_node; ypx++) {
            for (var xpx = x; xpx < x + px_per_node; xpx++) {
                var index = (xpx + ypx * image.width) * 4;
                image.data[index+0] = r;
                image.data[index+1] = g;
                image.data[index+2] = b;
                image.data[index+3] += a;
            }
        }
    }
}

function move_goal(e) {
    goal.x = e.hasOwnProperty('offsetX') ? e.offsetX : e.layerX;
    goal.y = e.hasOwnProperty('offsetY') ? e.offsetY : e.layerY;
    // Clear old marker,
    // draw new marker
    update_paths();
}

var step = document.getElementById("step");
step.addEventListener('click', update);

canvas.addEventListener('click', move_goal);

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function( callback ){
            window.setTimeout(callback, 1000 / 60);
        };
})();

(function animloop(){
    update();
    requestAnimFrame(animloop);
})();

<commit_msg>A* working<commit_after>var mapcanvas = document.getElementById("map");
var canvas = document.getElementById("particles");
var mapctx = mapcanvas.getContext('2d');
var ctx = canvas.getContext('2d');
var mouse = {'x':10, 'y':4};
map_width = 60;
block_size = Math.floor(canvas.width / map_width);
height = Math.floor(canvas.height / block_size);

map = [];
particles = [];
var particle_size = 2;

function random_range(min, max) {
    return Math.random() * (max - min) + min;
}

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

function angle(x1, y1, x2, y2) {
    // Return angle in radians, with 'North' being 0,
    // increasing clockwise to 3pi/2 at 'East', pi at 'South', etc.
    var dx = x2 - x1;
    var dy = y2 - y1;
    var theta = Math.atan2(dy, dx);
    // atan2 returns results in the range -pi...pi. Convert results
    // to the range 0...2pi
    if (theta < 0) {
        theta += (2 * Math.PI);
    }
    return theta;
}

function Particle(x,y) {
    this.x = x; // X position on canvas
    this.y = y; // Y position on canvas
    this.vel = {'x':0, 'y':0};
    this.ang = 0; // Angle the particle is travelling in
    this.speed = random_range(1,2);
    this.path = [];
    this.destination = {'x':0, 'y':0}; // The current destination
    this.inertia = random_range(0.05, 0.1);
    this.update = function() {
        // A particle's velocity doesn't change instantaneously. The angle
        // of its movement is nudges towards the angle towards its goal,
        // and then the goal angle is updated for its new position.

        // If particle has reached a node along its path, remove the next
        // node in the path, and set the
        var map_loc = map_location(this.x, this.y);
        if (map_loc.x === this.destination.x && map_loc.y === this.destination.y) {
            if (this.path.length > 0) {
                this.destination = this.path.pop();
            }
        }
        // Calculate angle to goal for current position.
        this.ang = angle(this.x, this.y, (this.destination.x * block_size) + (block_size / 2), (this.destination.y * block_size) + (block_size / 2));
        // Update particle velocity using new angle value
        var velx = this.speed * Math.cos(this.ang);
        var vely = this.speed * Math.sin(this.ang);
        this.vel.x = this.vel.x + (velx - this.vel.x) * this.inertia;
        this.vel.y = this.vel.y + (vely - this.vel.y) * this.inertia;
    };
    this.move = function() {
        // Get integer values for next position
        var newx = Math.round(this.vel.x + this.x);
        var newy = Math.round(this.vel.y + this.y );
        // Move if path unobstructed
        if (newx > 0 && newx < canvas.width - 1 &&
            newy > 0 && newy< canvas.height - 1 &&
            !collides(newx, newy)) {
            this.x = newx;
            this.y = newy;
        }
    };
    this.set_path = function() {
        // Find and set the path to the goal, using A*
        // This would
        // F = G + H
        var start = map_location(this.x, this.y);
        var goal = map_location(mouse.x, mouse.y);
        start.parent = null;
        start.g = 0;
        start.h = 0; // do this
        start.f = start.g + start.h;
        var to_visit  = {};
        to_visit[to_str(start)] = start;
        var visited = {};
        while (!isEmpty(to_visit)) {
            var idx = -1;
            var smallest_f = Infinity;
            // Find smalled F value
            for (var i in to_visit) {
                if (to_visit[i].f < smallest_f) {
                    idx = i;
                    smallest_f = to_visit[i].f;
                }
            }
            // Remove node with smallest F value from to_visit, add to visited
            var current = to_visit[idx];
            delete to_visit[idx];
            visited[idx] = current;
            // Calculate properties for neighbors and add to to_visit
            var neighbor_list = neighbors(current.x, current.y);
            for (var j = 0; j < neighbor_list.length; j++) {
                // diag 14, cardinal 10
                var nbr = neighbor_list[j];
                nbr.parent = current;
                if (nbr.x !== nbr.parent.x && nbr.y !== nbr.parent.y) {
                    // Diagonal movement costs more than horizontal or vertical movement
                    nbr.g = nbr.parent.g + 14;
                } else {
                    nbr.g = nbr.parent.g + 10;
                }
                nbr.h = calc_h(nbr, goal);
                nbr.f = nbr.g + nbr.h;

                var key = to_str(nbr);
                // Check if already visited, if so, check if F value here is better.
                if (key in to_visit && !(key in visited)) {
                    if (nbr.g < to_visit[key].g) {
                        to_visit[key] = nbr;
                    }
                } else if (!(key in visited)) {
                    to_visit[key] = nbr;
                }
                // Stop if we've reached our goal
                if (nbr.x === goal.x && nbr.y === goal.y) {
                    visited[to_str(nbr)] = nbr;
                    // Work backwards from goal, adding parents to list, until we reach start
                    var path = [];
                    var curr = visited[to_str(goal)];
                    while (curr !== null) {
                        path.push({'x':curr.x, 'y':curr.y});
                        curr = curr.parent;
                    }
                    this.destination = {'x':path[path.length-1].x, 'y':path[path.length-1].y};
                    this.path = path;
                    return;
                }
            }
        }
        if (isEmpty(to_visit)) {
            this.path = [];
        }
        function to_str(node) {
                return node.x + '' + node.y;
            }
        function calc_h(p0, p1){
            var d1 = Math.abs (p1.x - p0.x);
            var d2 = Math.abs (p1.y - p0.y);
            return d1 + d2;
        }
    };
}

function neighbors(x,y) {
    // Only return neighbors in cardinal directions
    // Particles can't navigate through barriers diagonally
    var neighbor_list = [];
    for (var i = -1; i <= 1; i++) {
        for (var j = -1; j <= 1; j++) {
            if (!(i===j && i===0) && map[x+i] !== undefined && map[x+i][y+j] !== undefined && !map[x+i][y+j].barrier && (Math.abs(i) + Math.abs(j) < 2)) {
                neighbor_list.push({'x': x+i, 'y':y+j, 'parent': {'x':x, 'y':y}});
             }
        }
    }
    return neighbor_list;
}

function init_map(width) {
    for(var x = 0; x < width; x++){
        map[x] = [];
        for(var y = 0; y < height; y++) {
            if(Math.random() * 10 > 7){
                map[x][y] = {'x' : x, 'y' : y, 'barrier' : true};
                mapctx.fillStyle = 'red';
            } else{
                map[x][y] = {'x' : x, 'y' : y, 'barrier' : false};
                mapctx.fillStyle = 'black';
            }
            mapctx.fillRect(x * block_size, y * block_size, block_size, block_size);
        }
    }
}

function collides(x,y) {
    // If a particle at x,y collides with a barrier on the map, return true
    // Check all four corners to see if any corner is within a barrier
    for (var i = 0; i < 1; i++) {
        for (var j = 0; j < 1; j++) {
             var mloc = map_location(x+(i*particle_size), y+(j*particle_size));
             if (map[mloc.x] === undefined || map[mloc.x][mloc.y] === undefined || map[mloc.x][mloc.y].barrier === true) {
                return true;
             }
        }
    }
    return false;
}

function map_location(x,y) {
    // Returns map coordinates for a given x,y on the canvas
    return {'x': Math.floor(x/block_size), 'y': Math.floor(y/block_size)};
}

function init_particles(n) {
    var added = 0;
    while (added < n) {
        var x = Math.floor(random_range(1, canvas.width - 2));
        var y = Math.floor(random_range(1, canvas.height - 2));
        if (!collides(x, y)) {
            var coords = map_location(x,y);
            particles.push( new Particle(x,y) );
            added += 1;
        }
    }
}

init_map(map_width);
init_particles(20);

function update_paths() {
    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
        p.set_path();
    }
}

function update() {
    var image = ctx.createImageData(canvas.width, canvas.height);

    for (var i = 0; i < particles.length; i++) {
        var p = particles[i];
        p.update();
        p.move();
        draw_particle(p.x, p.y, 0, 255, 0, 100);
    }

    ctx.putImageData(image, 0, 0);

    function draw_particle(x, y, r, g, b, a) {
        px_per_node = 2;
        for (var ypx = y; ypx < y + px_per_node; ypx++) {
            for (var xpx = x; xpx < x + px_per_node; xpx++) {
                var index = (xpx + ypx * image.width) * 4;
                image.data[index+0] = r;
                image.data[index+1] = g;
                image.data[index+2] = b;
                image.data[index+3] += a;
            }
        }
    }
}

function move_goal(e) {
    mouse.x = e.hasOwnProperty('offsetX') ? e.offsetX : e.layerX;
    mouse.y = e.hasOwnProperty('offsetY') ? e.offsetY : e.layerY;
    // Clear old marker,
    // draw new marker
    update_paths();
}

var step = document.getElementById("step");
step.addEventListener('click', update);

canvas.addEventListener('click', move_goal);

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function( callback ){
            window.setTimeout(callback, 1000 / 60);
        };
})();

(function animloop(){
    update();
    requestAnimFrame(animloop);
})();

<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const SefzigBot =     "[SefzigBot] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const KreationsBot =  "[KreationsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const LinkBot =       "[LinkBot] ";
const TextBot =       "[TextBot] ";
const SlackBot =      "[SlackBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(SefzigBot+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

    start: {

        receive: (bot) => {
            return bot.say(EmpfangsBot+'Darf ich Ihnen uns kurz vorstellen? Dann schreiben Sie bitte --Empfang!')
                .then(() => bot.say(EmpfangsBot+'Oder darf ich Ihnen unsere --Kreation,  --Beratung und --Technik vorstellen?'))
                .then(() => 'register'); /* <-- vorname: automatisches Onboarding */
        }
    },

 // -------------------------
 // Onboarding
 // -------------------------

    vorname: {

        prompt: (bot) => bot.say(SefzigBot+'Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(SefzigBot+`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {

        prompt: (bot) => bot.say(SefzigBot+'Und wie heissen Sie mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            bot.setProp('nachname', nachname)
            return bot.getProp('vorname')
                .then((vorname) => bot.say(SefzigBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
                .then((vorname) => bot.say(SefzigBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
                .then(() => 'name');
        }
    },

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(SefzigBot+'Sie können hier jederzeit eine Nachricht an Andreas schreiben!');
               bot.say(SefzigBot+'Unterhalten Sie sich mit mir: Bitte schreiben Sie --bot:');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--ABBRECHEN") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
                .then(() => dann);
        }
    },

 // -------------------------
 // Register
 // -------------------------

    register: {

        receive: (bot, message) => {

            var befehl = message.text.trim().toUpperCase();
            var dann = "register";

         // -----------------
         // Onboarding
         // -----------------

            if  (~befehl.indexOf("--NAME"))           { dann = "name"; }

         // -----------------
         // Bots
         // -----------------

            if  (~befehl.indexOf("--KREATION"))       { dann = "kreation"; }

         // -----------------
         // System
         // -----------------

            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--Empfang '
                                                              +'\n○ --Befehle '
                                                              +'\n○ --Mobil '
                                                              +'\n○ --Über '); }

            if ((~befehl.indexOf("--UBER")) ||
                (~befehl.indexOf("--ÜBER")))          { bot.say(EmpfangsBot+'#Robogeddon ist auf Bots für externe und interne Unternehmens-Kommunikation spezialisiert.');
                                                        bot.say(EmpfangsBot+'Wir bestehen aus Andreas Sefzig und mehreren Bots.');
                                                        bot.say(EmpfangsBot+'Empfang Befehle: ○ --Folgt.'); }
            if  (~befehl.indexOf("--MOBIL"))          { bot.say(EmpfangsBot+'Diesen Chat mobil öffnen: [Bild:https://zxing.org/w/chart?cht=qr&chs=200x200&chld=L&choe=UTF-8&chl=http%3A%2F%2Fsefzigbot.herokuapp.com?v=chat%2F]');
                                                        bot.say(EmpfangsBot+'(Leider werden Sie dort nicht wiedererkannt. Das sollte in einer späteren Version möglich sein...)'); }

         // -----------------
         // Tests
         // -----------------

            if  (~befehl.indexOf("--JAVASCRIPT"))     { bot.say(SefzigBot+'[Javascript:test_alert]'); }
            if  (~befehl.indexOf("--VIDEO"))          { bot.say(SefzigBot+'[Youtube:u07XONlDwX8]'); }

         // -----------------
         // Vorlage
         // -----------------

            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // .then(function(){ bot.say(''); })
            return bot.setProp('register', 'gesprochen')
                .then(() => dann);
        }
    },

 // -------------------------
 // Kreation
 // -------------------------

    kreation: {

        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "kreation";

         // Befehle
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(KreationsBot +'--Kreation '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt'); }
            if ((~befehl.indexOf("--ZURÜCK")) ||
                (~befehl.indexOf("--ABBRECHEN")))     { bot.say(KreationsBot +'Zurück an --Empfang-s-Bot. Bis später!');
                                                        dann = "register"; }

         // Inhalte
            if ((~befehl.indexOf("--UBER")) ||
                (~befehl.indexOf("--ÜBER")))          { bot.say(KreationsBot +'Text Über 1.');
                                                        bot.say(KreationsBot +'Text Über 2.'); }
            if  (~befehl.indexOf("--ARTIKEL"))        { bot.say(KreationsBot +'Text Artikel.'); }
            if  (~befehl.indexOf("--BLOGPOST"))       { bot.say(KreationsBot +'Text Blogpost.'); }
            if  (~befehl.indexOf("--LINKS"))          { bot.say(KreationsBot +'Text Links.'); }

         // Konversation fortführen
            return bot.setProp('text', 'gesprochen')
                .then(() => dann);

        }

    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>EmpfangsBot<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const SefzigBot =     "[SefzigBot] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const KreationsBot =  "[KreationsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const LinkBot =       "[LinkBot] ";
const TextBot =       "[TextBot] ";
const SlackBot =      "[SlackBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(SefzigBot+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

    start: {

        receive: (bot) => {
            return bot.say(EmpfangsBot+'Darf ich Ihnen uns kurz vorstellen? Dann schreiben Sie bitte --Empfang!')
                .then(() => bot.say(EmpfangsBot+'Oder darf ich Ihnen unsere --Kreation,  --Beratung und --Technik vorstellen?'))
                .then(() => 'register'); /* <-- vorname: automatisches Onboarding */
        }
    },

 // -------------------------
 // Onboarding
 // -------------------------

    vorname: {

        prompt: (bot) => bot.say(SefzigBot+'Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {
            var vorname = message.text;
            return bot.setProp('vorname', vorname)
                .then(() => bot.say(SefzigBot+`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {

        prompt: (bot) => bot.say(SefzigBot+'Und wie heissen Sie mit Nachnamen?'),
        receive: (bot, message) => {
            var nachname = message.text;
            bot.setProp('nachname', nachname)
            return bot.getProp('vorname')
                .then((vorname) => bot.say(SefzigBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
                .then((vorname) => bot.say(SefzigBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
                .then(() => 'name');
        }
    },

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(SefzigBot+'Sie können hier jederzeit eine Nachricht an Andreas schreiben!');
               bot.say(SefzigBot+'Unterhalten Sie sich mit mir: Bitte schreiben Sie --bot:');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--ABBRECHEN") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
                .then(() => dann);
        }
    },

 // -------------------------
 // Register
 // -------------------------

    register: {

        receive: (bot, message) => {

            var befehl = message.text.trim().toUpperCase();
            var dann = "register";

         // -----------------
         // Onboarding
         // -----------------

            if  (~befehl.indexOf("--NAME"))           { dann = "name"; }

         // -----------------
         // Bots
         // -----------------

            if  (~befehl.indexOf("--KREATION"))       { dann = "kreation"; }
         // if  (~befehl.indexOf("--BERATUNG"))       { dann = "beratung"; }
         // if  (~befehl.indexOf("--TECHNIK"))        { dann = "texhnik";  }

         // -----------------
         // System
         // -----------------

            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--Befehle '
                                                              +'\n○ --Mobil '
                                                              +'\n○ --Über '); }
            if  (~befehl.indexOf("--MOBIL"))          { bot.say(EmpfangsBot+'Diesen Chat mobil öffnen: [Bild:https://zxing.org/w/chart?cht=qr&chs=200x200&chld=L&choe=UTF-8&chl=http%3A%2F%2Fsefzigbot.herokuapp.com?v=chat%2F]');
                                                        bot.say(EmpfangsBot+'(Leider werden Sie dort nicht wiedererkannt. Das sollte in einer späteren Version möglich sein...)'); }
            if ((~befehl.indexOf("--UBER")) ||
                (~befehl.indexOf("--ÜBER")))          { bot.say(EmpfangsBot+'#Robogeddon ist auf Bots für externe und interne Unternehmens-Kommunikation spezialisiert.');
                                                        bot.say(EmpfangsBot+'Wir bestehen aus Andreas Sefzig und mehreren Bots.');
                                                        bot.say(EmpfangsBot+'Empfang Befehle: ○ --Folgt.'); }

         // -----------------
         // Tests
         // -----------------

            if  (~befehl.indexOf("--JAVASCRIPT"))     { bot.say(SefzigBot+'[Javascript:test_alert]'); }
            if  (~befehl.indexOf("--VIDEO"))          { bot.say(SefzigBot+'[Youtube:u07XONlDwX8]'); }

         // -----------------
         // Vorlage
         // -----------------

            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // Konversation fortführen
            return bot.setProp('register', 'gesprochen')
            .then(() => dann);
        }
    },

 // -------------------------
 // Kreation
 // -------------------------

    kreation: {

        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "kreation";

         // Befehle
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(KreationsBot +'--Kreation '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '); }
            if ((~befehl.indexOf("--ZURÜCK")) ||
                (~befehl.indexOf("--ABBRECHEN")))     { bot.say(KreationsBot+'Zurück an --Empfangs-Bot. Bis später!');
                                                        dann = "register"; }

         // Inhalte
            if  (~befehl.indexOf("--ARTIKEL"))        { bot.say(KreationsBot +'Text Artikel.'); }
            if  (~befehl.indexOf("--BLOGPOST"))       { bot.say(KreationsBot +'Text Blogpost.'); }
            if  (~befehl.indexOf("--LINKS"))          { bot.say(KreationsBot +'Text Links.'); }

         // Konversation fortführen
            return bot.setProp('text', 'gesprochen')
                .then(() => dann);

        }

    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>$(document).ready(function() {

	$(".nav a, .navbar-brand").on("click", function(){
		event.preventDefault();
	   $(".nav").find(".active").removeClass("active");
	   $(this).parent().addClass("active");
		scrollToID('#' + $(this).attr("way"), 1000);
		window.location.hash = sectionID;
	});

	// navigation click actions

	// scroll to top action
	$('.scroll-top').on('click', function(event) {
		event.preventDefault();
		$('html, body').animate({scrollTop:0}, 'slow');
	});
	// mobile nav toggle
	$('#nav-toggle').on('click', function (event) {
		event.preventDefault();
		$('#main-nav').toggleClass("open");
	});
});

// scroll function
function scrollToID(id, speed){
	var offSet = 0;
	var targetOffset = $(id).offset().top - offSet;
	var mainNav = $('#main-nav');
	$('html,body').animate({scrollTop:targetOffset}, speed);
	if (mainNav.hasClass("open")) {
		mainNav.css("height", "1px").removeClass("in").addClass("collapse");
		mainNav.removeClass("open");
	}
}
if (typeof console === "undefined") {
    console = {
        log: function() { }
    };
}<commit_msg>start7<commit_after>$(document).ready(function() {

	$(".nav").find(".active").removeClass("active");
	$("a[way=window.location.hash]").parent().addClass(active");

	$(".nav a, .navbar-brand").on("click", function(){
		event.preventDefault();

		$(".nav").find(".active").removeClass("active");
		$(this).parent().addClass("active");

		window.location.hash = $(this).attr("way");
		scrollToID('#' + window.location.hash, 1000);
		console.log(window.location.hash);
	});

	// navigation click actions

	// scroll to top action
	$('.scroll-top').on('click', function(event) {
		event.preventDefault();
		$('html, body').animate({scrollTop:0}, 'slow');
	});
	// mobile nav toggle
	$('#nav-toggle').on('click', function (event) {
		event.preventDefault();
		$('#main-nav').toggleClass("open");
	});
});

// scroll function
function scrollToID(id, speed){
	var offSet = 0;
	var targetOffset = $(id).offset().top - offSet;
	var mainNav = $('#main-nav');
	$('html,body').animate({scrollTop:targetOffset}, speed);
	if (mainNav.hasClass("open")) {
		mainNav.css("height", "1px").removeClass("in").addClass("collapse");
		mainNav.removeClass("open");
	}
}
if (typeof console === "undefined") {
    console = {
        log: function() { }
    };
}<|endoftext|>