<commit_before>var BASE = "http://ebh.herokuapp.com";

Handlebars.registerHelper('ifBoth', function(v1, v2, options) {
  if(v1 && v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Handlebars.registerHelper('bitterness', function(ibu){
	return 100 * (ibu/110);
});
Handlebars.registerHelper('bitternessText', function(ibu){
	var perc = 100 * (ibu/110);
	if (ibu <= 10){
		return "very low";
	} else if (ibu > 10 && ibu <= 30){
		return "low";
	} else if (ibu > 30 && ibu <= 40){
		return "medium";
	} else if (ibu > 40 && ibu <= 60){
		return "high medium";
	} else if (ibu > 60 && ibu <= 80){
		return "high";
	} else {
		return "very high";
	}

});

$.ajaxSetup({
	cache : false,
	data : {
		"withBreweries" : "Y"
	}
});
var theRequest;

var listhtml = "";
function getBeerList(h,p,page,query){
	var data;
	$("#index").fadeIn(); $("#single").fadeOut();
	if (!h) h = "";
	if (!p) p = 1;
	if (!page) page = "recommended";
	if (!query) query = "";

	$.getJSON("/me", function(data){
		console.log(data);
		if (page=="recommended"){
			data = {method : "beers", "order" : "status", "abv":"7,12", "ibu":"20,50", "p":p};
		// } else if (page=="recommended"){
			// data = {method : "beers", "order": "availableId", "sort" :"DESC", "p":p};
		} else if (page=="atoz"){
			data = {method : "beers", "order": "name", "sort" :"ASC", "p":p};
		} else if (page=="popular"){
			// These are the most recently updated... So they must be popular, right?
			var ts = Math.round((new Date()).getTime() / 1000) - (86400*4);
			data = {method : "beers", "since": ts, "sort" :"ASC", "p":p};
		} else if (page=="seasonal"){
			// grab those spring beers, dog
			data = {method : "beers", "availableId": 5, "order" : "abv", "sort" :"DESC", "p":p};
		} else if (page=="cellar"){
			var ids = "";
			$(data.drinks).each(function(i,el){
				ids += el.api_id + ",";
			})
			data = {method : "beers", "ids": ids, "sort" :"ASC", "p":p};
		} else if (page=="purchases"){
			data = {method : "beers", "ids": "Qx1hbt,R0MvCF,iLlMCb,FYS1Qj,y3lFdg,CfJ0cK,AXqmST,NoNhan,f9WbNU,x6bRxw,", "sort" :"ASC", "p":p};
		} else if (page=="search"){
			data = {method : "search", "q": query, "p":p};
		}

		theRequest = $.getJSON(BASE, data, function(data){
			var ctx = {
				beers : data.data
			}
			var source = $("#beer-list").html();
			var tpl = Handlebars.compile(source);
			h += tpl(ctx);
			var fragment = document.createDocumentFragment();
			var d = document.createElement("div");
			d.innerHTML=h;
			if ($(d).find("li").length < 60 && data.currentPage < data.numberOfPages){
				$("#beerlist").append(h);
				$(".loading-text").remove();
				return getBeerList(h,p+1,page,query);
			} else {
				$("#beerlist").append(h);
			}
		});
	})
}
getBeerList(listhtml, 1, "recommended");

$("nav").on("click", "a", function(e){
	if (!$(this).is(".logout")){
		e.preventDefault();
	} else { return true; }
	if (theRequest){
		theRequest.abort();
	}
	var el = this;
	if (!$(this).is(".current")){
		$(el).addClass("current").siblings().removeClass("current");
		var sec = $(el).attr("href").replace("#", "");
		$("#logo small").html(sec[0].toUpperCase() + sec.slice(1));
		$("#beerlist").empty().html("
Loading...
");
		getBeerList("", 1, sec);
		$("#contain").removeClass("nav-open");
		$(".nav-switch").removeClass("open");
	} else {
		// do nothing.
	}
});
$(".nav-switch").on("click", function(e){
	console.log(e.target);
	console.log(this);
	if ($(this).hasClass("open")){
		$(this).removeClass("open");
		$("#contain").removeClass("nav-open");
	} else {
		$(this).addClass("open");
		$("#contain").addClass("nav-open");
	}
})
$(".search-switch i").on("click", function(e){
	$(e.target).parent().toggleClass("on");
});

var tout;
$("input[name=search-input]").on("keyup", function(){
	clearTimeout(tout);
	if (theRequest){
		theRequest.abort();
	}
	$("#logo small").html("Search")
	$("#beerlist").empty().html("
Loading...
");
	tout = setTimeout(function(){
		getBeerList("", 1, "search", $("input[name=search-input]").val());
	}, 300);
});

function goToSingle(ev){
	if (!ev){
		var hash = document.location.hash;
	} else {
		if (!$(ev.target).is("a")){
			var t = $(ev.target).parents("a");
		} else {
			var t = $(ev.target);
		}
		var hash = $(t).attr("href");
	}
	$("#index").fadeOut();
	var id = hash.split("/")[hash.split("/").length-1];
	var data = { method : "beer/"+id }
	theRequest.abort();
	theRequest = $.getJSON(BASE, data, function(data){
		var ctx = data.data;
		var source = $("#single-beer").html();
		var tpl = Handlebars.compile(source);
		var h = tpl(ctx);
		$("#single").html(h).fadeIn();
		var rating = Math.round(Math.random() * 5);
		var i = 0;
		var h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").first().prepend("
"+h+"
");

			rating = Math.round(Math.random() * 5);
			i = 0;
			h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").last().prepend("
"+h+"
");
	});
}

$("body").on("click", ".single-link", goToSingle);
$(document).ready(function(){
	if (document.location.hash.split("/")[1] == "beer"){
		goToSingle();
	}
});
$("body").on("click", ".back", function(e){
	e.preventDefault();
	$("#single").fadeOut(function(){$("#single").empty();});
	$("#index").fadeIn();
});
$("body").on("click", ".styleinfo a", function(e){
	e.preventDefault();
	$(e.target).toggleClass("open");
	$(e.target).parent().next("p").slideToggle();
});
$("body").on("submit", "#add-a-review", function(e){
	e.preventDefault();
	var username = $("input[name='username']").val();
	var comments = $("textarea[name='comments']").val();
	var comment = "
"
                            +"
"
                                +"
"+username+"
"
                                +""
                                +"
"+comments+"
"
                            +"
"
                        +"
"
                        +"
";
    $(".reviews").append(comment);
});

$("body").on("click", ".add-beer", function(e){
	var id = $(this).data("api_id");
	var button = $(this);
	$.post("/cellar/add", {"api_id" : id}, function(data){
		var json = $.parseJSON(data);
		console.log(json)
		if (json.message == "Successfully added drink."){
			button.text("Added to cellar!").removeClass("add-beer");
		}
	});
})<commit_msg>fixing things<commit_after>var BASE = "http://ebh.herokuapp.com";

Handlebars.registerHelper('ifBoth', function(v1, v2, options) {
  if(v1 && v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

Handlebars.registerHelper('bitterness', function(ibu){
	return 100 * (ibu/110);
});
Handlebars.registerHelper('bitternessText', function(ibu){
	var perc = 100 * (ibu/110);
	if (ibu <= 10){
		return "very low";
	} else if (ibu > 10 && ibu <= 30){
		return "low";
	} else if (ibu > 30 && ibu <= 40){
		return "medium";
	} else if (ibu > 40 && ibu <= 60){
		return "high medium";
	} else if (ibu > 60 && ibu <= 80){
		return "high";
	} else {
		return "very high";
	}

});

$.ajaxSetup({
	cache : false,
	data : {
		"withBreweries" : "Y"
	}
});
var theRequest;

var listhtml = "";
function getBeerList(h,p,page,query){
	var data;
	$("#index").fadeIn(); $("#single").fadeOut();
	if (!h) h = "";
	if (!p) p = 1;
	if (!page) page = "recommended";
	if (!query) query = "";

	$.getJSON("/me", function(data){
		console.log(data);
		if (page=="recommended"){
			data = {method : "beers", "order" : "status", "abv":"7,12", "ibu":"20,50", "p":p};
		// } else if (page=="recommended"){
			// data = {method : "beers", "order": "availableId", "sort" :"DESC", "p":p};
		} else if (page=="atoz"){
			data = {method : "beers", "order": "name", "sort" :"ASC", "p":p};
		} else if (page=="popular"){
			// These are the most recently updated... So they must be popular, right?
			var ts = Math.round((new Date()).getTime() / 1000) - (86400*4);
			data = {method : "beers", "since": ts, "sort" :"ASC", "p":p};
		} else if (page=="seasonal"){
			// grab those spring beers, dog
			data = {method : "beers", "availableId": 5, "order" : "abv", "sort" :"DESC", "p":p};
		} else if (page=="cellar"){
			var ids = "";
			$(data.drinks).each(function(i,el){
				ids += el.api_id + ",";
			})
			data = {method : "beers", "ids": ids, "sort" :"ASC", "p":p};
		} else if (page=="purchases"){
			data = {method : "beers", "ids": "Qx1hbt,R0MvCF,iLlMCb,FYS1Qj,y3lFdg,CfJ0cK,AXqmST,NoNhan,f9WbNU,x6bRxw,", "sort" :"ASC", "p":p};
		} else if (page=="search"){
			data = {method : "search", "q": query, "p":p};
		}

		theRequest = $.getJSON(BASE, data, function(data){
			var ctx = {
				beers : data.data
			}
			var source = $("#beer-list").html();
			var tpl = Handlebars.compile(source);
			h += tpl(ctx);
			var fragment = document.createDocumentFragment();
			var d = document.createElement("div");
			d.innerHTML=h;
			if ($(d).find("li").length < 60 && data.currentPage < data.numberOfPages){
				$("#beerlist").append(h);
				$(".loading-text").remove();
				return getBeerList(h,p+1,page,query);
			} else {
				$("#beerlist").append(h);
			}
		});
	})
}
getBeerList(listhtml, 1, "recommended");

$("nav").on("click", "a", function(e){
	if (!$(this).is(".logout")){
		e.preventDefault();
	} else { return true; }
	if (theRequest){
		theRequest.abort();
	}
	var el = this;
	if (!$(this).is(".current")){
		$(el).addClass("current").siblings().removeClass("current");
		var sec = $(el).attr("href").replace("#", "");
		$("#logo small").html(sec[0].toUpperCase() + sec.slice(1));
		$("#beerlist").empty().html("
Loading...
");
		getBeerList("", 1, sec);
		$("#contain").removeClass("nav-open");
		$(".nav-switch").removeClass("open");
	} else {
		// do nothing.
	}
});
$(".nav-switch").on("click", function(e){
	console.log(e.target);
	console.log(this);
	if ($(this).hasClass("open")){
		$(this).removeClass("open");
		$("#contain").removeClass("nav-open");
	} else {
		$(this).addClass("open");
		$("#contain").addClass("nav-open");
	}
})
$(".search-switch i").on("click", function(e){
	$(e.target).parent().toggleClass("on");
});

var tout;
$("input[name=search-input]").on("keyup", function(){
	clearTimeout(tout);
	if (theRequest){
		theRequest.abort();
	}
	$("#logo small").html("Search")
	$("#beerlist").empty().html("
Loading...
");
	tout = setTimeout(function(){
		getBeerList("", 1, "search", $("input[name=search-input]").val());
	}, 300);
});

function goToSingle(ev){
	if (!ev){
		var hash = document.location.hash;
	} else {
		if (!$(ev.target).is("a")){
			var t = $(ev.target).parents("a");
		} else {
			var t = $(ev.target);
		}
		var hash = $(t).attr("href");
	}
	$("#index").fadeOut();
	var id = hash.split("/")[hash.split("/").length-1];
	var data = { method : "beer/"+id }
	theRequest.abort();
	theRequest = $.getJSON(BASE, data, function(data){
		var ctx = data.data;
		var source = $("#single-beer").html();
		var tpl = Handlebars.compile(source);
		var h = tpl(ctx);
		$("#single").html(h).fadeIn();
		var rating = Math.round(Math.random() * 5);
		var i = 0;
		var h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").first().prepend("
"+h+"
");

			rating = Math.round(Math.random() * 5);
			i = 0;
			h = "";
		for (i = i; i < rating; i++){
			h += "";
		}
		for (i = i; i < 5; i++){
			h += "";
		}
		$(".review p").last().prepend("
"+h+"
");
	});
}

$("body").on("click", ".single-link", goToSingle);
$(document).ready(function(){
	if (document.location.hash.split("/")[1] == "beer"){
		goToSingle();
	}
});
$("body").on("click", ".back", function(e){
	e.preventDefault();
	$("#single").fadeOut(function(){$("#single").empty();});
	$("#index").fadeIn();
});
$("body").on("click", ".styleinfo a", function(e){
	e.preventDefault();
	$(e.target).toggleClass("open");
	$(e.target).parent().next("p").slideToggle();
});
$("body").on("submit", "#add-a-review", function(e){
	e.preventDefault();
	var username = $("input[name='username']").val();
	var comments = $("textarea[name='comments']").val();
	var comment = "
"
                            +"
"
                                +"
"+username+"
"
                                +""
                                +"
"+comments+"
"
                            +"
"
                        +"
"
                        +"
";
    $(".reviews").append(comment);
});

$("body").on("click", ".add-beer", function(e){
	var id = $(this).data("api_id");
	var button = $(this);
	$.post("/cellar/add", {"api_id" : id}, function(data){
		var json = $.parseJSON(data);
		console.log(json);
		if (json.message == "Successfully added drink."){
			button.text("Added to cellar!").removeClass("add-beer");
		}
	});
})<|endoftext|>


<commit_before>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.update();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = localStorage.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone;// + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		var fac = this;
 		fac.facilities = [];

		$scope.getAll = function() {
			var path = '/facilities/';
			$http({method: 'GET', url: path}).
				success(function(data, status) {
					fac.facilities = data;
				});
				$scope.facilities = fac.facilities;
		};

		$scope.getFac = function() {
			var path = '/facilities/' + 1;		// need to fix this; dynamically add facility number
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];

					}
				});
		};

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Falcon Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Shark Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Courgar Court',
				image: "../assets/rb.jpg"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<commit_msg>updated<commit_after>
(function() {
	var app = angular.module('SportScheduler', []);

 	app.controller('UserController', ['$scope', '$http', function($scope, $http){
 		$scope.user = {
 		firstName: '',
 		lastName: '',
 		email: '',
 		phone: '',
 		fbUserId: '',
 		accessToken: '',
 		image: '',
 		loggedIn: 'false'
		};

		$(document).ready(function(){
		    $(".toggle-modal").click(function(){
		        $("#myModal").modal('toggle');
		    });
		});

		$scope.submit = function(phone) {
		 	$scope.user.phone = phone;
		 	localStorage.phone = phone;
		 	$scope.update();
		};

		$scope.log = function() {
		 	console.log($scope.user.firstName);
		 	console.log($scope.user.lastName);
		 	console.log($scope.user.email);
		 	console.log($scope.user.fbUserId);
		};

		$scope.setUser = function(){
			if(localStorage.getItem("loggedIn") === "true"){
				$scope.get();
			}
		};

		$scope.logout = function() {
			localStorage.setItem("loggedIn", "false");
			localStorage.setItem("first_name", "");
			localStorage.setItem("last_name", "");
			localStorage.setItem("email", "");
			localStorage.setItem("id", "");
			localStorage.setItem("image", "");
			localStorage.setItem("phone", "");
			alert("You have logged out of the application, but you are still logged into Facebook.")
			window.location = "../";
		}

		$scope.get = function() {
			$scope.userGetPath = '/users/' + localStorage.id;
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var userVals = data[0];
						$scope.user.firstName = userVals.firstName;
						$scope.user.lastName = userVals.lastName;
						$scope.user.email = userVals.email;
						$scope.user.fbUserId = userVals.fbUserId;
						$scope.user.loggedIn = userVals.loggedIn;
						$scope.user.image = localStorage.image;
						$scope.user.phone = localStorage.phone;

					} else {
						$scope.put();
					}
				});
		};

		$scope.update = function() {
			$scope.userPutPath = '/users/' + $scope.user.fbUserId + '/' + $scope.user.email + '/' + $scope.user.phone;// + '/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.loggedIn;

			$http({method: 'POST', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

		$scope.put = function() {

			$scope.user.firstName = localStorage.getItem("first_name");
			$scope.user.lastName = localStorage.getItem("last_name");
			$scope.user.email = localStorage.getItem("email");
			$scope.user.fbUserId = localStorage.getItem("id");
			$scope.user.image = localStorage.getItem("image");
			$scope.user.phone = localStorage.getItem("phone");
			$scope.user.loggedIn = localStorage.getItem("loggedIn");

			$scope.userPutPath = '/users/' + $scope.user.firstName + '/' + $scope.user.lastName + '/' + $scope.user.email + '/' + $scope.user.phone + '/' + $scope.user.loggedIn + '/' + $scope.user.fbUserId;

			$http({method: 'PUT', url: $scope.userPutPath}).
				success(function(data, status) {
					if(status = '200'){
						console.log(data);
					}
				});
		};

	}]);

	app.controller('FacilityController', ['$scope', '$http', function($scope, $http){

		$scope.facilityId = 0;

		var fac = this;
 		fac.facilities = [];

		$scope.getAll = function() {
			var path = '/facilities/';
			$http({method: 'GET', url: path}).
				success(function(data, status) {
					fac.facilities = data;
				});
				sessionStorage.facs = fac.facilities;
		};

		$scope.assign = function(){
			$scope.facilities = sessionStorage.facs;
		};

		$scope.getFac = function() {
			var path = '/facilities/' + 1;		// need to fix this; dynamically add facility number
			$http({method: 'GET', url: $scope.userGetPath}).
				success(function(data, status) {
					if(data.length) {
						var facVals = data[0];

					}
				});
		};

	}]);

	app.controller('CourtController', ['$scope', function($scope){
 		$scope.courts = [
			{
				name: 'Bulldog Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Falcon Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Shark Court',
				image: "../assets/rb.jpg"
			},
			{
				name: 'Courgar Court',
				image: "../assets/rb.jpg"
			}

		];
	}]);

	app.controller('CalendarController', ['$scope', function($scope){
	 		$scope.calendars = [
			['7 am','7 am','7 am','7 am','7 am','7 am','7 am'],
			['8 am','8 am','8 am','8 am','8 am','8 am','8 am'],
			['9 am','9 am','9 am','9 am','9 am','9 am','9 am'],
			['10 am','10 am','10 am','10 am','10 am','10 am','10 am'],
			['11 am','11 am','11 am','11 am','11 am','11 am','11 am'],
			['12 pm','12 pm','12 pm','RESERVED','12 pm','12 pm','12 pm'],
			['1 pm','1 pm','1 pm','1 pm','1 pm','1 pm','1 pm'],
			['2 pm','2 pm','2 pm','2 pm','2 pm','2 pm','2 pm'],
			['3 pm','3 pm','3 pm','3 pm','3 pm','3 pm','3 pm'],
			['4 pm','4 pm','4 pm','4 pm','4 pm','4 pm','4 pm'],
			['5 pm','5 pm','5 pm','5 pm','5 pm','5 pm','5 pm'],
			['6 pm','6 pm','6 pm','6 pm','6 pm','6 pm','6 pm'],
			['7 pm','7 pm','7 pm','7 pm','7 pm','7 pm','7 pm'],
			['8 pm','8 pm','8 pm','8 pm','8 pm','8 pm','8 pm']

			];

		}]);

})();
<|endoftext|>


<commit_before>var Sounds = {
  source: null,
  result: {
    clips: [],
    sources: []
  }
};

var WebAudio = {
  context: new webkitAudioContext(),
  loadSound: function(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function() {
      if (xhr.readyState != 4) return;
      this.context.decodeAudioData(xhr.response, function(buffer) {
        cb && cb(buffer);
      });
    }.bind(this);

    xhr.send();
  },
  createSound: function(buffer) {
    var source = this.context.createBufferSource();
    source.buffer = buffer;
    source.connect(this.context.destination);
    return source;
  },
  playSound: function(source, delay, start, duration) {
    if (!start || !duration) {
      source.noteOn(this.context.currentTime + (delay || 0));
    } else if (start && duration) {
      source.noteGrainOn(this.context.currentTime + (delay || 0), start, duration);
    }
  },
  stopSound: function(source, delay) {
    source.noteOff(this.context.currentTime + (delay || 0));
  },
  source: null
};

var Clip = {
  createUI: function(src, offsetX, width, left) {
    var width = width || '100%';
    var clip = $('

').addClass('clip')
    .css('background-image', 'url("' + src + '")');
    width && clip.css('width', width);
    left && clip.css('left', left);
    offsetX && clip.css('background-position-x', -offsetX + 'px ');
    return clip;
  },
  create: function(selection, waveformWidth, duration) {
    var startTime = ((selection.x1 * duration) / waveformWidth) / 1000,
        duration   = (((selection.x2 * duration) / waveformWidth) / 1000) - startTime;

    return { startTime: startTime, duration: duration };
  }
};

var Animation = {
  update: function(initialTime, duration, renderer, ender) {
    var currentTime = WebAudio.context.currentTime - initialTime,
        currentDuration = duration(),
        progress = currentTime / currentDuration;

    if (currentTime <= currentDuration && renderer) {
      renderer(progress);
      webkitRequestAnimationFrame(function() {
        this.update(initialTime, duration, renderer, ender);
      }.bind(this));
    } else if (currentTime > currentDuration && ender) {
      ender();
    }
  }
};

var Wav = {};
Wav.createWaveFileData = (function() {
  var writeString = function(s, a, offset) {
    for (var i = 0; i < s.length; ++i) {
      a[offset + i] = s.charCodeAt(i);
    }
  };

  var writeInt16 = function(n, a, offset) {
    n = n | 0;
    a[offset + 0] = n & 255;
    a[offset + 1] = (n >> 8) & 255;
  };

  var writeInt32 = function(n, a, offset) {
    n = n | 0
    a[offset + 0] = n & 255;
    a[offset + 1] = (n >> 8) & 255;
    a[offset + 2] = (n >> 16) & 255;
    a[offset + 3] = (n >> 24) & 255;
  };

  var writeAudioBuffer = function(audioBuffer, a, offset) {
    var n = audioBuffer.length,
        bufferL = audioBuffer.getChannelData(0),
        sampleL,
        bufferR = audioBuffer.getChannelData(1),
        sampleR;

    for (var i = 0; i < n; ++i) {
      sampleL = bufferL[i] * 32768.0;
      sampleR = bufferR[i] * 32768.0;

      // Clip left and right samples to the limitations of 16-bit.
      // If we don't do this then we'll get nasty wrap-around distortion.
      if (sampleL < -32768) { sampleL = -32768; }
      if (sampleL >  32767) { sampleL =  32767; }
      if (sampleR < -32768) { sampleR = -32768; }
      if (sampleR >  32767) { sampleR =  32767; }

      writeInt16(sampleL, a, offset);
      writeInt16(sampleR, a, offset + 2);
      offset += 4;
    }
  };

  return function(audioBuffer) {
    var frameLength = audioBuffer.length,
        numberOfChannels = audioBuffer.numberOfChannels,
        sampleRate = audioBuffer.sampleRate,
        bitsPerSample = 16,
        byteRate = sampleRate * numberOfChannels * bitsPerSample / 8,
        blockAlign = numberOfChannels * bitsPerSample / 8,
        wavDataByteLength = frameLength * numberOfChannels * 2, // 16-bit audio
        headerByteLength = 44,
        totalLength = headerByteLength + wavDataByteLength,
        waveFileData = new Uint8Array(totalLength),
        subChunk1Size = 16, // for linear PCM
        subChunk2Size = wavDataByteLength,
        chunkSize = 4 + (8 + subChunk1Size) + (8 + subChunk2Size);

    writeString('RIFF', waveFileData, 0);
    writeInt32(chunkSize, waveFileData, 4);
    writeString('WAVE', waveFileData, 8);
    writeString('fmt ', waveFileData, 12);

    writeInt32(subChunk1Size, waveFileData, 16);      // SubChunk1Size (4)
    writeInt16(1, waveFileData, 20);                  // AudioFormat (2)
    writeInt16(numberOfChannels, waveFileData, 22);   // NumChannels (2)
    writeInt32(sampleRate, waveFileData, 24);         // SampleRate (4)
    writeInt32(byteRate, waveFileData, 28);           // ByteRate (4)
    writeInt16(blockAlign, waveFileData, 32);         // BlockAlign (2)
    writeInt32(bitsPerSample, waveFileData, 34);      // BitsPerSample (4)

    writeString('data', waveFileData, 36);
    writeInt32(subChunk2Size, waveFileData, 40);      // SubChunk2Size (4)

    // Write actual audio data starting at offset 44.
    writeAudioBuffer(audioBuffer, waveFileData, 44);

    return waveFileData;
  }
}());

var SoundRenderering = {
  create: function(duration, cb) {
    WebAudio.context = new webkitAudioContext(2, duration * 44100, 44100);
    WebAudio.context.oncomplete = function(event) {
      var data = Wav.createWaveFileData(event.renderedBuffer);
      WebAudio.context = new webkitAudioContext();
      cb && cb(data);
    };
    this.play();
    WebAudio.context.startRendering();
  },
  stop: function() {
    Sounds.result.sources.reverse().forEach(function(source) {
      WebAudio.stopSound(source);
    });
    Sounds.result.sources = [];
  },
  play: function() {
    var cue = -Sounds.result.clips[0].duration;

    this.stop();

    Sounds.result.clips.forEach(function(clip, i, clips) {
      cue += clips[i ? i - 1 : i].duration;
      Sounds.result.sources.push(WebAudio.createSound(Sounds.source.buffer));
      WebAudio.playSound(Sounds.result.sources[ Sounds.result.sources.length - 1 ], cue, clip.startTime, clip.duration);
    });

    Animation.update(WebAudio.context.currentTime, function() {
      return Sounds.result.sources.length ? Sounds.result.clips.map(function(clip) {
        return clip.duration;
      }).reduce(function(a, b) {
        return a + b;
      }) : 0;
    }, function(progress) {
      $('.track.result').find('.playhead').width((progress * 100).toFixed(3) + '%');
    }, function() {
      $('.track.result').find('.playhead').width(0);
    });
  }
};

var Uploading = {
  create: function(data) {
    var token = localStorage['access_token'] //|| '1-9330-522011-d7aec0c537d947e121';

    if (!token || token.length == 0) {
      alert('Please connect to SoundCloud first. Press C');
      return;
    }

    var title = $('#sound-title').html(),
        xhr = new XMLHttpRequest(),
        formData = new FormData(),
        bb = new (window.BlobBuilder || window.WebKitBlobBuilder)()

    bb.append(data.buffer);
    formData.append('track[asset_data]', bb.getBlob('audio/x-wav'));
    formData.append('track[title]', Sounds.source.title + ' AudioJedit Remix!');
    formData.append('track[sharing]', 'public');
    xhr.open('POST', 'https://api.soundcloud.com/tracks.json?oauth_token=' + token, true);
    xhr.onload = function(e) {
      $('#sound-title').html(title);
      $('.track.result').removeClass('uploading').find('.playhead').width(0);
      alert('Upload completed!');
    };

    xhr.onprogress = function(ev) {
      if(ev.lengthComputable) {
        var progress = (ev.loaded / ev.total) * 100;
        $('#sound-title').html('Uploading ' + progress + '%');
        $('.track.result').find('.playhead').width(progress + '%');
      }
    };

    $('.track.result').addClass('uploading');

    xhr.send(formData);
  }
};

$(window).bind('hashchange load', function() {
  var soundUrl = document.location.hash.substring(1);
  if (!soundUrl.length) return;

  $.getJSON(soundUrl + '.json', function(sound) {
    Sounds.source = sound;

    $('#sound-title').html(sound.title + ' by ' + '' + sound.user.username + '');

    $('.track.source').append(Clip.createUI(sound.waveform_url));

    WebAudio.loadSound(soundUrl + '/audio', function(buffer) {
      Sounds.source.buffer = buffer;
      var waveformHeight = $('.track.source').height();

      $('.track.source').addClass('loaded').imgAreaSelect({
        handles: true,
        instance: true,
        minHeight: waveformHeight,
        onSelectEnd: function(img, selection) {
          if (!selection.width) return false;

          var waveformWidth = $('.track.source').width(),
              clip = Clip.create(selection, waveformWidth, Sounds.source.duration);

          WebAudio.source && WebAudio.stopSound(WebAudio.source, 0);
          WebAudio.source = WebAudio.createSound(Sounds.source.buffer);
          WebAudio.playSound(WebAudio.source, 0, clip.startTime, clip.duration);
          Animation.update(WebAudio.context.currentTime, function() {
            return clip.duration;
          }, function(progress) {
            $('.track.source').find('.playhead').css('left', selection.x1).width(progress * selection.width | 0);
          }, function() {
            var selectionWidth = $('.track.source').imgAreaSelect({ instance: true }).getSelection().width;
            $('.track.source').find('.playhead').width(selectionWidth);
          });
        }
      });
    });
  });
})
.bind('keydown', function(ev) {
  var keyMap = {
    27: function() { // Escape
      var $sourceTrack = $('.track.source');
      $sourceTrack.imgAreaSelect({ instance: true }).cancelSelection();
      $sourceTrack.find('.playhead').css({ left: 0, width: 0});
    },
    13: function() { // Enter
      var $sourceTrack = $('.track.source'),
          $resultTrack = $('.track.result'),
          selection = $sourceTrack.imgAreaSelect({ instance: true }).getSelection(),
          clip = Clip.create(selection, $sourceTrack.width(), Sounds.source.duration);

      $resultTrack.append(Clip.createUI(Sounds.source.waveform_url, selection.x1, selection.width, $resultTrack.width()))
      .width($resultTrack.width() + selection.width);

      Sounds.result.clips.push(clip);
    },
    32: function() { // Space
      SoundRenderering.play();
    },
    67: function() { // c - Connect with SoundCloud
      SC.connect({
        scope: 'non-expiring',
        client_id: '1288146c708a6fa789f74748fe960337',
        redirect_uri: 'http://audiojedit.herokuapp.com/public/soundcloud-callback.html',
        connected: function() {
          localStorage['access_token'] = SC.options.access_token;
        }
      });
    },
    85: function() { // u - Upload to SoundCloud
      if (!Sounds.result.clips.length) {
        alert('You have nothing to upload!');
        return;
      }

      SoundRenderering.create(Sounds.result.clips.map(function(clip) {
        return clip.duration;
      }).reduce(function(a, b) {
        return a + b;
      }), function(data) {
        Uploading.create(data); // Yay
      });
    },
    82: function() { // r = Reset result
      Sounds.result = {
        clips: [],
        sources: []
      };

      $('.track.result').width(0).find('.clip').remove();
    },
    83: function() { // s - Stop playing result
      SoundRenderering.stop();
    }
  };

  if (!ev.metaKey && !ev.shiftKey && !ev.ctrlKey && !ev.altKey) {
    keyMap[ev.keyCode] && keyMap[ev.keyCode]();
  }
});<commit_msg>Remove my token<commit_after>var Sounds = {
  source: null,
  result: {
    clips: [],
    sources: []
  }
};

var WebAudio = {
  context: new webkitAudioContext(),
  loadSound: function(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function() {
      if (xhr.readyState != 4) return;
      this.context.decodeAudioData(xhr.response, function(buffer) {
        cb && cb(buffer);
      });
    }.bind(this);

    xhr.send();
  },
  createSound: function(buffer) {
    var source = this.context.createBufferSource();
    source.buffer = buffer;
    source.connect(this.context.destination);
    return source;
  },
  playSound: function(source, delay, start, duration) {
    if (!start || !duration) {
      source.noteOn(this.context.currentTime + (delay || 0));
    } else if (start && duration) {
      source.noteGrainOn(this.context.currentTime + (delay || 0), start, duration);
    }
  },
  stopSound: function(source, delay) {
    source.noteOff(this.context.currentTime + (delay || 0));
  },
  source: null
};

var Clip = {
  createUI: function(src, offsetX, width, left) {
    var width = width || '100%';
    var clip = $('

').addClass('clip')
    .css('background-image', 'url("' + src + '")');
    width && clip.css('width', width);
    left && clip.css('left', left);
    offsetX && clip.css('background-position-x', -offsetX + 'px ');
    return clip;
  },
  create: function(selection, waveformWidth, duration) {
    var startTime = ((selection.x1 * duration) / waveformWidth) / 1000,
        duration   = (((selection.x2 * duration) / waveformWidth) / 1000) - startTime;

    return { startTime: startTime, duration: duration };
  }
};

var Animation = {
  update: function(initialTime, duration, renderer, ender) {
    var currentTime = WebAudio.context.currentTime - initialTime,
        currentDuration = duration(),
        progress = currentTime / currentDuration;

    if (currentTime <= currentDuration && renderer) {
      renderer(progress);
      webkitRequestAnimationFrame(function() {
        this.update(initialTime, duration, renderer, ender);
      }.bind(this));
    } else if (currentTime > currentDuration && ender) {
      ender();
    }
  }
};

var Wav = {};
Wav.createWaveFileData = (function() {
  var writeString = function(s, a, offset) {
    for (var i = 0; i < s.length; ++i) {
      a[offset + i] = s.charCodeAt(i);
    }
  };

  var writeInt16 = function(n, a, offset) {
    n = n | 0;
    a[offset + 0] = n & 255;
    a[offset + 1] = (n >> 8) & 255;
  };

  var writeInt32 = function(n, a, offset) {
    n = n | 0
    a[offset + 0] = n & 255;
    a[offset + 1] = (n >> 8) & 255;
    a[offset + 2] = (n >> 16) & 255;
    a[offset + 3] = (n >> 24) & 255;
  };

  var writeAudioBuffer = function(audioBuffer, a, offset) {
    var n = audioBuffer.length,
        bufferL = audioBuffer.getChannelData(0),
        sampleL,
        bufferR = audioBuffer.getChannelData(1),
        sampleR;

    for (var i = 0; i < n; ++i) {
      sampleL = bufferL[i] * 32768.0;
      sampleR = bufferR[i] * 32768.0;

      // Clip left and right samples to the limitations of 16-bit.
      // If we don't do this then we'll get nasty wrap-around distortion.
      if (sampleL < -32768) { sampleL = -32768; }
      if (sampleL >  32767) { sampleL =  32767; }
      if (sampleR < -32768) { sampleR = -32768; }
      if (sampleR >  32767) { sampleR =  32767; }

      writeInt16(sampleL, a, offset);
      writeInt16(sampleR, a, offset + 2);
      offset += 4;
    }
  };

  return function(audioBuffer) {
    var frameLength = audioBuffer.length,
        numberOfChannels = audioBuffer.numberOfChannels,
        sampleRate = audioBuffer.sampleRate,
        bitsPerSample = 16,
        byteRate = sampleRate * numberOfChannels * bitsPerSample / 8,
        blockAlign = numberOfChannels * bitsPerSample / 8,
        wavDataByteLength = frameLength * numberOfChannels * 2, // 16-bit audio
        headerByteLength = 44,
        totalLength = headerByteLength + wavDataByteLength,
        waveFileData = new Uint8Array(totalLength),
        subChunk1Size = 16, // for linear PCM
        subChunk2Size = wavDataByteLength,
        chunkSize = 4 + (8 + subChunk1Size) + (8 + subChunk2Size);

    writeString('RIFF', waveFileData, 0);
    writeInt32(chunkSize, waveFileData, 4);
    writeString('WAVE', waveFileData, 8);
    writeString('fmt ', waveFileData, 12);

    writeInt32(subChunk1Size, waveFileData, 16);      // SubChunk1Size (4)
    writeInt16(1, waveFileData, 20);                  // AudioFormat (2)
    writeInt16(numberOfChannels, waveFileData, 22);   // NumChannels (2)
    writeInt32(sampleRate, waveFileData, 24);         // SampleRate (4)
    writeInt32(byteRate, waveFileData, 28);           // ByteRate (4)
    writeInt16(blockAlign, waveFileData, 32);         // BlockAlign (2)
    writeInt32(bitsPerSample, waveFileData, 34);      // BitsPerSample (4)

    writeString('data', waveFileData, 36);
    writeInt32(subChunk2Size, waveFileData, 40);      // SubChunk2Size (4)

    // Write actual audio data starting at offset 44.
    writeAudioBuffer(audioBuffer, waveFileData, 44);

    return waveFileData;
  }
}());

var SoundRenderering = {
  create: function(duration, cb) {
    WebAudio.context = new webkitAudioContext(2, duration * 44100, 44100);
    WebAudio.context.oncomplete = function(event) {
      var data = Wav.createWaveFileData(event.renderedBuffer);
      WebAudio.context = new webkitAudioContext();
      cb && cb(data);
    };
    this.play();
    WebAudio.context.startRendering();
  },
  stop: function() {
    Sounds.result.sources.reverse().forEach(function(source) {
      WebAudio.stopSound(source);
    });
    Sounds.result.sources = [];
  },
  play: function() {
    var cue = -Sounds.result.clips[0].duration;

    this.stop();

    Sounds.result.clips.forEach(function(clip, i, clips) {
      cue += clips[i ? i - 1 : i].duration;
      Sounds.result.sources.push(WebAudio.createSound(Sounds.source.buffer));
      WebAudio.playSound(Sounds.result.sources[ Sounds.result.sources.length - 1 ], cue, clip.startTime, clip.duration);
    });

    Animation.update(WebAudio.context.currentTime, function() {
      return Sounds.result.sources.length ? Sounds.result.clips.map(function(clip) {
        return clip.duration;
      }).reduce(function(a, b) {
        return a + b;
      }) : 0;
    }, function(progress) {
      $('.track.result').find('.playhead').width((progress * 100).toFixed(3) + '%');
    }, function() {
      $('.track.result').find('.playhead').width(0);
    });
  }
};

var Uploading = {
  create: function(data) {
    var token = localStorage['access_token'];

    if (!token || token.length == 0) {
      alert('Please connect to SoundCloud first. Press C');
      return;
    }

    var title = $('#sound-title').html(),
        xhr = new XMLHttpRequest(),
        formData = new FormData(),
        bb = new (window.BlobBuilder || window.WebKitBlobBuilder)()

    bb.append(data.buffer);
    formData.append('track[asset_data]', bb.getBlob('audio/x-wav'));
    formData.append('track[title]', Sounds.source.title + ' AudioJedit Remix!');
    formData.append('track[sharing]', 'public');
    xhr.open('POST', 'https://api.soundcloud.com/tracks.json?oauth_token=' + token, true);
    xhr.onload = function(e) {
      $('#sound-title').html(title);
      $('.track.result').removeClass('uploading').find('.playhead').width(0);
      alert('Upload completed!');
    };

    xhr.onprogress = function(ev) {
      if(ev.lengthComputable) {
        var progress = (ev.loaded / ev.total) * 100;
        $('#sound-title').html('Uploading ' + progress + '%');
        $('.track.result').find('.playhead').width(progress + '%');
      }
    };

    $('.track.result').addClass('uploading');

    xhr.send(formData);
  }
};

$(window).bind('hashchange load', function() {
  var soundUrl = document.location.hash.substring(1);
  if (!soundUrl.length) return;

  $.getJSON(soundUrl + '.json', function(sound) {
    Sounds.source = sound;

    $('#sound-title').html(sound.title + ' by ' + '' + sound.user.username + '');

    $('.track.source').append(Clip.createUI(sound.waveform_url));

    WebAudio.loadSound(soundUrl + '/audio', function(buffer) {
      Sounds.source.buffer = buffer;
      var waveformHeight = $('.track.source').height();

      $('.track.source').addClass('loaded').imgAreaSelect({
        handles: true,
        instance: true,
        minHeight: waveformHeight,
        onSelectEnd: function(img, selection) {
          if (!selection.width) return false;

          var waveformWidth = $('.track.source').width(),
              clip = Clip.create(selection, waveformWidth, Sounds.source.duration);

          WebAudio.source && WebAudio.stopSound(WebAudio.source, 0);
          WebAudio.source = WebAudio.createSound(Sounds.source.buffer);
          WebAudio.playSound(WebAudio.source, 0, clip.startTime, clip.duration);
          Animation.update(WebAudio.context.currentTime, function() {
            return clip.duration;
          }, function(progress) {
            $('.track.source').find('.playhead').css('left', selection.x1).width(progress * selection.width | 0);
          }, function() {
            var selectionWidth = $('.track.source').imgAreaSelect({ instance: true }).getSelection().width;
            $('.track.source').find('.playhead').width(selectionWidth);
          });
        }
      });
    });
  });
})
.bind('keydown', function(ev) {
  var keyMap = {
    27: function() { // Escape
      var $sourceTrack = $('.track.source');
      $sourceTrack.imgAreaSelect({ instance: true }).cancelSelection();
      $sourceTrack.find('.playhead').css({ left: 0, width: 0});
    },
    13: function() { // Enter
      var $sourceTrack = $('.track.source'),
          $resultTrack = $('.track.result'),
          selection = $sourceTrack.imgAreaSelect({ instance: true }).getSelection(),
          clip = Clip.create(selection, $sourceTrack.width(), Sounds.source.duration);

      $resultTrack.append(Clip.createUI(Sounds.source.waveform_url, selection.x1, selection.width, $resultTrack.width()))
      .width($resultTrack.width() + selection.width);

      Sounds.result.clips.push(clip);
    },
    32: function() { // Space
      SoundRenderering.play();
    },
    67: function() { // c - Connect with SoundCloud
      SC.connect({
        scope: 'non-expiring',
        client_id: '1288146c708a6fa789f74748fe960337',
        redirect_uri: 'http://audiojedit.herokuapp.com/public/soundcloud-callback.html',
        connected: function() {
          localStorage['access_token'] = SC.options.access_token;
        }
      });
    },
    85: function() { // u - Upload to SoundCloud
      if (!Sounds.result.clips.length) {
        alert('You have nothing to upload!');
        return;
      }

      SoundRenderering.create(Sounds.result.clips.map(function(clip) {
        return clip.duration;
      }).reduce(function(a, b) {
        return a + b;
      }), function(data) {
        Uploading.create(data); // Yay
      });
    },
    82: function() { // r = Reset result
      Sounds.result = {
        clips: [],
        sources: []
      };

      $('.track.result').width(0).find('.clip').remove();
    },
    83: function() { // s - Stop playing result
      SoundRenderering.stop();
    }
  };

  if (!ev.metaKey && !ev.shiftKey && !ev.ctrlKey && !ev.altKey) {
    keyMap[ev.keyCode] && keyMap[ev.keyCode]();
  }
});<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////

// set center coordinates
var centerlat = 32.878486;
var centerlon = -117.241435;

// set default zoom level
var zoomLevel = 15;

var currentPoint = 604;
var discountRatio;
var control;

// set source for map tiles
ATTR = '© OpenStreetMap contributors, ' +
  'CC-BY-SA | ' +
  '© CartoDB';

CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

//Mapzen API Key
L.Mapzen.apiKey = "mapzen-2DryXS8";
// initialize map
var map = L.Mapzen.map('map');
map.setView([centerlat, centerlon], 15);

waypoints = [L.latLng(centerlat, centerlon)];

var newIcon = L.Icon.extend({
      options: {
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
      }
    });

addMarkers();

function createButton(label, container) {
    var btn = L.DomUtil.create('button', '', container);
    btn.setAttribute('type', 'button');
    btn.innerHTML = label;
    return btn;
}

/*
marker1.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});

marker2.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});

marker3.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});
*/
map.on('click', function(e) {
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
    map.closePopup();
});

/////////////////////////////////////////////////////////////////////////////////////////////
//generating the GeoJSON objects//
/////////////////////////////////////////////////////////////////////////////////////////////

//create some GeoJSON points to be sampled (function below)
var dotcount = 200000;
var dots = make_dots(dotcount);

//parameters for hex grid
//var bbox = [-117.341445, 32.778486, -116.241435, 32.978486];
var bbox = [-117.3, 32.8, -117.15, 32.95];
var cellWidth = 0.4;
var units = 'miles';

//create hex grid and count points within each cell
var hexgrid = turf.hexGrid(bbox, cellWidth, units);

function getRandomCoordinates(radius, uniform) {
  // Generate two random numbers1
  var a = Math.random(),
    b = Math.random();

  // Flip for more uniformity.
  if (uniform) {
    if (b < a) {
      var c = b;
      b = a;
      a = c;
    }
  }

  // It's all triangles.
  return [
    b * radius * Math.cos(2 * Math.PI * a / b),
    b * radius * Math.sin(2 * Math.PI * a / b)
  ];
}

function getRandomLocation(latitude, longitude, radiusInMeters) {
  var randomCoordinates = getRandomCoordinates(radiusInMeters, true);

  // Earths radius in meters via WGS 84 model.
  var earth = 6378137;

  // Offsets in meters.
  var northOffset = randomCoordinates[0],
    eastOffset = randomCoordinates[1];

  // Offset coordinates in radians.
  var offsetLatitude = northOffset / earth,
    offsetLongitude = eastOffset / (earth * Math.cos(Math.PI * (latitude / 180)));

  // Offset position in decimal degrees.
  return {
    latitude: latitude + (offsetLatitude * (180 / Math.PI)),
    longitude: longitude + (offsetLongitude * (180 / Math.PI))
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////
//legend//
/////////////////////////////////////////////////////////////////////////////////////////////

//create legend
var hexlegend = L.control({
  position: 'bottomleft'
});
//generate legend contents
hexlegend.onAdd = function(map) {
  //set up legend grades and labels
  var div = L.DomUtil.create('div', 'info legend'),
    grades = [1, 2, 3, 4, 5],
    labels = ['Surge Multiplier'],
    colorval = [100, 200, 300, 400, 500, 600],
    from, to;

  //iterate through grades and create a color field and label for each
  labels.push(' ' + 'None');
  for (var i = 0; i < grades.length; i++) {
    from = grades[i]+0.1;
    to = grades[i + 1];
    colorin = colorval[i+1];
    labels.push(' ' + from + (to ? 'x – '+to+'.0x' : 'x+'));
  }
  div.innerHTML = labels.join('
');
  return div;
};
hexlegend.addTo(map);

/////////////////////////////////////////////////////////////////////////////////////////////
//styling functions//
/////////////////////////////////////////////////////////////////////////////////////////////

//highlight style
var hexStyleHighlight = {
  color: "#336",
  weight: 2,
  opacity: .5,
};

//create color ramp
function getColor(y) {
  return y == undefined ? '#888' :
    y < 100 ? '#FFFFFF':
    y < 200 ? '#FEFEFE' :
    y < 300 ? '#AAAAAA' :
    y < 400 ? '#FFFB12' :
    y < 500 ? '#E8C115' :
    y < 600 ? '#FFA100' :
    '#FF2000';
}

//create style, with fillColor picked from color ramp
function style(feature) {
  return {
    fillColor: getColor(feature.properties.pt_count),
    color: "#888",
    weight: 0.5,
    opacity: 1,
    fillOpacity: 0.3//0.8
  };
}

//attach styles and popups to the hex layer
function highlightHex(e) {
  var layer = e.target;
  layer.setStyle(hexStyleHighlight);
  if (!L.Browser.ie && !L.Browser.opera) {
    layer.bringToFront();
  }
}

function resetHexHighlight(e) {
  var layer = e.target;
  var hexStyleDefault = style(layer.feature);
  layer.setStyle(hexStyleDefault);
}

function calculateSave(i) {
  return Math.round(100*(1-(i+100)/(currentPoint+100))) //currentPoint is hardcoded (604)?
}

function onEachHex(feature, layer) {
  var hexStyleDefault = style(layer.feature);
  layer.setStyle(hexStyleDefault);
  layer.on('click', function(e) {
    discountRatio = calculateSave(feature.properties.pt_count);
    control.remove();
    control = L.Routing.control({
      plan: L.Routing.plan(waypoints, {
        createMarker: function(i, wp) {
          return L.marker(wp.latLng, {
            draggable: false,
            icon: new newIcon({iconUrl: './images/marker.png'})
          });
        }
      }),
      router: L.Routing.mapzen("mapzen-2DryXS8", {costing:"pedestrian"}),
      formatter: new L.Routing.mapzenFormatter(),
      summaryTemplate:'
{name}

{distance}, {time}
' + discountRatio + '% cheaper
',
      routeWhileDragging: false,
      fitSelectedRoutes: false
        //routeWhileDragging: true

    });
    control.addTo(map);
    if(discountRatio > 0){
      console.log("Selected location is %f% cheaper", discountRatio);
    } else if(discountRatio < 0){
      console.log("Selected location is %f% more expensive", -discountRatio);
    } else if(discountRatio == 0){
      console.log("Selected location is the same price");
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////
//synthetic GeoJSON functions//
/////////////////////////////////////////////////////////////////////////////////////////////

//cheapo normrand function
function normish(mean, range) {
  var num_out = ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() - 4) / 4) * range + mean;
  return num_out;
}

//create geojson data with random ~normal distribution
function make_dots(dotcount) {

  var dots = {
    type: "FeatureCollection",
    features: []
  };

  for (var i = 0; i < dotcount; ++i) {
    var loc = getRandomLocation(40.769996, -73.973007, 5000);

    var t = L.marker([loc.latitude, loc.longitude]);

    dots.features.push(t.toGeoJSON());
  }
  return dots;
}

function setPrefs() {
  var x = document.getElementById("pref_form");
  var dist = (x.elements[0].value);
  console.log(dist);
  map.setZoom((18-dist));
  closeNav();
  return false;
}

function loadPrices(){
/*
//center
arr[299] = 500;

//1 away
arr[272] = 400;
arr[273] = 300;

arr[298] = 400;
arr[300] = 300;

arr[324] = 500;
arr[325] = 200;

//2 away
arr[246] = 000;
arr[247] = 000;
arr[248] = 000;

arr[271] = 100;
arr[274] = 100;

arr[297] = 100;
arr[301] = 000;

arr[323] = 200;
arr[326] = 100;

arr[350] = 400;
arr[351] = 300;
arr[352] = 000;
*/

  for(var x = 0; x < Object.keys(hexgrid.features).length; x++) {
    hexgrid.features[x].properties['pt_count'] = prices[x];
    /*https://github.com/GIScience/osmatrix-client/blob/master/js/osmatrix.js
     * Example of getting feature based on coordinates
    */
  }

  L.geoJson(hexgrid, {onEachFeature: onEachHex}).addTo(map);
}

function addMarkers()
{
    marker1 = L.marker([32.873, -117.238])
      .bindTooltip("81% Cheaper
 7min walk",
          {
            permanent: true,
            direction: 'top',
          }
    ).addTo(map);

    marker2 = L.marker([32.878, -117.248])
      .bindTooltip("35% Cheaper
 11min walk",
          {
            permanent: true,
            direction: 'top'
          }
    ).addTo(map);

}

if (typeof(control) == "undefined") {
  control = L.Routing.control({
    plan: L.Routing.plan(waypoints, {
      createMarker: function(i, wp) {
        return L.marker(wp.latLng, {
          draggable: false,
          icon: new newIcon({iconUrl: './images/marker.png'})
        });
      }
    }),
    router: L.Routing.mapzen("mapzen-2DryXS8", {costing:"pedestrian"}),
    formatter: new L.Routing.mapzenFormatter(),
    summaryTemplate:'
{name}

{distance}, {time}
' + discountRatio + '% cheaper
',
    routeWhileDragging: false,
    fitSelectedRoutes: false
      //routeWhileDragging: true

  });
  control.addTo(map);
}
<commit_msg>fixed routing price info<commit_after>/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////

// set center coordinates
var centerlat = 32.878486;
var centerlon = -117.241435;

// set default zoom level
var zoomLevel = 15;

var currentPoint = 604;
var discountRatio;
var control;

// set source for map tiles
ATTR = '© OpenStreetMap contributors, ' +
  'CC-BY-SA | ' +
  '© CartoDB';

CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';

//Mapzen API Key
L.Mapzen.apiKey = "mapzen-2DryXS8";
// initialize map
var map = L.Mapzen.map('map');
map.setView([centerlat, centerlon], 15);

waypoints = [L.latLng(centerlat, centerlon)];

var newIcon = L.Icon.extend({
      options: {
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
      }
    });

addMarkers();

function createButton(label, container) {
    var btn = L.DomUtil.create('button', '', container);
    btn.setAttribute('type', 'button');
    btn.innerHTML = label;
    return btn;
}

/*
marker1.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});

marker2.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});

marker3.on('click', function(e){
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
});
*/
map.on('click', function(e) {
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
    map.closePopup();
});

/////////////////////////////////////////////////////////////////////////////////////////////
//generating the GeoJSON objects//
/////////////////////////////////////////////////////////////////////////////////////////////

//create some GeoJSON points to be sampled (function below)
var dotcount = 200000;
var dots = make_dots(dotcount);

//parameters for hex grid
//var bbox = [-117.341445, 32.778486, -116.241435, 32.978486];
var bbox = [-117.3, 32.8, -117.15, 32.95];
var cellWidth = 0.4;
var units = 'miles';

//create hex grid and count points within each cell
var hexgrid = turf.hexGrid(bbox, cellWidth, units);

function getRandomCoordinates(radius, uniform) {
  // Generate two random numbers1
  var a = Math.random(),
    b = Math.random();

  // Flip for more uniformity.
  if (uniform) {
    if (b < a) {
      var c = b;
      b = a;
      a = c;
    }
  }

  // It's all triangles.
  return [
    b * radius * Math.cos(2 * Math.PI * a / b),
    b * radius * Math.sin(2 * Math.PI * a / b)
  ];
}

function getRandomLocation(latitude, longitude, radiusInMeters) {
  var randomCoordinates = getRandomCoordinates(radiusInMeters, true);

  // Earths radius in meters via WGS 84 model.
  var earth = 6378137;

  // Offsets in meters.
  var northOffset = randomCoordinates[0],
    eastOffset = randomCoordinates[1];

  // Offset coordinates in radians.
  var offsetLatitude = northOffset / earth,
    offsetLongitude = eastOffset / (earth * Math.cos(Math.PI * (latitude / 180)));

  // Offset position in decimal degrees.
  return {
    latitude: latitude + (offsetLatitude * (180 / Math.PI)),
    longitude: longitude + (offsetLongitude * (180 / Math.PI))
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////
//legend//
/////////////////////////////////////////////////////////////////////////////////////////////

//create legend
var hexlegend = L.control({
  position: 'bottomleft'
});
//generate legend contents
hexlegend.onAdd = function(map) {
  //set up legend grades and labels
  var div = L.DomUtil.create('div', 'info legend'),
    grades = [1, 2, 3, 4, 5],
    labels = ['Surge Multiplier'],
    colorval = [100, 200, 300, 400, 500, 600],
    from, to;

  //iterate through grades and create a color field and label for each
  labels.push(' ' + 'None');
  for (var i = 0; i < grades.length; i++) {
    from = grades[i]+0.1;
    to = grades[i + 1];
    colorin = colorval[i+1];
    labels.push(' ' + from + (to ? 'x – '+to+'.0x' : 'x+'));
  }
  div.innerHTML = labels.join('
');
  return div;
};
hexlegend.addTo(map);

/////////////////////////////////////////////////////////////////////////////////////////////
//styling functions//
/////////////////////////////////////////////////////////////////////////////////////////////

//highlight style
var hexStyleHighlight = {
  color: "#336",
  weight: 2,
  opacity: .5,
};

//create color ramp
function getColor(y) {
  return y == undefined ? '#888' :
    y < 100 ? '#FFFFFF':
    y < 200 ? '#FEFEFE' :
    y < 300 ? '#AAAAAA' :
    y < 400 ? '#FFFB12' :
    y < 500 ? '#E8C115' :
    y < 600 ? '#FFA100' :
    '#FF2000';
}

//create style, with fillColor picked from color ramp
function style(feature) {
  return {
    fillColor: getColor(feature.properties.pt_count),
    color: "#888",
    weight: 0.5,
    opacity: 1,
    fillOpacity: 0.3//0.8
  };
}

//attach styles and popups to the hex layer
function highlightHex(e) {
  var layer = e.target;
  layer.setStyle(hexStyleHighlight);
  if (!L.Browser.ie && !L.Browser.opera) {
    layer.bringToFront();
  }
}

function resetHexHighlight(e) {
  var layer = e.target;
  var hexStyleDefault = style(layer.feature);
  layer.setStyle(hexStyleDefault);
}

function calculateSave(i) {
  return Math.round(100*(1-(i+100)/(currentPoint+100))) //currentPoint is hardcoded (604)?
}

function onEachHex(feature, layer) {
  var hexStyleDefault = style(layer.feature);
  layer.setStyle(hexStyleDefault);
  layer.on('click', function(e) {
    var toset;
    discountRatio = calculateSave(feature.properties.pt_count);
    if (discountRatio > 0)
      toset = discountRatio + '% cheaper';
    else if (discountRatio < 0)
      toset = -discountRatio + '% more expensive';
    else
      toset = 'Same price';
    control.remove();
    control = L.Routing.control({
      plan: L.Routing.plan(waypoints, {
        createMarker: function(i, wp) {
          return L.marker(wp.latLng, {
            draggable: false,
            icon: new newIcon({iconUrl: './images/marker.png'})
          });
        }
      }),
      router: L.Routing.mapzen("mapzen-2DryXS8", {costing:"pedestrian"}),
      formatter: new L.Routing.mapzenFormatter(),
      summaryTemplate:'
{name}

{distance}, {time}
' + toset,
      routeWhileDragging: false,
      fitSelectedRoutes: false
        //routeWhileDragging: true

    });
    control.addTo(map);
    if(discountRatio > 0){
      console.log("Selected location is %f% cheaper", discountRatio);
    } else if(discountRatio < 0){
      console.log("Selected location is %f% more expensive", -discountRatio);
    } else if(discountRatio == 0){
      console.log("Selected location is the same price");
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////
//synthetic GeoJSON functions//
/////////////////////////////////////////////////////////////////////////////////////////////

//cheapo normrand function
function normish(mean, range) {
  var num_out = ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random() - 4) / 4) * range + mean;
  return num_out;
}

//create geojson data with random ~normal distribution
function make_dots(dotcount) {

  var dots = {
    type: "FeatureCollection",
    features: []
  };

  for (var i = 0; i < dotcount; ++i) {
    var loc = getRandomLocation(40.769996, -73.973007, 5000);

    var t = L.marker([loc.latitude, loc.longitude]);

    dots.features.push(t.toGeoJSON());
  }
  return dots;
}

function setPrefs() {
  var x = document.getElementById("pref_form");
  var dist = (x.elements[0].value);
  console.log(dist);
  map.setZoom((18-dist));
  closeNav();
  return false;
}

function loadPrices(){
/*
//center
arr[299] = 500;

//1 away
arr[272] = 400;
arr[273] = 300;

arr[298] = 400;
arr[300] = 300;

arr[324] = 500;
arr[325] = 200;

//2 away
arr[246] = 000;
arr[247] = 000;
arr[248] = 000;

arr[271] = 100;
arr[274] = 100;

arr[297] = 100;
arr[301] = 000;

arr[323] = 200;
arr[326] = 100;

arr[350] = 400;
arr[351] = 300;
arr[352] = 000;
*/

  for(var x = 0; x < Object.keys(hexgrid.features).length; x++) {
    hexgrid.features[x].properties['pt_count'] = prices[x];
    /*https://github.com/GIScience/osmatrix-client/blob/master/js/osmatrix.js
     * Example of getting feature based on coordinates
    */
  }

  L.geoJson(hexgrid, {onEachFeature: onEachHex}).addTo(map);
}

function addMarkers()
{
    marker1 = L.marker([32.873, -117.238])
      .bindTooltip("81% Cheaper
 7min walk",
          {
            permanent: true,
            direction: 'top',
          }
    ).addTo(map);

    marker2 = L.marker([32.878, -117.248])
      .bindTooltip("35% Cheaper
 11min walk",
          {
            permanent: true,
            direction: 'top'
          }
    ).addTo(map);

}

if (typeof(control) == "undefined") {
  control = L.Routing.control({
    plan: L.Routing.plan(waypoints, {
      createMarker: function(i, wp) {
        return L.marker(wp.latLng, {
          draggable: false,
          icon: new newIcon({iconUrl: './images/marker.png'})
        });
      }
    }),
    router: L.Routing.mapzen("mapzen-2DryXS8", {costing:"pedestrian"}),
    formatter: new L.Routing.mapzenFormatter(),
    summaryTemplate:'
{name}

{distance}, {time}
' + discountRatio + '% cheaper
',
    routeWhileDragging: false,
    fitSelectedRoutes: false
      //routeWhileDragging: true

  });
  control.addTo(map);
}
<|endoftext|>


<commit_before>'use strict';

/*
 * Bootstrap Tanura.
 *
 * This script will bootstrap Tanura into an application.
 */

/**
 * Globally available information about Tanura.
 *
 * This object contains information about Tanura, that is available to the
 * hosting website.
 */
var tanura = {
    url: /.*\//.exec(document.currentScript.src)[0],
    nuve: null,
    erizo: null,
    whiteboard: null
};

(function() {
    var request = new XMLHttpRequest();
    request.addEventListener('load', function() {
        var replaceScriptNodes = node => {
            if (node.tagName === 'SCRIPT') {
                var script  = document.createElement('script');
                script.text = node.innerHTML;
                for(var i = node.attributes.length - 1; i >= 0; i--) {
                    script.setAttribute(
                        node.attributes[i].name, node.attributes[i].value);
                }
                node.parentNode.replaceChild(script, node);
            } else {
                var childs = node.childNodes;
                for (var i = 0; i < childs.length; i++) {
                    replaceScriptNodes(childs[i]);
                }
            }
        }

        document.getElementsByTagName('body')[0].innerHTML += this.responseText;

        // Regenerate all script nodes in the new content, since they will not
        // be loaded otherwise.
        replaceScriptNodes(document.getElementById('tanura-src'));
    });
    request.responseType = 'text';
    request.open(
        'GET', tanura.url + 'tanura.html.frag?base=' + tanura.url);
    request.send();
})()

<commit_msg>Add tanura.init().<commit_after>'use strict';

/*
 * Bootstrap Tanura.
 *
 * This script will bootstrap Tanura into an application.
 */

/**
 * Globally available information about Tanura.
 *
 * This object contains information about Tanura, that is available to the
 * hosting website.
 */
var tanura = {
    url: /.*\//.exec(document.currentScript.src)[0],
    options: null,
    nuve: null,
    erizo: null,
    whiteboard: null
};

/**
 * Initialize Tanura.
 */
tanura.init = (_) => {
    tanura.options = _ || {};

    // Start Tanura, if everything is loaded already. If Tanura is still
    // loading, it will automatically launch when ready.
    if (tanura.run) { tanura.run(); }
}

(function() {
    var request = new XMLHttpRequest();
    request.addEventListener('load', function() {
        var replaceScriptNodes = node => {
            if (node.tagName === 'SCRIPT') {
                var script  = document.createElement('script');
                script.text = node.innerHTML;
                for(var i = node.attributes.length - 1; i >= 0; i--) {
                    script.setAttribute(
                        node.attributes[i].name, node.attributes[i].value);
                }
                node.parentNode.replaceChild(script, node);
            } else {
                var childs = node.childNodes;
                for (var i = 0; i < childs.length; i++) {
                    replaceScriptNodes(childs[i]);
                }
            }
        }

        document.getElementsByTagName('body')[0].innerHTML += this.responseText;

        // Regenerate all script nodes in the new content, since they will not
        // be loaded otherwise.
        replaceScriptNodes(document.getElementById('tanura-src'));
    });
    request.responseType = 'text';
    request.open(
        'GET', tanura.url + 'tanura.html.frag?base=' + tanura.url);
    request.send();
})()

<|endoftext|>


<commit_before>function prepend(node, child) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	if (typeof child == "string") {
		node.insertAdjacentHTML("afterbegin", child);
	} else {
		node.insertBefore(child, node.childNodes[0]);
	}
}

function bind(node, event, callback) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	if (node) {
		node.addEventListener(event, callback);
	}
}

bind.one = function(node, event, callback) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	node.addEventListener(event, function self(e) {
		node.removeEventListener(event, self);
		callback.call(this, e);
	});
};

bind(document, "DOMContentLoaded", init);

function init() {
	var bookmark = function(){
		var MAX_LENGTH = 10,
			scrTop,
			nav, cmd, menu;

		function read() {
			var bookmarks;
			try {
				bookmarks = JSON.parse(localStorage.bookmarks);
				if (!(bookmarks instanceof Array)) {
					bookmarks = [];
				}
			} catch (err) {
				bookmarks = [];
			}
			return bookmarks;
		}

		function save(bookmarks) {
			while (bookmarks.length > MAX_LENGTH) {
				bookmarks.shift();
			}
			localStorage.bookmarks = JSON.stringify(bookmarks);
		}

		function add() {
			var bookmarks = read(),
				bookmark = {
					path: cv.curr.full,
					scrTop: window.scrollY,
					name: cv.curr.name
				};

			bookmarks.push(bookmark);
			addMenuItem(bookmark);

			save(bookmarks);

			panel.notify("Saved bookmark: " + cv.curr.full);
		}

		function load() {
			var bookmarks = read(),
				last = bookmarks[bookmarks.length - 1];

			if (!last) {
				panel.notify("Bookmark is empty");
			} else if (last.path == cv.curr.full) {
				scrTop = last.scrTop;
				open();
			} else {
				location.href = "/view?path=" + encodeURIComponent(last.path) + "#SCRTOP" + last.scrTop;
			}
		}

		function open() {
			window.scrollTo(window.scrollX, scrTop);
			if (window.scrollY != scrTop) {
				setTimeout(open, 200);
			} else {
				panel.notify("Bookmark opened: " + cv.curr.full);
				history.pushState("", document.title, window.location.pathname + window.location.search);
			}
		}

		function createMenu() {
			var bookmarks = read(),
				i;

			for (i = 0; i < bookmarks.length; i++) {
				addMenuItem(bookmarks[i]);
			}
		}

		function addMenuItem(bookmark) {
			var a = document.createElement("a");
			a.href = "/view?path=" + encodeURIComponent(bookmark.path) + "#SCRTOP" + bookmark.scrTop;
			a.textContent = bookmark.name;
			prepend(menu, a);
		}

		function hashOpen() {
			var match;
			if ((match = location.hash.match(/^#SCRTOP(\d+)/))) {
				scrTop = match[1];
				open();
			}
		}

		function showMenu() {
			nav.classList.add("show");
			cmd.classList.add("active");
			menu.classList.add("show");
			setTimeout(bindHideMenu);
		}

		function bindHideMenu() {
			bind.one(window, "click", hideMenu);
		}

		function hideMenu() {
			nav.classList.remove("show");
			cmd.classList.remove("active");
			menu.classList.remove("show");
		}

		cmd = document.querySelector(".command-bookmarks");
		nav = document.querySelector(".nav");
		menu = document.querySelector(".bookmark-menu");

		hashOpen();
		createMenu();

		bind(cmd, "click", showMenu);
		bind(window, "hashchange", hashOpen);

		return {
			load: load,
			add: add
		};
	}();

	function go(path, name) {
		path = encodeURIComponent(path);
		name = name ? "#" + name : "";
		return function () {
			location.href = "/view?path=" + path + name;
		};
	}

	var scroller = function(){

		function nextJump() {
			var imgs = images.current(),
				img = imgs[1] || imgs[0];
			if (img) {
				window.scrollBy(0, img.height);
			}
		}

		function prevJump() {
			var imgs = images.current(),
				img = imgs[imgs.length - 2] || imgs[0];
			if (img) {
				window.scrollBy(0, -img.height);
			}
		}

		function nextPage() {
			var imgs = images.current(),
				img = imgs[1] && imgs[1].top == window.scrollY ? imgs[1] : imgs[0];

			if (img) {
				window.scrollBy(0, img.top + img.height - window.scrollY);
			}
		}

		function prevPage() {
			var imgs = images.current(),
				img = imgs[0];

			if (img) {
				window.scrollBy(0, img.top - window.scrollY);
			}
		}

		return {
			nextJump: nextJump,
			prevJump: prevJump,
			nextPage: nextPage,
			prevPage: prevPage
		};
	}();

	var images = function(){

		function current() {
			var scrTop = window.scrollY,
				top = Math.round(document.querySelector(".images").getBoundingClientRect().top) + scrTop,
				windowHeight = window.innerHeight,
				select = [],
				images = document.querySelectorAll(".images img"),
				i, ch;

			for (i = 0; i < images.length; i++) {
				ch = images[i].clientHeight;
				if (top + ch < scrTop) {
					top += ch;
					continue;
				} else if (top <= scrTop + windowHeight) {
					select.push({
						top: top,
						height: ch
					});
					top += ch;
					continue;
				}
				break;
			}

			return select;
		}

		return {
			current: current
		};
	}();

	var panel = function(){
		var timer, x, y,
			hideStyle = document.querySelector("#hide-cursor-style"),
			nav = document.querySelector(".nav"),
			inner = document.querySelector(".container-inner"),
			notifyEl = document.querySelector(".notify");

		function show() {
			var scrWidth,
				scrTop = window.scrollY;

			document.body.classList.add("show-cursor");
			document.head.removeChild(hideStyle);

			scrWidth = document.documentElement.clientWidth - window.innerWidth + "px";
			nav.style.marginRight = scrWidth;
			inner.style.marginRight = scrWidth;

			window.scrollTo(window.scrollX, scrTop);
			timer = setTimeout(hide, 1000);
		}

		function hide() {
			document.head.appendChild(hideStyle);
			document.body.classList.remove("show-cursor");

			inner.style.marginRight = "";
			nav.style.marginRight = "";

			timer = null;
		}

		function handleMove(e) {
			// sometimes e.screenX and e.screenY will be 0
			if (!e.screenX && !e.screenY) {
				return;
			}
			if (x == null && y == null) {
				x = e.screenX;
				y = e.screenY;
				return;
			}
			// chrome fires move event even not moving
			if (e.screenX == x && e.screenY == y) {
				return;
			}
			x = e.screenX;
			y = e.screenY;
			if (timer) {
				clearTimeout(timer);
				timer = setTimeout(hide, 1000);
				return;
			}
			show();
		}

		var notifyTimer;
		function notify(s) {
			clearTimeout(notifyTimer);
			notifyEl.textContent = s;
			notifyEl.classList.add("show");
			notifyTimer = setTimeout(denotify, 1000);
		}

		function denotify() {
			notifyEl.classList.remove("show");
		}

		bind(window, "mousemove", handleMove);

		return {
			notify: notify
		};
	}();

	var explorer = function(){

		function open() {
			fetchival("/open").post({path: encodeURIComponent(cv.isFile ? cv.curr.dir : cv.curr.full)});
			panel.notify("Launch directory");
		}

		bind(".command-explorer", "click", open);

		return {
			open: open
		};
	}();

	(function dirSearch (){
		var box = document.querySelector(".dir-search-box"),
			cache = "";

		if (!box) {
			return;
		}

		function filter(value) {
			if (cache == value) {
				return;
			}
			if (cache + "\u3000" == value) {
				// typing
				return;
			}
			cache = value;

			var dirs = document.querySelectorAll(".dirs a"),
				i;

			for (i = 0; i < dirs.length; i++) {
				dirs[i].style.display = !value || dirs[i].textContent.indexOf(value) >= 0 ? "" : "none";
			}
		}

		function handleInput(e) {
			filter(e.target.value);
		}

		bind(box, "input", handleInput);

		if (box.value) {
			filter(box.value);
		}

	})();

	Mousetrap.bind("[", go(cv.prev && cv.prev.full));
	Mousetrap.bind("]", go(cv.next && cv.next.full));
	Mousetrap.bind("q", go(cv.curr.dir, cv.curr.name));
	Mousetrap.bind("b", bookmark.add);
	Mousetrap.bind("shift+b", bookmark.load);
	Mousetrap.bind("ctrl+enter", explorer.open);
	Mousetrap.bind("left", scroller.prevPage);
	Mousetrap.bind("right", scroller.nextPage);
	Mousetrap.bind("shift+left", scroller.prevJump);
	Mousetrap.bind("shift+right", scroller.nextJump);

}
<commit_msg>Fix shift selection bug<commit_after>function prepend(node, child) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	if (typeof child == "string") {
		node.insertAdjacentHTML("afterbegin", child);
	} else {
		node.insertBefore(child, node.childNodes[0]);
	}
}

function bind(node, event, callback) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	if (node) {
		node.addEventListener(event, callback);
	}
}

bind.one = function(node, event, callback) {
	if (typeof node == "string") {
		node = document.querySelector(node);
	}
	node.addEventListener(event, function self(e) {
		node.removeEventListener(event, self);
		callback.call(this, e);
	});
};

bind(document, "DOMContentLoaded", init);

function init() {
	var bookmark = function(){
		var MAX_LENGTH = 10,
			scrTop,
			nav, cmd, menu;

		function read() {
			var bookmarks;
			try {
				bookmarks = JSON.parse(localStorage.bookmarks);
				if (!(bookmarks instanceof Array)) {
					bookmarks = [];
				}
			} catch (err) {
				bookmarks = [];
			}
			return bookmarks;
		}

		function save(bookmarks) {
			while (bookmarks.length > MAX_LENGTH) {
				bookmarks.shift();
			}
			localStorage.bookmarks = JSON.stringify(bookmarks);
		}

		function add() {
			var bookmarks = read(),
				bookmark = {
					path: cv.curr.full,
					scrTop: window.scrollY,
					name: cv.curr.name
				};

			bookmarks.push(bookmark);
			addMenuItem(bookmark);

			save(bookmarks);

			panel.notify("Saved bookmark: " + cv.curr.full);
		}

		function load() {
			var bookmarks = read(),
				last = bookmarks[bookmarks.length - 1];

			if (!last) {
				panel.notify("Bookmark is empty");
			} else if (last.path == cv.curr.full) {
				scrTop = last.scrTop;
				open();
			} else {
				location.href = "/view?path=" + encodeURIComponent(last.path) + "#SCRTOP" + last.scrTop;
			}
		}

		function open() {
			window.scrollTo(window.scrollX, scrTop);
			if (window.scrollY != scrTop) {
				setTimeout(open, 200);
			} else {
				panel.notify("Bookmark opened: " + cv.curr.full);
				history.pushState("", document.title, window.location.pathname + window.location.search);
			}
		}

		function createMenu() {
			var bookmarks = read(),
				i;

			for (i = 0; i < bookmarks.length; i++) {
				addMenuItem(bookmarks[i]);
			}
		}

		function addMenuItem(bookmark) {
			var a = document.createElement("a");
			a.href = "/view?path=" + encodeURIComponent(bookmark.path) + "#SCRTOP" + bookmark.scrTop;
			a.textContent = bookmark.name;
			prepend(menu, a);
		}

		function hashOpen() {
			var match;
			if ((match = location.hash.match(/^#SCRTOP(\d+)/))) {
				scrTop = match[1];
				open();
			}
		}

		function showMenu() {
			nav.classList.add("show");
			cmd.classList.add("active");
			menu.classList.add("show");
			setTimeout(bindHideMenu);
		}

		function bindHideMenu() {
			bind.one(window, "click", hideMenu);
		}

		function hideMenu() {
			nav.classList.remove("show");
			cmd.classList.remove("active");
			menu.classList.remove("show");
		}

		cmd = document.querySelector(".command-bookmarks");
		nav = document.querySelector(".nav");
		menu = document.querySelector(".bookmark-menu");

		hashOpen();
		createMenu();

		bind(cmd, "click", showMenu);
		bind(window, "hashchange", hashOpen);

		return {
			load: load,
			add: add
		};
	}();

	function go(path, name) {
		path = encodeURIComponent(path);
		name = name ? "#" + name : "";
		return function () {
			location.href = "/view?path=" + path + name;
		};
	}

	var scroller = function(){

		function nextJump(e) {
			e.preventDefault();
			var imgs = images.current(),
				img = imgs[1] || imgs[0];
			if (img) {
				window.scrollBy(0, img.height);
			}
		}

		function prevJump(e) {
			e.preventDefault();
			var imgs = images.current(),
				img = imgs[imgs.length - 2] || imgs[0];
			if (img) {
				window.scrollBy(0, -img.height);
			}
		}

		function nextPage() {
			var imgs = images.current(),
				img = imgs[1] && imgs[1].top == window.scrollY ? imgs[1] : imgs[0];

			if (img) {
				window.scrollBy(0, img.top + img.height - window.scrollY);
			}
		}

		function prevPage() {
			var imgs = images.current(),
				img = imgs[0];

			if (img) {
				window.scrollBy(0, img.top - window.scrollY);
			}
		}

		return {
			nextJump: nextJump,
			prevJump: prevJump,
			nextPage: nextPage,
			prevPage: prevPage
		};
	}();

	var images = function(){

		function current() {
			var scrTop = window.scrollY,
				top = Math.round(document.querySelector(".images").getBoundingClientRect().top) + scrTop,
				windowHeight = window.innerHeight,
				select = [],
				images = document.querySelectorAll(".images img"),
				i, ch;

			for (i = 0; i < images.length; i++) {
				ch = images[i].clientHeight;
				if (top + ch < scrTop) {
					top += ch;
					continue;
				} else if (top <= scrTop + windowHeight) {
					select.push({
						top: top,
						height: ch
					});
					top += ch;
					continue;
				}
				break;
			}

			return select;
		}

		return {
			current: current
		};
	}();

	var panel = function(){
		var timer, x, y,
			hideStyle = document.querySelector("#hide-cursor-style"),
			nav = document.querySelector(".nav"),
			inner = document.querySelector(".container-inner"),
			notifyEl = document.querySelector(".notify");

		function show() {
			var scrWidth,
				scrTop = window.scrollY;

			document.body.classList.add("show-cursor");
			document.head.removeChild(hideStyle);

			scrWidth = document.documentElement.clientWidth - window.innerWidth + "px";
			nav.style.marginRight = scrWidth;
			inner.style.marginRight = scrWidth;

			window.scrollTo(window.scrollX, scrTop);
			timer = setTimeout(hide, 1000);
		}

		function hide() {
			document.head.appendChild(hideStyle);
			document.body.classList.remove("show-cursor");

			inner.style.marginRight = "";
			nav.style.marginRight = "";

			timer = null;
		}

		function handleMove(e) {
			// sometimes e.screenX and e.screenY will be 0
			if (!e.screenX && !e.screenY) {
				return;
			}
			if (x == null && y == null) {
				x = e.screenX;
				y = e.screenY;
				return;
			}
			// chrome fires move event even not moving
			if (e.screenX == x && e.screenY == y) {
				return;
			}
			x = e.screenX;
			y = e.screenY;
			if (timer) {
				clearTimeout(timer);
				timer = setTimeout(hide, 1000);
				return;
			}
			show();
		}

		var notifyTimer;
		function notify(s) {
			clearTimeout(notifyTimer);
			notifyEl.textContent = s;
			notifyEl.classList.add("show");
			notifyTimer = setTimeout(denotify, 1000);
		}

		function denotify() {
			notifyEl.classList.remove("show");
		}

		bind(window, "mousemove", handleMove);

		return {
			notify: notify
		};
	}();

	var explorer = function(){

		function open() {
			fetchival("/open").post({path: encodeURIComponent(cv.isFile ? cv.curr.dir : cv.curr.full)});
			panel.notify("Launch directory");
		}

		bind(".command-explorer", "click", open);

		return {
			open: open
		};
	}();

	(function dirSearch (){
		var box = document.querySelector(".dir-search-box"),
			cache = "";

		if (!box) {
			return;
		}

		function filter(value) {
			if (cache == value) {
				return;
			}
			if (cache + "\u3000" == value) {
				// typing
				return;
			}
			cache = value;

			var dirs = document.querySelectorAll(".dirs a"),
				i;

			for (i = 0; i < dirs.length; i++) {
				dirs[i].style.display = !value || dirs[i].textContent.indexOf(value) >= 0 ? "" : "none";
			}
		}

		function handleInput(e) {
			filter(e.target.value);
		}

		bind(box, "input", handleInput);

		if (box.value) {
			filter(box.value);
		}

	})();

	Mousetrap.bind("[", go(cv.prev && cv.prev.full));
	Mousetrap.bind("]", go(cv.next && cv.next.full));
	Mousetrap.bind("q", go(cv.curr.dir, cv.curr.name));
	Mousetrap.bind("b", bookmark.add);
	Mousetrap.bind("shift+b", bookmark.load);
	Mousetrap.bind("ctrl+enter", explorer.open);
	Mousetrap.bind("left", scroller.prevPage);
	Mousetrap.bind("right", scroller.nextPage);
	Mousetrap.bind("shift+left", scroller.prevJump);
	Mousetrap.bind("shift+right", scroller.nextJump);

}
<|endoftext|>


<commit_before>
var Utils = require('asNEAT/utils')['default'],
    log = Utils.log,
    asNEAT = require('asNEAT/asNEAT')['default'],
    context = asNEAT.context,
    offlineContext = asNEAT.offlineContext,
    name = "Connection";

// TODO: Different kinds of connections?
var Connection = function(parameters) {
  Utils.extend(this, this.defaultParameters, parameters);
  this.gainNode = null;
  this.hasChanged = false;
  // Only generate a new id if one isn't given in the parameters
  if (parameters && typeof parameters.id !== 'undefined')
    this.id = parameters.id;
  else
    this.id = Utils.createHash();
};

Connection.prototype.name = name;
Connection.prototype.defaultParameters = {
  sourceNode: null,
  targetNode: null,

  // null if connecting to audio input of targetNode
  targetParameter: null,
  targetParameterNodeName: "node",

  weight: 1.0,
  enabled: true,

  mutationDeltaChance: 0.8,
  mutationDeltaInterpolationType: Utils.InterpolationType.EXPONENTIAL,
  mutationDelta: {min: [0.05, 0.3], max: [0.1, 0.6]},
  randomMutationRange: {min: 0.1, max: 1.5}
};

/**
  @param clonedsourceNode {Node} (optional)
  @param clonedtargetNode {Node} (optional)
*/
Connection.prototype.clone = function(clonedsourceNode, clonedtargetNode) {
  var sourceNode = clonedsourceNode || this.sourceNode.clone();
  var targetNode = clonedtargetNode || this.targetNode.clone();
  return new Connection({
    id: this.id,
    sourceNode: sourceNode,
    targetNode: targetNode,
    targetParameter: this.targetParameter,
    targetParameterNodeName: this.targetParameterNodeName,
    weight: this.weight,
    enabled: this.enabled,
    mutationDeltaChance: this.mutationDeltaChance,
    mutationDeltaInterpolationType: this.mutationDeltaInterpolationType,
    mutationDelta: _.clone(this.mutationDelta),
    randomMutationRange: _.clone(this.randomMutationRange)
  });
};
Connection.prototype.connect = function(contextPair) {
  connect.call(this, contextPair);
};
Connection.prototype.offlineConnect = function(contextPair) {
  connect.call(this, contextPair, "offline");
};

function connect(contextPair, accessorPrefix) {
  if (!this.enabled) return;

  accessorPrefix = accessorPrefix || "";
  var accessor = accessorPrefix + (accessorPrefix ? "Node" : "node");

  // The gainNode is what carries the connection's
  // weight attribute
  this.gainNode = contextPair.context.createGain();
  this.gainNode.gain.value = this.weight;
  this.sourceNode[accessor].connect(this.gainNode);

  var param = this.targetParameter;
  if (param === null)
    this.gainNode.connect(this.targetNode[accessor]);
  else {
    var nodeName = this.targetParameterNodeName ? this.targetParameterNodeName : "node";
    accessor = accessorPrefix + (accessorPrefix ? Utils.upperCaseFirstLetter(nodeName) : nodeName);
    this.gainNode.connect(this.targetNode[accessor][param]);
  }

  return this;
}

Connection.prototype.disable = function() {
  this.enabled = false;
  return this;
};

Connection.prototype.mutate = function(mutationDistance) {
  var mutationInfo = Utils.mutateParameter({
    obj: this,
    parameter: 'weight',
    mutationDistance: mutationDistance,
    mutationDeltaInterpolationType: this.mutationDeltaInterpolationType,
    mutationDeltaChance: this.mutationDeltaChance,
    mutationDelta: this.mutationDelta,
    randomMutationRange: this.randomMutationRange
  });
  return this;
};

Connection.prototype.getParameters = function() {
  return {
    name: name,
    id: this.id,
    weight: this.weight,
    enabled: this.enabled,
    sourceNode: this.sourceNode.name,
    targetNode: this.targetNode.name,
    targetParameter: this.targetParameter
  };
};

Connection.prototype.toString = function() {
  return (this.enabled? "" : "*") +
          "connection("+this.weight.toFixed(2)+")("+
          this.sourceNode.id+" --> "+this.targetNode.id+
          (this.targetParameter ? (": "+this.targetParameter) : "" )+")";
};

Connection.prototype.toJSON = function() {
  var json = {
    id: this.id,
    sourceNode: this.sourceNode.id,
    targetNode: this.targetNode.id,
    targetParameter: this.targetParameter,
    targetParameterNodeName: this.targetParameterNodeName,
    weight: this.weight,
    enabled: this.enabled
  };
  return JSON.stringify(json);
};

export default Connection;
<commit_msg>added mutation info to connections in toJSON<commit_after>
var Utils = require('asNEAT/utils')['default'],
    log = Utils.log,
    asNEAT = require('asNEAT/asNEAT')['default'],
    context = asNEAT.context,
    offlineContext = asNEAT.offlineContext,
    name = "Connection";

// TODO: Different kinds of connections?
var Connection = function(parameters) {
  Utils.extend(this, this.defaultParameters, parameters);
  this.gainNode = null;
  this.hasChanged = false;
  // Only generate a new id if one isn't given in the parameters
  if (parameters && typeof parameters.id !== 'undefined')
    this.id = parameters.id;
  else
    this.id = Utils.createHash();
};

Connection.prototype.name = name;
Connection.prototype.defaultParameters = {
  sourceNode: null,
  targetNode: null,

  // null if connecting to audio input of targetNode
  targetParameter: null,
  targetParameterNodeName: "node",

  weight: 1.0,
  enabled: true,

  mutationDeltaChance: 0.8,
  mutationDeltaInterpolationType: Utils.InterpolationType.EXPONENTIAL,
  mutationDelta: {min: [0.05, 0.3], max: [0.1, 0.6]},
  randomMutationRange: {min: 0.1, max: 1.5}
};

/**
  @param clonedsourceNode {Node} (optional)
  @param clonedtargetNode {Node} (optional)
*/
Connection.prototype.clone = function(clonedsourceNode, clonedtargetNode) {
  var sourceNode = clonedsourceNode || this.sourceNode.clone();
  var targetNode = clonedtargetNode || this.targetNode.clone();
  return new Connection({
    id: this.id,
    sourceNode: sourceNode,
    targetNode: targetNode,
    targetParameter: this.targetParameter,
    targetParameterNodeName: this.targetParameterNodeName,
    weight: this.weight,
    enabled: this.enabled,
    mutationDeltaChance: this.mutationDeltaChance,
    mutationDeltaInterpolationType: this.mutationDeltaInterpolationType,
    mutationDelta: _.clone(this.mutationDelta),
    randomMutationRange: _.clone(this.randomMutationRange)
  });
};
Connection.prototype.connect = function(contextPair) {
  connect.call(this, contextPair);
};
Connection.prototype.offlineConnect = function(contextPair) {
  connect.call(this, contextPair, "offline");
};

function connect(contextPair, accessorPrefix) {
  if (!this.enabled) return;

  accessorPrefix = accessorPrefix || "";
  var accessor = accessorPrefix + (accessorPrefix ? "Node" : "node");

  // The gainNode is what carries the connection's
  // weight attribute
  this.gainNode = contextPair.context.createGain();
  this.gainNode.gain.value = this.weight;
  this.sourceNode[accessor].connect(this.gainNode);

  var param = this.targetParameter;
  if (param === null)
    this.gainNode.connect(this.targetNode[accessor]);
  else {
    var nodeName = this.targetParameterNodeName ? this.targetParameterNodeName : "node";
    accessor = accessorPrefix + (accessorPrefix ? Utils.upperCaseFirstLetter(nodeName) : nodeName);
    this.gainNode.connect(this.targetNode[accessor][param]);
  }

  return this;
}

Connection.prototype.disable = function() {
  this.enabled = false;
  return this;
};

Connection.prototype.mutate = function(mutationDistance) {
  var mutationInfo = Utils.mutateParameter({
    obj: this,
    parameter: 'weight',
    mutationDistance: mutationDistance,
    mutationDeltaInterpolationType: this.mutationDeltaInterpolationType,
    mutationDeltaChance: this.mutationDeltaChance,
    mutationDelta: this.mutationDelta,
    randomMutationRange: this.randomMutationRange
  });
  return this;
};

Connection.prototype.getParameters = function() {
  return {
    name: name,
    id: this.id,
    weight: this.weight,
    enabled: this.enabled,
    sourceNode: this.sourceNode.name,
    targetNode: this.targetNode.name,
    targetParameter: this.targetParameter
  };
};

Connection.prototype.toString = function() {
  return (this.enabled? "" : "*") +
          "connection("+this.weight.toFixed(2)+")("+
          this.sourceNode.id+" --> "+this.targetNode.id+
          (this.targetParameter ? (": "+this.targetParameter) : "" )+")";
};

Connection.prototype.toJSON = function() {
  var json = {
    id: this.id,
    sourceNode: this.sourceNode.id,
    targetNode: this.targetNode.id,
    targetParameter: this.targetParameter,
    targetParameterNodeName: this.targetParameterNodeName,
    weight: this.weight,
    enabled: this.enabled,
    mutationDeltaChance: this.mutationDeltaChance,
    mutationDeltaInterpolationType: this.mutationDeltaInterpolationType,
    mutationDelta: this.mutationDelta,
    randomMutationRange: this.randomMutationRange
  };
  return JSON.stringify(json);
};

export default Connection;
<|endoftext|>