<commit_before>// TODO -----> fix the bug: when equal then click on a number, prevnum does not change
var prevNum,
	currentNum,
	display = document.getElementById('result');

// When a "number" button is clicked
function getValue() {
	// Prevent adding number in display when displayed sign is equals
	if (document.querySelector('.clear-entry').className.indexOf('no-border') != -1) {
		return false;
	}

	// Check if number count on display is equal to 13
	//   to prevent overflowing of numbers in display
	// Note: undefined does not have a length property so we need to check for it
	if (currentNum === undefined || currentNum.length < 13) {
		// undefined currentNum == zero (0) display
		if (currentNum === undefined) {
			// Prevent calc from displaying a number starting with 0
			// Info: uses parseInt since the value of input is a string
			if (parseInt(this.value) === 0) {
				// Check if display starts with 0
				if (display.innerHTML.indexOf(0) === 0) {
					return false; // Prevent the execution of ff. lines of code
				}
			}

			currentNum = this.value;
			if (parseInt(display.innerHTML) === 0) {
				// Check for operators in display
				if (isOperating()) {
					display.innerHTML += currentNum;
				} else {
					// If the display is 0, it will be replace by the button's value
					//   rather than concatenate to it
					display.innerHTML = currentNum;
				}
			} else {
				display.innerHTML += currentNum;
			}
		} else {
			// Add the value to currentNum so that it can be tracked
			//   by operator functions later
			currentNum += this.value;
			display.innerHTML += this.value;
		}

		if (display.innerHTML.length > 18) {
			// Make the display text smaller so that it will not overflow
			display.style.fontSize = "16px";
		}
	}
	// If num count on display is greater than 13, stop getting values
	else return false;
}

var numberBtns = document.querySelectorAll('.number');

for (var i = 0, len = numberBtns.length; i < len; i++) {
	numberBtns[i].addEventListener('click', getValue);
}

var inuseOperator;

// Check if an operator exist on display
function isOperating() {
	var operators = ["+", "-", "*", "/"];
	for (var i = 0, len = operators.length; i < len; i++) {
		// If an operator is found
		if (display.innerHTML.indexOf(operators[i]) !== -1) {
			return true; // So, the operation will not proceed
		} else {
			return false;
		}
	}
}

// Make display sign from = to encircled X
function changeDisplaySign() {
	// Change display sign
	var x = document.querySelector('.clear-entry');
	x.innerHTML = "×";
	x.className = "clear-entry";
}

function getOperator() {
	if (!isOperating()) {
		changeDisplaySign(); // So, users can input number
		if (prevNum != parseFloat(display.innerHTML)) {
			// This will prevent the display from returning NaN if user
			// did NOT enter a value || just clicked an operator in the first use
			if (currentNum === undefined) prevNum = 0;
			else prevNum = currentNum;
		}

		// Reset currentNum
		currentNum = undefined;
		// Add operator sign in display
		display.innerHTML += "+";
		inuseOperator = "+";
	} else {
		// TO DO -----> call "equals" function to display result
		// then add "operator to display"
		console.log('Operator is already in use');
	}
}

var operatorBtns = document.querySelectorAll('.operator');

operatorBtns[3].onclick = getOperator;

// When "equals" (=) is clicked or called
function equal() {
	// check if inuse operator is not undefined to prevent running equal() when
	// there's no operator in use
	if (inuseOperator !== undefined) {
		// Testing: for checking if display is NaN
		if (isNaN(parseInt(display.innerHTML))) {
			console.log(display.innerHTML);
			display.innerHTML = "Syntax Error";
		}
		// check if current no. is undefined
		// to indicate whether the operation should be repeated
		if (currentNum === undefined) {
			display.innerHTML = parseFloat(prevNum) + parseFloat(prevNum);
		} else {
			display.innerHTML = parseFloat(prevNum) + parseFloat(currentNum);
		}

		// Change "delete" button (x) to (=)
		var x = document.querySelector('.clear-entry');
		x.innerHTML = "=";
		x.className += " no-border";

		prevNum = display.innerHTML;
		console.log(prevNum);
	} else {
		console.log("Can't perform anything, operator is undefined");
	}
}

document.getElementById('equal').onclick = equal;

/*  When "clear all" (AC) is clicked
		set in use operator = undefined
		set current num and previous num = undefined
		set display = 0 */

function clearAll() {
	// Reset all from the start
	changeDisplaySign();
	inuseOperator = currentNum = prevNum = undefined;
	display.innerHTML = 0;
}

document.getElementById('clear').onclick = clearAll;

/* 	When "decimal" button (.) is clicked
		add "." to current num
		display it */
<commit_msg>Remove unnecessary comments for clearAll<commit_after>// TODO -----> fix the bug: when equal then click on a number, prevnum does not change
var prevNum,
	currentNum,
	display = document.getElementById('result');

// When a "number" button is clicked
function getValue() {
	// Prevent adding number in display when displayed sign is equals
	if (document.querySelector('.clear-entry').className.indexOf('no-border') != -1) {
		return false;
	}

	// Check if number count on display is equal to 13
	//   to prevent overflowing of numbers in display
	// Note: undefined does not have a length property so we need to check for it
	if (currentNum === undefined || currentNum.length < 13) {
		// undefined currentNum == zero (0) display
		if (currentNum === undefined) {
			// Prevent calc from displaying a number starting with 0
			// Info: uses parseInt since the value of input is a string
			if (parseInt(this.value) === 0) {
				// Check if display starts with 0
				if (display.innerHTML.indexOf(0) === 0) {
					return false; // Prevent the execution of ff. lines of code
				}
			}

			currentNum = this.value;
			if (parseInt(display.innerHTML) === 0) {
				// Check for operators in display
				if (isOperating()) {
					display.innerHTML += currentNum;
				} else {
					// If the display is 0, it will be replace by the button's value
					//   rather than concatenate to it
					display.innerHTML = currentNum;
				}
			} else {
				display.innerHTML += currentNum;
			}
		} else {
			// Add the value to currentNum so that it can be tracked
			//   by operator functions later
			currentNum += this.value;
			display.innerHTML += this.value;
		}

		if (display.innerHTML.length > 18) {
			// Make the display text smaller so that it will not overflow
			display.style.fontSize = "16px";
		}
	}
	// If num count on display is greater than 13, stop getting values
	else return false;
}

var numberBtns = document.querySelectorAll('.number');

for (var i = 0, len = numberBtns.length; i < len; i++) {
	numberBtns[i].addEventListener('click', getValue);
}

var inuseOperator;

// Check if an operator exist on display
function isOperating() {
	var operators = ["+", "-", "*", "/"];
	for (var i = 0, len = operators.length; i < len; i++) {
		// If an operator is found
		if (display.innerHTML.indexOf(operators[i]) !== -1) {
			return true; // So, the operation will not proceed
		} else {
			return false;
		}
	}
}

// Make display sign from = to encircled X
function changeDisplaySign() {
	// Change display sign
	var x = document.querySelector('.clear-entry');
	x.innerHTML = "×";
	x.className = "clear-entry";
}

function getOperator() {
	if (!isOperating()) {
		changeDisplaySign(); // So, users can input number
		if (prevNum != parseFloat(display.innerHTML)) {
			// This will prevent the display from returning NaN if user
			// did NOT enter a value || just clicked an operator in the first use
			if (currentNum === undefined) prevNum = 0;
			else prevNum = currentNum;
		}

		// Reset currentNum
		currentNum = undefined;
		// Add operator sign in display
		display.innerHTML += "+";
		inuseOperator = "+";
	} else {
		// TO DO -----> call "equals" function to display result
		// then add "operator to display"
		console.log('Operator is already in use');
	}
}

var operatorBtns = document.querySelectorAll('.operator');

operatorBtns[3].onclick = getOperator;

// When "equals" (=) is clicked or called
function equal() {
	// check if inuse operator is not undefined to prevent running equal() when
	// there's no operator in use
	if (inuseOperator !== undefined) {
		// Testing: for checking if display is NaN
		if (isNaN(parseInt(display.innerHTML))) {
			console.log(display.innerHTML);
			display.innerHTML = "Syntax Error";
		}
		// check if current no. is undefined
		// to indicate whether the operation should be repeated
		if (currentNum === undefined) {
			display.innerHTML = parseFloat(prevNum) + parseFloat(prevNum);
		} else {
			display.innerHTML = parseFloat(prevNum) + parseFloat(currentNum);
		}

		// Change "delete" button (x) to (=)
		var x = document.querySelector('.clear-entry');
		x.innerHTML = "=";
		x.className += " no-border";

		prevNum = display.innerHTML;
		console.log(prevNum);
	} else {
		console.log("Can't perform anything, operator is undefined");
	}
}

document.getElementById('equal').onclick = equal;

function clearAll() {
	// Reset all from the start
	changeDisplaySign();
	inuseOperator = currentNum = prevNum = undefined;
	display.innerHTML = 0;
}

document.getElementById('clear').onclick = clearAll;

/* 	When "decimal" button (.) is clicked
		add "." to current num
		display it */
<|endoftext|>


<commit_before>/*
 * iOS Fonts
 * A Happy Place for Typography
 * by @mike_critz and contributors
 * https://github.com/mcritz/iosfonts
 */

define(
	[
		"jquery"
	],
	function(
		$
	) {
		var allFonts = {};
		var $el = $('#iosfonts');
		var $previewEl = $('#live-preview');
		var $searchEl = $('#font-search');
		var $versionEl = $('#os-version');
		var userText = '';

		var matchesQuery = function(query) {
			return
		}

		var handleError = function($target, headline, message) {
			$target = $target || $el;
			headline = headline || 'Error';

			if (!$target) {
				alert('Critical error');
				return;
			}
			var errorString = '<div class="row error"'
				+ '
' + headline + '

'
				+ message
				+ '

';
			$target.html(errorString);
			throw(headline);
		}

		var getKeys = function(object) {
			var objectKeys = [];

			for (var key in object) {
				if (typeof(object[key]) == 'boolean') {
					break;
				};

				if (object.hasOwnProperty(key)) {
					objectKeys.push(key);
				}
			}
			return objectKeys;
		}

		var renderFontsForVersion = function(fontData, version) {
			if (!fontData) {
				var errorMessage = 'Please report this error to '
				+ 'the developer.';
				handleError(null, 'Server Error', errorMessage);
			}
			var availableFaces = 0;
			$(fontData).each(function(ii, fontDefinition) {
				$(fontDefinition.faces).each(function(jj, faceDefinition) {
					var facePlatforms = faceDefinition.platforms;
					for (var key in facePlatforms) {
						if (!facePlatforms[key]) { return; }

						if (facePlatforms[key].version > version
							|| facePlatforms[key].depricated <= version) {
							facePlatforms[key].isNotAvailable = true;
						} else {
							facePlatforms[key].isNotAvailable = false;
							availableFaces++;
						}
					}
				});
// 				this.isNotActive = availableFaces ? false : true;
			});
			renderFonts($el, fontData, userText);
		}

		var renderFontsWithQuery = function(fontData, query) {
			var regexPattern = new RegExp(query, "gi");

			$(fontData).each(function(ii, fontDefinition) {
				var faceCount = fontDefinition.faces.count;
				var matchCount = 0;

				$(fontDefinition.faces).each(function(jj, faceDefinition) {
					var faceName = faceDefinition.font_face;

					if (faceName.match(regexPattern)) {
						faceDefinition.doesNotMatch = false;
						matchCount++;
					} else {
						faceDefinition.doesNotMatch = true;
					}
				});

				this.isNotActive = matchCount ? false : true;
			});

			renderFonts($el, fontData, userText);
		}

		var initEvents = function() {
			$previewEl.on(
				'keyup', function() {
					userText = $(this).val();
					renderFonts($el, allFonts, userText);
				}
			);
			$searchEl.on(
				'keyup change search', function() {
					renderFontsWithQuery(allFonts, $(this).val());
				}
			);
			$versionEl.on(
				'change', function() {
					renderFontsForVersion(allFonts, $(this).val());
				}
			);
		}

		/**
		 * itemizeValue
		 * @param value (number, string, object) : data to be parsed
		 * @param fontFamily (string) : display text to be rendered
		 * returns a DOM dictionary value of data
		 * converting non-text into pretty strings.
		 **/
		var itemizeValue = function(value, fontFamily) {
			var fontStyle = "";
			var elClass = "small-4 medium-2 columns";
			var fontAttributes = "";

			switch (typeof(value)) {
				case "number" :
					if (value % 1 == 0) {
						value = value + '.0';
					}
					break;
				case "string" :
					if (!fontFamily) { return; }
					elClass = "face-name small-12 medium-6 columns";
					fontAttributes = "title=" + fontFamily
						+ " style='font-family:" + fontFamily + ";'";
					break;
				case "object" :
					if (!value.version) { return; }
					if (value.isNotAvailable) {
						elClass += " unavailable";
					} else {
						elClass += " available";
					}
					value = value.version;
					break;
				default :
					return '—';
			}
			return '' + value + '';
		}

		var listPlatforms = function(platforms) {
			var platformList = '';
			$(platforms).each( function(ll, platform) {
				for (key in platform) {
					platformList += itemizeValue( platform[key] );
				}
			});
			return platformList;
		}

		var renderFontFaces = function(faceData, displayText) {
			if (!faceData) return;

			var faces = '';

			$(faceData).each( function() {
				var faceClass = 'row';

				if (this.doesNotMatch) {
					faceClass += ' inactive';
				} else {
					faceClass += ' active';
				}

				faces += '
';
				var elText = displayText ? displayText : this.font_face;
				faces += itemizeValue(elText, this.font_face)
				+ listPlatforms(this.platforms)
				+ '
';
			});

			return faces;
		}

		var renderFonts = function($target, data, previewText) {

			var $list = $('

');
			var elClass = "small-4 medium-2 columns";

			$(data).each( function() {
				if (this.isNotActive) {
					return;
				}
				$list.append('

'
				+ ''
				+ this.family_name + ''
				+ 'iPhone'
				+ 'iPad'
				+ ' WATCH'
				+ '
'
				+ renderFontFaces(this.faces, previewText)
				+ '
');
			});

			$list.append('
');
			$target.html($list);
		};

		var init = function($targetEl) {
			$.ajax({
				url: "data/iosfonts.json",
				context: document.body
			}).done(function(data) {
				allFonts = data.fonts;
				renderFontsForVersion(allFonts, 8);
				initEvents();
			});
		};

		init($el);
	}
);
<commit_msg>updated deprication template<commit_after>/*
 * iOS Fonts
 * A Happy Place for Typography
 * by @mike_critz and contributors
 * https://github.com/mcritz/iosfonts
 */

define(
	[
		"jquery"
	],
	function(
		$
	) {
		var allFonts = {};
		var $el = $('#iosfonts');
		var $previewEl = $('#live-preview');
		var $searchEl = $('#font-search');
		var $versionEl = $('#os-version');
		var userText = '';

		var matchesQuery = function(query) {
			return
		}

		var handleError = function($target, headline, message) {
			$target = $target || $el;
			headline = headline || 'Error';

			if (!$target) {
				alert('Critical error');
				return;
			}
			var errorString = '<div class="row error"'
				+ '
' + headline + '

'
				+ message
				+ '

';
			$target.html(errorString);
			throw(headline);
		}

		var getKeys = function(object) {
			var objectKeys = [];

			for (var key in object) {
				if (typeof(object[key]) == 'boolean') {
					break;
				};

				if (object.hasOwnProperty(key)) {
					objectKeys.push(key);
				}
			}
			return objectKeys;
		}

		var renderFontsForVersion = function(fontData, version) {
			if (!fontData) {
				var errorMessage = 'Please report this error to '
				+ 'the developer.';
				handleError(null, 'Server Error', errorMessage);
			}
			var availableFaces = 0;
			$(fontData).each(function(ii, fontDefinition) {
				$(fontDefinition.faces).each(function(jj, faceDefinition) {
					var facePlatforms = faceDefinition.platforms;
					for (var key in facePlatforms) {
						if (!facePlatforms[key]) { return; }

						if (facePlatforms[key].version > version
							|| facePlatforms[key].depricated <= version) {
							facePlatforms[key].isNotAvailable = true;
						} else {
							facePlatforms[key].isNotAvailable = false;
							availableFaces++;
						}
					}
				});
			});
			renderFonts($el, fontData, userText);
		}

		var renderFontsWithQuery = function(fontData, query) {
			var regexPattern = new RegExp(query, "gi");

			$(fontData).each(function(ii, fontDefinition) {
				var faceCount = fontDefinition.faces.count;
				var matchCount = 0;

				$(fontDefinition.faces).each(function(jj, faceDefinition) {
					var faceName = faceDefinition.font_face;

					if (faceName.match(regexPattern)) {
						faceDefinition.doesNotMatch = false;
						matchCount++;
					} else {
						faceDefinition.doesNotMatch = true;
					}
				});

				this.isNotActive = matchCount ? false : true;
			});

			renderFonts($el, fontData, userText);
		}

		var initEvents = function() {
			$previewEl.on(
				'keyup', function() {
					userText = $(this).val();
					renderFonts($el, allFonts, userText);
				}
			);
			$searchEl.on(
				'keyup change search', function() {
					renderFontsWithQuery(allFonts, $(this).val());
				}
			);
			$versionEl.on(
				'change', function() {
					renderFontsForVersion(allFonts, $(this).val());
				}
			);
		}

		/**
		 * itemizeValue
		 * @param value (number, string, object) : data to be parsed
		 * @param fontFamily (string) : display text to be rendered
		 * returns a DOM dictionary value of data
		 * converting non-text into pretty strings.
		 **/
		var itemizeValue = function(value, fontFamily) {
			var fontStyle = "";
			var elClass = "small-4 medium-2 columns";
			var fontAttributes = "";

			switch (typeof(value)) {
				case "number" :
					if (value % 1 == 0) {
						value = value + '.0';
					}
					break;
				case "string" :
					if (!fontFamily) { return; }
					elClass = "face-name small-12 medium-6 columns";
					fontAttributes = "title=" + fontFamily
						+ " style='font-family:" + fontFamily + ";'";
					break;
				case "object" :
					var isDepricated = value.depricated;
					if (!value.version) { return; }
					if (value.isNotAvailable) {
						elClass += " unavailable";
					} else {
						elClass += " available";
					}
					value = (isDepricated) ?
						'depricated iOS ' + value.depricated : value.version;
					break;
				default :
					return '—';
			}
			return '' + value + '';
		}

		var listPlatforms = function(platforms) {
			var platformList = '';
			$(platforms).each( function(ll, platform) {
				for (key in platform) {
					platformList += itemizeValue( platform[key] );
				}
			});
			return platformList;
		}

		var renderFontFaces = function(faceData, displayText) {
			if (!faceData) return;

			var faces = '';

			$(faceData).each( function() {
				var faceClass = 'row';

				if (this.doesNotMatch) {
					faceClass += ' inactive';
				} else {
					faceClass += ' active';
				}

				faces += '
';
				var elText = displayText ? displayText : this.font_face;
				faces += itemizeValue(elText, this.font_face)
				+ listPlatforms(this.platforms)
				+ '
';
			});

			return faces;
		}

		var renderFonts = function($target, data, previewText) {

			var $list = $('

');
			var elClass = "small-4 medium-2 columns";

			$(data).each( function() {
				if (this.isNotActive) {
					return;
				}
				$list.append('

'
				+ ''
				+ this.family_name + ''
				+ 'iPhone'
				+ 'iPad'
				+ ' WATCH'
				+ '
'
				+ renderFontFaces(this.faces, previewText)
				+ '
');
			});

			$list.append('
');
			$target.html($list);
		};

		var init = function($targetEl) {
			$.ajax({
				url: "data/iosfonts.json",
				context: document.body
			}).done(function(data) {
				allFonts = data.fonts;
				renderFontsForVersion(allFonts, 8);
				initEvents();
			});
		};

		init($el);
	}
);
<|endoftext|>


<commit_before>//+++++++++++++++++++++++++++++++++++++++++++++++++++
// WATS1020 - Add a Map Assignment
//+++++++++++++++++++++++++++++++++++++++++++++++++++

    //Set script to run after document load
$(document).ready(function() {

    //Create map and set home location
    var map = L.map('map-container').setView([46.852, -121.760], 10);

	var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib='Map data © OpenStreetMap contributors';

    //Create map layers and set attributes
    var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 18, attribution: osmAttrib});

    var satLayer = L.tileLayer( 'http://{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest ',
        subdomains: ['otile1','otile2','otile3','otile4']
});

    var drawLayer = L.tileLayer( 'http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest ',
        subdomains: ['otile1','otile2','otile3','otile4']
});

    var mapLayers = {
        "Satellite": satLayer,
        "Map View": drawLayer,
        "Open Street Maps": osm
}

    L.control.layers(mapLayers).addTo(map);
        satLayer.addTo(map);

    //Add markers, circle, and polygon to identify key areas on map
    var marker = L.marker([46.852, -121.760]).addTo(map);
        marker.bindPopup('Welcome to Mt. Rainier!
This peak is 14,392 feet (4,386 m) high.
Learn More');

    var marker = L.marker([46.8244992,-121.7623382]).addTo(map);
        marker.bindPopup('Liberty Cap Glacier
Elevation: 14,100 feet (4,300 m)
Learn More');

    var marker = L.marker([46.8570898,-121.7964111]).addTo(map);
        marker.bindPopup('Little Tahoma Peak
Elevation: 11,138 ft (3,395 m)
Learn More');

    var marker = L.marker([46.8494191,-121.7255489]).addTo(map);
        marker.bindPopup('Cowlitz Chimneys South
Elevation: 7,605 ft (2,318 m)
Learn More');

    var marker = L.marker([46.8490996,-121.326563]).addTo(map);
        marker.bindPopup('Bumping Lake
Elevation: 3,426 ft (1,044 m)
Learn More');

    var circle = L.circle([46.8915901,-121.6137634], 700, {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        }).addTo(map);
        circle.bindPopup('Crystal Mountain Ski Area
Learn More');

    var polygon = L.polygon([
        [46.7858338,-121.725148],
        [46.7913057,-121.726635],
        [46.7896897,-121.735622],
        ]).addTo(map);
        polygon.bindPopup('Paradise, WA - Inn and Natural Area
Learn More');

    var popup = L.popup();

    //Listen for clicks on map and return lat/long in popup
    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString())
            .openOn(map);
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Navbar dropdown menu fix (opens tabs from navbar - adds smooth scroll)
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	$('a.js-link-scroll').on('shown.bs.tab', function (e) {
   	$('#tabs .active').removeClass('active');
   	$('a[href="'+$(this).attr('href')+'"]').parent().addClass('active');
   	 	var that = this;
   	 	$('html, body').animate({
   	     scrollTop: $( $(that).attr('href') ).offset().top
   	 }, 800);
	});

});

    <commit_msg>Adjusted indents (main.js)<commit_after>//+++++++++++++++++++++++++++++++++++++++++++++++++++
// WATS1020 - Add a Map Assignment
//+++++++++++++++++++++++++++++++++++++++++++++++++++

//Set script to run after document load
$(document).ready(function() {

    //Create map and set home location
    var map = L.map('map-container').setView([46.852, -121.760], 10);

	var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib='Map data © OpenStreetMap contributors';

    //Create map layers and set attributes
    var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 18, attribution: osmAttrib});

    var satLayer = L.tileLayer( 'http://{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest ',
        subdomains: ['otile1','otile2','otile3','otile4']
});

    var drawLayer = L.tileLayer( 'http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors | Tiles Courtesy of MapQuest ',
        subdomains: ['otile1','otile2','otile3','otile4']
});

    var mapLayers = {
        "Satellite": satLayer,
        "Map View": drawLayer,
        "Open Street Maps": osm
};

    L.control.layers(mapLayers).addTo(map);
        satLayer.addTo(map);

    //Add markers, circle, and polygon to identify key areas on map
    var marker = L.marker([46.852, -121.760]).addTo(map);
        marker.bindPopup('Welcome to Mt. Rainier!
This peak is 14,392 feet (4,386 m) high.
Learn More');

    var marker = L.marker([46.8244992,-121.7623382]).addTo(map);
        marker.bindPopup('Liberty Cap Glacier
Elevation: 14,100 feet (4,300 m)
Learn More');

    var marker = L.marker([46.8570898,-121.7964111]).addTo(map);
        marker.bindPopup('Little Tahoma Peak
Elevation: 11,138 ft (3,395 m)
Learn More');

    var marker = L.marker([46.8494191,-121.7255489]).addTo(map);
        marker.bindPopup('Cowlitz Chimneys South
Elevation: 7,605 ft (2,318 m)
Learn More');

    var marker = L.marker([46.8490996,-121.326563]).addTo(map);
        marker.bindPopup('Bumping Lake
Elevation: 3,426 ft (1,044 m)
Learn More');

    var circle = L.circle([46.8915901,-121.6137634], 700, {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5,
        }).addTo(map);
        circle.bindPopup('Crystal Mountain Ski Area
Learn More');

    var polygon = L.polygon([
        [46.7858338,-121.725148],
        [46.7913057,-121.726635],
        [46.7896897,-121.735622],
        ]).addTo(map);
        polygon.bindPopup('Paradise, WA - Inn and Natural Area
Learn More');

    var popup = L.popup();

    //Listen for clicks on map and return lat/long in popup
    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString())
            .openOn(map);
    }

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // Navbar dropdown menu fix (opens tabs from navbar - adds smooth scroll)
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	$('a.js-link-scroll').on('shown.bs.tab', function (e) {
   		$('#tabs .active').removeClass('active');
   		$('a[href="'+$(this).attr('href')+'"]').parent().addClass('active');
   	 		var that = this;
   	 		$('html, body').animate({
   	     	scrollTop: $( $(that).attr('href') ).offset().top
   	 		}, 800);
	});

});

    <|endoftext|>


<commit_before>class BluetoothConnection {
  constructor(serviceUuid, characteristicUuid) {
    this._device = null;
    this._characteristic = null;

    this._boundHandleDisconnection = this._handleDisconnection.bind(this);
    this._boundHandleCharacteristicValueChanged =
        this._handleCharacteristicValueChanged.bind(this);

    this._serviceUuid = serviceUuid;
    this._characteristicUuid = characteristicUuid;

    // TODO: Separate UI from model
    this._consoleContainer = document.getElementById('console');
    this._terminalContainer = document.getElementById('terminal');
  }

  connect() {
    return this._connectToDevice(this._device);
  }

  disconnect() {
    this._disconnectFromDevice(this._device);

    if (this._characteristic) {
      this._characteristic.removeEventListener('characteristicvaluechanged',
          this._boundHandleDisconnection);
      this._characteristic = null;
    }

    this._device = null;
  }

  _connectToDevice(device) {
    return (device ? Promise.resolve(device) : this._requestBluetoothDevice()).
        then(device => this._connectDeviceAndCacheCharacteristic(device)).
        then(characteristic => this._startNotifications(characteristic)).
        catch(error => this._log(error));
  }

  _disconnectFromDevice(device) {
    if (!device) {
      return;
    }

    this._log('Disconnecting from "' + device.name + '" bluetooth device...');

    device.removeEventListener('gattserverdisconnected',
        this._boundHandleDisconnection);

    if (!device.gatt.connected) {
      this._log('"' + device.name +
          '" bluetooth device is already disconnected');
      return;
    }

    device.gatt.disconnect();

    this._log('"' + device.name + '" bluetooth device disconnected');
  }

  _requestBluetoothDevice() {
    this._log('Requesting bluetooth device...');

    return navigator.bluetooth.requestDevice({
      filters: [{services: [this._serviceUuid]}],
    }).
        then(device => {
          this._log('"' + device.name + '" bluetooth device selected');

          this._device = device; // remember device
          this._device.addEventListener('gattserverdisconnected',
              this._boundHandleDisconnection);

          return this._device;
        });
  }

  _connectDeviceAndCacheCharacteristic(device) {
    if (device.gatt.connected && this._characteristic) { // check remembered characteristic
      return Promise.resolve(this._characteristic);
    }

    this._log('Connecting to GATT server...');

    return device.gatt.connect().
        then(server => {
          this._log('GATT server connected', 'Getting service...');

          return server.getPrimaryService(this._serviceUuid);
        }).
        then(service => {
          this._log('Service found', 'Getting characteristic...');

          return service.getCharacteristic(this._characteristicUuid);
        }).
        then(characteristic => {
          this._log('Characteristic found');

          this._characteristic = characteristic; // remember characteristic

          return this._characteristic;
        });
  }

  _startNotifications(characteristic) {
    this._log('Starting notifications...');

    return characteristic.startNotifications().
        then(() => {
          this._log('Notifications started');

          characteristic.addEventListener('characteristicvaluechanged',
              this._boundHandleCharacteristicValueChanged);
        });
  }

  _stopNotifications(characteristic) {
    this._log('Stopping notifications...');

    return characteristic.stopNotifications().
        then(() => {
          this._log('Notifications stopped');

          characteristic.removeEventListener('characteristicvaluechanged',
              this._boundHandleCharacteristicValueChanged);
        });
  }

  _handleDisconnection(event) {
    let device = event.target;

    this._log('"' + device.name +
        '" bluetooth device disconnected, trying to reconnect...');

    this._connectDeviceAndCacheCharacteristic(device).
        then(characteristic => this._startNotifications(characteristic)).
        catch(error => this._log(error));
  }

  _handleCharacteristicValueChanged(event) {
    let value = new TextDecoder().decode(event.target.value);

    // TODO: Separate output logic
    this._logToTerminal('> ' + value);
  }

  send(message) {
    if (!this._characteristic) {
      return;
    }

    this._sendToCharacteristic(this._characteristic, message);
  }

  _sendToCharacteristic(characteristic, message) {
    // TODO: Separate output logic
    this._logToTerminal('< ' + message);

    characteristic.writeValue(this._str2ab(message + '\r\n'));
  }

  _log(...messages) {
    let html = messages.join('
') + '
';

    messages.forEach(message => console.log(message));

    // TODO: Separate UI from model
    this._consoleContainer.insertAdjacentHTML('beforeend', html);
  }

  _logToTerminal(message) {
    let html = message + '
';

    // TODO: Separate UI from model
    this._terminalContainer.insertAdjacentHTML('beforeend', html);
  }

  _str2ab(str) {
    let buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    let bufView = new Uint8Array(buf);

    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }

    return buf;
  }
}

let connection = new BluetoothConnection(0xFFE0, 0xFFE1);

let connectButton = document.getElementById('connect');
let disconnectButton = document.getElementById('disconnect');
let inputField = document.getElementById('input');
let sendButton = document.getElementById('send');

connectButton.addEventListener('click', () => connection.connect());

disconnectButton.addEventListener('click', () => connection.disconnect());

sendButton.addEventListener('click', () => {
  connection.send(inputField.value);
  inputField.value = '';
});
<commit_msg>`_str2ab` made static<commit_after>class BluetoothConnection {
  constructor(serviceUuid, characteristicUuid) {
    this._device = null;
    this._characteristic = null;

    this._boundHandleDisconnection = this._handleDisconnection.bind(this);
    this._boundHandleCharacteristicValueChanged =
        this._handleCharacteristicValueChanged.bind(this);

    this._serviceUuid = serviceUuid;
    this._characteristicUuid = characteristicUuid;

    // TODO: Separate UI from model
    this._consoleContainer = document.getElementById('console');
    this._terminalContainer = document.getElementById('terminal');
  }

  connect() {
    return this._connectToDevice(this._device);
  }

  disconnect() {
    this._disconnectFromDevice(this._device);

    if (this._characteristic) {
      this._characteristic.removeEventListener('characteristicvaluechanged',
          this._boundHandleDisconnection);
      this._characteristic = null;
    }

    this._device = null;
  }

  _connectToDevice(device) {
    return (device ? Promise.resolve(device) : this._requestBluetoothDevice()).
        then(device => this._connectDeviceAndCacheCharacteristic(device)).
        then(characteristic => this._startNotifications(characteristic)).
        catch(error => this._log(error));
  }

  _disconnectFromDevice(device) {
    if (!device) {
      return;
    }

    this._log('Disconnecting from "' + device.name + '" bluetooth device...');

    device.removeEventListener('gattserverdisconnected',
        this._boundHandleDisconnection);

    if (!device.gatt.connected) {
      this._log('"' + device.name +
          '" bluetooth device is already disconnected');
      return;
    }

    device.gatt.disconnect();

    this._log('"' + device.name + '" bluetooth device disconnected');
  }

  _requestBluetoothDevice() {
    this._log('Requesting bluetooth device...');

    return navigator.bluetooth.requestDevice({
      filters: [{services: [this._serviceUuid]}],
    }).
        then(device => {
          this._log('"' + device.name + '" bluetooth device selected');

          this._device = device; // remember device
          this._device.addEventListener('gattserverdisconnected',
              this._boundHandleDisconnection);

          return this._device;
        });
  }

  _connectDeviceAndCacheCharacteristic(device) {
    if (device.gatt.connected && this._characteristic) { // check remembered characteristic
      return Promise.resolve(this._characteristic);
    }

    this._log('Connecting to GATT server...');

    return device.gatt.connect().
        then(server => {
          this._log('GATT server connected', 'Getting service...');

          return server.getPrimaryService(this._serviceUuid);
        }).
        then(service => {
          this._log('Service found', 'Getting characteristic...');

          return service.getCharacteristic(this._characteristicUuid);
        }).
        then(characteristic => {
          this._log('Characteristic found');

          this._characteristic = characteristic; // remember characteristic

          return this._characteristic;
        });
  }

  _startNotifications(characteristic) {
    this._log('Starting notifications...');

    return characteristic.startNotifications().
        then(() => {
          this._log('Notifications started');

          characteristic.addEventListener('characteristicvaluechanged',
              this._boundHandleCharacteristicValueChanged);
        });
  }

  _stopNotifications(characteristic) {
    this._log('Stopping notifications...');

    return characteristic.stopNotifications().
        then(() => {
          this._log('Notifications stopped');

          characteristic.removeEventListener('characteristicvaluechanged',
              this._boundHandleCharacteristicValueChanged);
        });
  }

  _handleDisconnection(event) {
    let device = event.target;

    this._log('"' + device.name +
        '" bluetooth device disconnected, trying to reconnect...');

    this._connectDeviceAndCacheCharacteristic(device).
        then(characteristic => this._startNotifications(characteristic)).
        catch(error => this._log(error));
  }

  _handleCharacteristicValueChanged(event) {
    let value = new TextDecoder().decode(event.target.value);

    // TODO: Separate output logic
    this._logToTerminal('> ' + value);
  }

  send(message) {
    if (!this._characteristic) {
      return;
    }

    this._sendToCharacteristic(this._characteristic, message);
  }

  _sendToCharacteristic(characteristic, message) {
    // TODO: Separate output logic
    this._logToTerminal('< ' + message);

    characteristic.writeValue(this.constructor._str2ab(message + '\r\n'));
  }

  _log(...messages) {
    let html = messages.join('
') + '
';

    messages.forEach(message => console.log(message));

    // TODO: Separate UI from model
    this._consoleContainer.insertAdjacentHTML('beforeend', html);
  }

  _logToTerminal(message) {
    let html = message + '
';

    // TODO: Separate UI from model
    this._terminalContainer.insertAdjacentHTML('beforeend', html);
  }

  static _str2ab(str) {
    let buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    let bufView = new Uint8Array(buf);

    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }

    return buf;
  }
}

let connection = new BluetoothConnection(0xFFE0, 0xFFE1);

let connectButton = document.getElementById('connect');
let disconnectButton = document.getElementById('disconnect');
let inputField = document.getElementById('input');
let sendButton = document.getElementById('send');

connectButton.addEventListener('click', () => connection.connect());

disconnectButton.addEventListener('click', () => connection.disconnect());

sendButton.addEventListener('click', () => {
  connection.send(inputField.value);
  inputField.value = '';
});
<|endoftext|>


<commit_before>(function ($) {
  'use strict';

  var url = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&callback=touristinfo.map.init';
  var map = touristinfo.map.instance;
  var autocomplete = touristinfo.map.autocomplete;

  function addMarker(place) {
    var marker = new google.maps.Marker({
      id: place.id,
      map: map,
      position: {
        lat: place.latitude,
        lng: place.longitude
      },
      title: place.name
    });

    touristinfo.map.markers.push(marker);

    marker.addListener('click', function() {
      var mode = touristinfo.map.mode;

      if ((mode !== 'explore') && (mode !== 'view')) {
        return;
      }

      if (mode === 'view') {
        touristinfo.map.activeMarker.setAnimation(null);
      }

      marker.setAnimation(google.maps.Animation.BOUNCE);

      touristinfo.map.activeMarker = marker;

      $('#place').load('/ajax/places/' + marker.id);

      if (mode === 'explore') {
        $('a[href="#view"]').tab('show');
      }
    });
  }

  touristinfo.map.init = function () {
    var mapOptions = {
      center: touristinfo.map.center,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: touristinfo.map.zoom
    };

    map = new google.maps.Map($('#map')[0], mapOptions);

    $.getJSON('/ajax/places', function (places) {
      for (var i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });

    autocomplete = new google.maps.places.Autocomplete($('#query')[0]);

    autocomplete.bindTo('bounds', map);

    map.addListener('click', function (event) {
      if (touristinfo.map.mode === 'add') {
        var marker = new google.maps.Marker({
          map: map,
          position: event.latLng,
          draggable: true
        });

        touristinfo.map.markers.push(marker);

        touristinfo.map.mode = 'added';

        $('#latitude').val(event.latLng.lat);
        $('#longitude').val(event.latLng.lng);

        marker.addListener('dragend', function (event) {
          $('#latitude').val(event.latLng.lat);
          $('#longitude').val(event.latLng.lng);
        });
      }
    });
  };

  $.getScript(url);

  $('[data-toggle="tooltip"]').tooltip();

  $('[data-trigger="tab"]').click(function (event) {
    if ($(this).is('a')) {
      event.preventDefault();
    }

    var target = $(this).attr('href') || $(this).data('target');

    $('a[href="' + target + '"]').tab('show');
  });

  $('a[data-toggle="tab"]').on('show.bs.tab', function (event) {
    var target = $(event.target).attr('href');

    switch (target) {
      case '#search':
        touristinfo.map.mode = 'explore';

        break;

      case '#new':
        touristinfo.map.mode = 'add';

        for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
          touristinfo.map.markers[i].setVisible(false);
        }

        break;

      case '#view':
        touristinfo.map.mode = 'view';

        break;
    }
  });

  $('a[data-toggle="tab"]').on('hide.bs.tab', function (event) {
    var target = $(event.target).attr('href');

    switch (target) {
      case '#new':
        touristinfo.map.mode = 'explore';

        for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
          touristinfo.map.markers[i].setVisible(true);
        }

        break;

      case '#view':
        touristinfo.map.mode = 'explore';

        if (touristinfo.map.activeMarker !== null) {
          touristinfo.map.activeMarker.setAnimation(null);

          touristinfo.map.activeMarker = null;
        }

        break;
    }
  });

  $('#filter-places').submit(function (event) {
    event.preventDefault();

    var place = autocomplete.getPlace();

    if (!place.geometry) {
      window.alert('Autocomplete\'s returned place contains no geometry.');

      return;
    }

    var data = {
      distance: $('#distance').val(),
      latitude: place.geometry.location.lat(),
      longitude: place.geometry.location.lng(),
      radius: $('#radius').val()
    };

    $.post('/ajax/places/filter', data, function (places) {
      for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
        touristinfo.map.markers[i].setMap(null);
      }

      touristinfo.map.markers = [];

      for (i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });
  });

  $('#filter-places').on('reset', function () {
    $.getJSON('/ajax/places', function (places) {
      for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
        touristinfo.map.markers[i].setMap(null);
      }

      touristinfo.map.markers = [];

      for (i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });
  });

  $('#add-place').submit(function (event) {
    event.preventDefault();

    $.post('/ajax/places/add', $('#add-place').serialize(), function (id) {
      var n = touristinfo.map.markers.length - 1;
      var marker = touristinfo.map.markers[n];

      marker.id = id;

      marker.setDraggable(false);
      marker.setAnimation(google.maps.Animation.BOUNCE);
      marker.setTitle($('#name').val());

      touristinfo.map.activeMarker = marker;

      $('#add-place').trigger('reset');
      $('a[href="#view"]').tab('show');
    });
  });

  $('#discard-place').click(function () {
    var marker = touristinfo.map.markers.pop();

    marker.setMap(null);
  });
})(jQuery);
<commit_msg>Prevented form submit before place changed<commit_after>(function ($) {
  'use strict';

  var url = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&callback=touristinfo.map.init';
  var map = touristinfo.map.instance;
  var autocomplete = touristinfo.map.autocomplete;

  function addMarker(place) {
    var marker = new google.maps.Marker({
      id: place.id,
      map: map,
      position: {
        lat: place.latitude,
        lng: place.longitude
      },
      title: place.name
    });

    touristinfo.map.markers.push(marker);

    marker.addListener('click', function() {
      var mode = touristinfo.map.mode;

      if ((mode !== 'explore') && (mode !== 'view')) {
        return;
      }

      if (mode === 'view') {
        touristinfo.map.activeMarker.setAnimation(null);
      }

      marker.setAnimation(google.maps.Animation.BOUNCE);

      touristinfo.map.activeMarker = marker;

      $('#place').load('/ajax/places/' + marker.id);

      if (mode === 'explore') {
        $('a[href="#view"]').tab('show');
      }
    });
  }

  touristinfo.map.init = function () {
    var mapOptions = {
      center: touristinfo.map.center,
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoom: touristinfo.map.zoom
    };

    map = new google.maps.Map($('#map')[0], mapOptions);

    $.getJSON('/ajax/places', function (places) {
      for (var i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });

    autocomplete = new google.maps.places.Autocomplete($('#query')[0]);

    autocomplete.bindTo('bounds', map);

    map.addListener('click', function (event) {
      if (touristinfo.map.mode === 'add') {
        var marker = new google.maps.Marker({
          map: map,
          position: event.latLng,
          draggable: true
        });

        touristinfo.map.markers.push(marker);

        touristinfo.map.mode = 'added';

        $('#latitude').val(event.latLng.lat);
        $('#longitude').val(event.latLng.lng);

        marker.addListener('dragend', function (event) {
          $('#latitude').val(event.latLng.lat);
          $('#longitude').val(event.latLng.lng);
        });
      }
    });
  };

  $.getScript(url);

  $('[data-toggle="tooltip"]').tooltip();

  $('[data-trigger="tab"]').click(function (event) {
    if ($(this).is('a')) {
      event.preventDefault();
    }

    var target = $(this).attr('href') || $(this).data('target');

    $('a[href="' + target + '"]').tab('show');
  });

  $('a[data-toggle="tab"]').on('show.bs.tab', function (event) {
    var target = $(event.target).attr('href');

    switch (target) {
      case '#search':
        touristinfo.map.mode = 'explore';

        break;

      case '#new':
        touristinfo.map.mode = 'add';

        for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
          touristinfo.map.markers[i].setVisible(false);
        }

        break;

      case '#view':
        touristinfo.map.mode = 'view';

        break;
    }
  });

  $('a[data-toggle="tab"]').on('hide.bs.tab', function (event) {
    var target = $(event.target).attr('href');

    switch (target) {
      case '#new':
        touristinfo.map.mode = 'explore';

        for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
          touristinfo.map.markers[i].setVisible(true);
        }

        break;

      case '#view':
        touristinfo.map.mode = 'explore';

        if (touristinfo.map.activeMarker !== null) {
          touristinfo.map.activeMarker.setAnimation(null);

          touristinfo.map.activeMarker = null;
        }

        break;
    }
  });

  $('#filter-places').submit(function (event) {
    event.preventDefault();

    var place = autocomplete.getPlace();

    if (!place.geometry) {
      window.alert('Autocomplete\'s returned place contains no geometry.');

      return;
    }

    var data = {
      distance: $('#distance').val(),
      latitude: place.geometry.location.lat(),
      longitude: place.geometry.location.lng(),
      radius: $('#radius').val()
    };

    $.post('/ajax/places/filter', data, function (places) {
      for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
        touristinfo.map.markers[i].setMap(null);
      }

      touristinfo.map.markers = [];

      for (i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });
  });

  $('#filter-places').on('reset', function () {
    $.getJSON('/ajax/places', function (places) {
      for (var i = touristinfo.map.markers.length - 1; i >= 0; i--) {
        touristinfo.map.markers[i].setMap(null);
      }

      touristinfo.map.markers = [];

      for (i = places.length - 1; i >= 0; i--) {
        addMarker(places[i]);
      }
    });
  });

  $('#add-place').submit(function (event) {
    event.preventDefault();

    $.post('/ajax/places/add', $('#add-place').serialize(), function (id) {
      var n = touristinfo.map.markers.length - 1;
      var marker = touristinfo.map.markers[n];

      marker.id = id;

      marker.setDraggable(false);
      marker.setAnimation(google.maps.Animation.BOUNCE);
      marker.setTitle($('#name').val());

      touristinfo.map.activeMarker = marker;

      $('#add-place').trigger('reset');
      $('a[href="#view"]').tab('show');
    });
  });

  $('#discard-place').click(function () {
    var marker = touristinfo.map.markers.pop();

    marker.setMap(null);
  });

  $('#query').keydown(function (event) {
    if (event.which == 13 && $('.pac-container:visible').length) {
      return false;
    }
  });
})(jQuery);
<|endoftext|>


<commit_before>let DontPanic = {};
let player;
let whale;
let enemy;
let fuelbar;
let background;
let gameStarted = false;
let coinTotal = localStorage['coinTotal'] || '0';
let currentDistance;
let bestDistance = localStorage['bestDistance'] || '0';
let filter;

function init() {
  const gameWidth = 360;
  const gameHeight = 600;
  DontPanic.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, 'gameWindow', {
    preload: preload,
    create: create,
    update: update
  });
}

function preload() {
  DontPanic.game.load.script('filter', 'https://cdn.rawgit.com/photonstorm/phaser/master/v2/filters/LightBeam.js');
  DontPanic.game.load.image('background1', 'assets/space_background.png');
  DontPanic.game.load.image('home_background', 'assets/game_screen.jpg');
  DontPanic.game.load.image('startButton', 'assets/button_start.png'); // placeholders for now
  DontPanic.game.load.image('settingsButton', 'assets/button_settings.png'); // placeholders for now
  DontPanic.game.load.image('playAgainButton', 'assets/button_play-again.png'); // placeholders for now
  DontPanic.game.load.spritesheet('rocket_red', 'assets/rocket_spritesheet1.png', 115, 175);
  DontPanic.game.load.spritesheet('rocket_blue', 'assets/rocket_spritesheet_blue1.png', 115, 175);
  DontPanic.game.load.image('whale', 'assets/whale.png');
  DontPanic.game.load.spritesheet('enemyShip', 'assets/enemy_ship_spritesheet1.png', 440, 1140);
  DontPanic.game.load.image('heart', 'assets/life.png');
  DontPanic.game.load.image('enemyBullet', 'assets/enemy-bullet.png'); //placeholder
  DontPanic.game.load.image('coin', 'assets/coin_2.png');
}

function create() {
  DontPanic.game.world.setBounds(0, 0, 360, 600);
  // DontPanic.game.physics.startSystem(Phaser.Physics.P2JS); //may need to swap to p2 system for better collision areas
  cursors = DontPanic.game.input.keyboard.createCursorKeys();
  mainMenu();
  console.log(config[config.currentLevel]['coinSpawnRate']);
  // DontPanic.game.camera.follow(player.playerSprite, Phaser.Camera.LO);
}

function update() {
  if (gameStarted) {
    player.handleInput();
    handleCollision();
    enemy.moveEnemy();
    // DontPanic.game.debug.spriteBounds(player);
  }
  // game.debug.cameraInfo(game.camera, 32, 32);
}

function startGame() {
  gameStarted = true;
  background = DontPanic.game.add.tileSprite(0, 0, DontPanic.game.width, DontPanic.game.height, 'background1');
  background.autoScroll(0, 50);
  player = new Player();
  whale = new Whale();
  enemy = new Enemy();
  coins = new Coins();
  lives = new Lives();
  coinScore = new CoinScore();
  distanceScore = new DistanceScore();
  // DontPanic.game.camera.follow(player.playerSprite, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);
}

function handleCollision() {
  DontPanic.game.physics.arcade.overlap(player.playerSprite, whale.whaleSprite, obstacleCollision, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, coins.coins, collectCoin, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, enemy.enemies, abductPlayer, null, this);
}

function obstacleCollision() {
  player.playerSprite.kill();
  gameOver();
}

function collectCoin(player, coin) {
  coin.kill();
  coinScore.addToCoinScore()
}

function abductPlayer(player, vogon) {
  console.log('enemy overlap');

  if (!vogon.abductSuccessful && vogon.frame == 2) {
    console.log(lives.lives.livesLeft);
    vogon.abductSuccessful = true;
    // vogon.kill(); // this needs to be something else - doesn't look good to just disappear.
    lives.loseLife();

    // make player animation flash
    player.animations.play('lifeLost', 20, false);
    // pause game assets for a sec?
  }
}

function stopGameAssetGeneration() {
  coins.coinTimer.timer.stop();
  enemy.enemyTimer.timer.stop();
}

function gameOver() {
  player.playerSprite.kill();
  DontPanic.game.gameOver = DontPanic.game.add.text(DontPanic.game.world.centerX, DontPanic.game.world.centerY * 0.75, 'GAME OVER', { font: '40px whoopass', fill: '#fff' });
  DontPanic.game.gameOver.anchor.setTo(0.5);
  DontPanic.game.camera.fade(0x0000000, 4000); // https://phaser.io/examples/v2/camera/camera-fade
  DontPanic.game.camera.onFadeComplete.add(playAgainMenu, this);
  gameStarted = false;
  stopGameAssetGeneration();
  if (currentDistance > parseInt(bestDistance)) {
    localStorage['bestDistance'] = currentDistance.toString();
  }
}
<commit_msg>fix vogon animation abduct, player animation still broken<commit_after>let DontPanic = {};
let player;
let whale;
let enemy;
let fuelbar;
let background;
let gameStarted = false;
let coinTotal = localStorage['coinTotal'] || '0';
let currentDistance;
let bestDistance = localStorage['bestDistance'] || '0';
let filter;

function init() {
  const gameWidth = 360;
  const gameHeight = 600;
  DontPanic.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, 'gameWindow', {
    preload: preload,
    create: create,
    update: update
  });
}

function preload() {
  DontPanic.game.load.script('filter', 'https://cdn.rawgit.com/photonstorm/phaser/master/v2/filters/LightBeam.js');
  DontPanic.game.load.image('background1', 'assets/space_background.png');
  DontPanic.game.load.image('home_background', 'assets/game_screen.jpg');
  DontPanic.game.load.image('startButton', 'assets/button_start.png'); // placeholders for now
  DontPanic.game.load.image('settingsButton', 'assets/button_settings.png'); // placeholders for now
  DontPanic.game.load.image('playAgainButton', 'assets/button_play-again.png'); // placeholders for now
  DontPanic.game.load.spritesheet('rocket_red', 'assets/rocket_spritesheet1.png', 115, 175);
  DontPanic.game.load.spritesheet('rocket_blue', 'assets/rocket_spritesheet_blue1.png', 115, 175);
  DontPanic.game.load.image('whale', 'assets/whale.png');
  DontPanic.game.load.spritesheet('enemyShip', 'assets/enemy_ship_spritesheet1.png', 440, 1140);
  DontPanic.game.load.image('heart', 'assets/life.png');
  DontPanic.game.load.image('enemyBullet', 'assets/enemy-bullet.png'); //placeholder
  DontPanic.game.load.image('coin', 'assets/coin_2.png');
}

function create() {
  DontPanic.game.world.setBounds(0, 0, 360, 600);
  // DontPanic.game.physics.startSystem(Phaser.Physics.P2JS); //may need to swap to p2 system for better collision areas
  cursors = DontPanic.game.input.keyboard.createCursorKeys();
  mainMenu();
  console.log(config[config.currentLevel]['coinSpawnRate']);
  // DontPanic.game.camera.follow(player.playerSprite, Phaser.Camera.LO);
}

function update() {
  if (gameStarted) {
    player.handleInput();
    handleCollision();
    enemy.moveEnemy();
    // DontPanic.game.debug.spriteBounds(player);
  }
  // game.debug.cameraInfo(game.camera, 32, 32);
}

function startGame() {
  gameStarted = true;
  background = DontPanic.game.add.tileSprite(0, 0, DontPanic.game.width, DontPanic.game.height, 'background1');
  background.autoScroll(0, 50);
  player = new Player();
  whale = new Whale();
  enemy = new Enemy();
  coins = new Coins();
  lives = new Lives();
  coinScore = new CoinScore();
  distanceScore = new DistanceScore();
  // DontPanic.game.camera.follow(player.playerSprite, Phaser.Camera.FOLLOW_LOCKON, 0.1, 0.1);
}

function handleCollision() {
  DontPanic.game.physics.arcade.overlap(player.playerSprite, whale.whaleSprite, obstacleCollision, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, coins.coins, collectCoin, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, enemy.enemies, abductPlayer, null, this);
}

function obstacleCollision() {
  player.playerSprite.kill();
  gameOver();
}

function collectCoin(player, coin) {
  coin.kill();
  coinScore.addToCoinScore()
}

function abductPlayer(playerSprite, vogon) {
  console.log('enemy overlap');

  if (!vogon.abductSuccessful && vogon.frame == 3) {
    console.log(lives.lives.livesLeft);
    // vogon.kill(); // this needs to be something else - doesn't look good to just disappear.
    lives.loseLife();
    // make player animation flash
    playerSprite.play('lifeLost');
    vogon.play('abduct');
    vogon.abductSuccessful = true;
    // pause game assets for a sec?
    // DontPanic.game.paused = true;
  }
}

function stopGameAssetGeneration() {
  coins.coinTimer.timer.stop();
  enemy.enemyTimer.timer.stop();
}

function gameOver() {
  player.playerSprite.kill();
  DontPanic.game.gameOver = DontPanic.game.add.text(DontPanic.game.world.centerX, DontPanic.game.world.centerY * 0.75, 'GAME OVER', { font: '40px whoopass', fill: '#fff' });
  DontPanic.game.gameOver.anchor.setTo(0.5);
  DontPanic.game.camera.fade(0x0000000, 4000); // https://phaser.io/examples/v2/camera/camera-fade
  DontPanic.game.camera.onFadeComplete.add(playAgainMenu, this);
  gameStarted = false;
  stopGameAssetGeneration();
  if (currentDistance > parseInt(bestDistance)) {
    localStorage['bestDistance'] = currentDistance.toString();
  }
}
<|endoftext|>


<commit_before>---
layout: null
---
    $(document).ready(function() {
        $('a.blog-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}"));
            setAnimation();
        })

        $('a.about-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}about/"));
            setAnimation();
        })

        $('a.speaking-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}speaking/"));
            setAnimation();
        })

        if (window.location.hash && window.location.hash == '#about') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}about/"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        if (window.location.hash && window.location.hash == '#blog') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        if (window.location.hash && window.location.hash == '#speaking') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}speaking/"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        $('.btn-mobile-menu').click(function() {
            $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
            $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
        })

        $('.navigation-wrapper .blog-button').click(function() {
            $('.navigation-wrapper').toggleClass('visible')
            $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
        })

    })

var getContentFromURL = function(url) {
    var result = null;

    $.ajax({
        url: url,
        type: 'get',
        dataType: 'html',
        async: false,
        success: function(data) {
            result = data;
        }
    });

    var elements = $(result);
    var found_content = $(".content-wrapper__inner", elements);

    return found_content;

}

var setAnimation = function() {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) {
        return

    }
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
        $('.panel-cover').addClass('panel-cover--collapsed')
        $('.content-wrapper').addClass('animated slideInRight')
    } else {
        $('.panel-cover').addClass('panel-cover--collapsed')
        $('.panel-cover').css('max-width', currentWidth)
        $('.panel-cover').animate({ 'max-width': '530px', 'width': '40%' }, 400, swing = 'swing', function() {})

    }
}<commit_msg>debugging<commit_after>---
layout: null
---
    $(document).ready(function() {
        $('a.blog-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}"));
            setAnimation();
        })

        $('a.about-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}about/"));
            setAnimation();
        })

        $('a.speaking-button').click(function(e) {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl }}speaking/"));
            setAnimation();
        })

        if (window.location.hash && window.location.hash == '#about') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}about/"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        if (window.location.hash && window.location.hash == '#blog') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        if (window.location.hash && window.location.hash == '#speaking') {
            $(".content-wrapper").html(getContentFromURL("{{ site.baseurl}}speaking/"));
            $('.panel-cover').addClass('panel-cover--collapsed')
        }

        // if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}index.html') {
        //     $('.panel-cover').addClass('panel-cover--collapsed')
        // }

        $('.btn-mobile-menu').click(function() {
            $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
            $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
        })

        $('.navigation-wrapper .blog-button').click(function() {
            $('.navigation-wrapper').toggleClass('visible')
            $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
        })

    })

var getContentFromURL = function(url) {
    var result = null;

    $.ajax({
        url: url,
        type: 'get',
        dataType: 'html',
        async: false,
        success: function(data) {
            result = data;
        }
    });

    var elements = $(result);
    var found_content = $(".content-wrapper__inner", elements);

    return found_content;

}

var setAnimation = function() {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) {
        return

    }
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
        $('.panel-cover').addClass('panel-cover--collapsed')
        $('.content-wrapper').addClass('animated slideInRight')
    } else {
        $('.panel-cover').addClass('panel-cover--collapsed')
        $('.panel-cover').css('max-width', currentWidth)
        $('.panel-cover').animate({ 'max-width': '530px', 'width': '40%' }, 400, swing = 'swing', function() {})

    }
}<|endoftext|>


<commit_before>

let calculateMonthlyPayment = (principal, years, rate) => {

    let monthlyRate = 0;

    if ( rate ) {
        monthlyRate = rate / 100 / 12;
    }

    let monthlyPayment = principal * monthlyRate /
                         (1 - (Math.pow(1/(1 + monthlyRate), years * 12)));

    return { principal, years, rate, monthlyPayment, monthlyRate };

};

let calculateAmortization = (principal, years, rate) => {

    let { monthlyRate, monthlyPayment } = calculateMonthlyPayment(principal, years, rate);
    let balance = principal;
    let amortization = [];

    for ( let y=0; y<years; y++ ) {

        let interestY = 0;  //Interest payment for year y
        let principalY = 0; //Principal payment for year y

        for ( let m=0; m<12; m++ ) {

            let interestM = balance * monthlyRate;       //Interest payment for month m
            let principalM = monthlyPayment - interestM; //Principal payment for month m
            interestY = interestY + interestM;
            principalY = principalY + principalM;
            balance = balance - principalM;

        }

        amortization.push({ principalY, interestY, balance });

    }
    return { monthlyPayment, monthlyRate, amortization };

};

document.getElementById('calcBtn').addEventListener('click', function () {

    let principal = document.getElementById("principal").value;
    let years = document.getElementById("years").value;
    let rate = document.getElementById("rate").value;

    //let monthlyPayment = calculateMonthlyPayment(principal, years, rate);
    let { monthlyPayment, monthlyRate } = calculateMonthlyPayment(principal, years, rate);

    console.log('monthlyPayment ', monthlyPayment);

    document.getElementById("monthlyPayment").innerHTML = monthlyPayment.toFixed(2);
    document.getElementById("monthlyRate").innerHTML = (monthlyRate * 100).toFixed(2);

});
<commit_msg>arrow syntax change<commit_after>

let calculateMonthlyPayment = (principal, years, rate) => {

    let monthlyRate = 0;

    if ( rate ) {
        monthlyRate = rate / 100 / 12;
    }

    let monthlyPayment = principal * monthlyRate /
                         (1 - (Math.pow(1/(1 + monthlyRate), years * 12)));

    return { principal, years, rate, monthlyPayment, monthlyRate };

};

let calculateAmortization = (principal, years, rate) => {

    let { monthlyRate, monthlyPayment } = calculateMonthlyPayment(principal, years, rate);
    let balance = principal;
    let amortization = [];

    for ( let y=0; y<years; y++ ) {

        let interestY = 0;  //Interest payment for year y
        let principalY = 0; //Principal payment for year y

        for ( let m=0; m<12; m++ ) {

            let interestM = balance * monthlyRate;       //Interest payment for month m
            let principalM = monthlyPayment - interestM; //Principal payment for month m
            interestY = interestY + interestM;
            principalY = principalY + principalM;
            balance = balance - principalM;

        }

        amortization.push({ principalY, interestY, balance });

    }
    return { monthlyPayment, monthlyRate, amortization };

};

document.getElementById('calcBtn').addEventListener('click', () => {

    let principal = document.getElementById("principal").value;
    let years = document.getElementById("years").value;
    let rate = document.getElementById("rate").value;

    //let monthlyPayment = calculateMonthlyPayment(principal, years, rate);
    let { monthlyPayment, monthlyRate } = calculateMonthlyPayment(principal, years, rate);

    console.log('monthlyPayment ', monthlyPayment);

    document.getElementById("monthlyPayment").innerHTML = monthlyPayment.toFixed(2);
    document.getElementById("monthlyRate").innerHTML = (monthlyRate * 100).toFixed(2);

});
<|endoftext|>


<commit_before>var firstkey = true;
var startTime = 0;
var currentTime = 0;
var globalData;
var lastBoldedIndex = -1;

$('#comment-input').keydown(function(event) {
	if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
		if (firstkey) {
			firstkey = false;
			startTime = document.getElementById("main-video").currentTime;
		}

	}
});

$("#comment-input").keyup(function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if (code == 13) { //Enter keycode

		var comment = document.getElementById("comment-input").value;
		var endTime = document.getElementById("main-video").currentTime;

		console.log("Adding comment:" + comment);
		console.log("with StartTime:" + startTime);
		console.log("and endTime:" + endTime);

		//TODO: need to fix.
		//add comment to popcorn instance
		var popcorn = Popcorn("#main-video");

		popcorn.footnote({
			start: 0,
			end: 5,
			target: "footnotes",
			text: comment
		});

		//display new comment for 2 seconds
		var newFootnotes = document.getElementById("green-block");
		newFootnotes.style.visibility = 'visible';
		newFootnotes.innerHTML = comment;
		setTimeout(function() {
			newFootnotes.style.visibility = 'hidden';
			newFootnotes("green_footnotes").innerHTML = '';
		}, 2000); // 2000 ms = 2 s

		//TODO:add comment to server

		//TODO:add to annotation-container

		//reset stuff
		startTime = 0;
		document.getElementById("comment-input").value = '';
		firstkey = true;
	}
});

function getServer() {
	var popcorn = Popcorn("#main-video");
	popcorn.on('timeupdate', function(number) {
		if (Math.floor(this.currentTime()) > currentTime) {
			currentTime = Math.floor(this.currentTime());
			populatePageWithData(currentTime);
		}
	});
	$.ajax({
		url: "http://vidersion.herokuapp.com/get?id=1",
		type: "GET",
		dataType: "jsonp",
		crossDomain: true,
		jsonp: "callback",
		// cache: false,
		jsonpCallback: "JSONPCallback",
		error: function(xhr, status, error) {
			console.log("error!");
			console.dir(error);
		},
		success: function(data) {
			globalData = data;
			populatePageWithData();
			//add to popcorn
			var popcorn = Popcorn("#main-video");
			for (var i = 0; i < globalData.length; i++) {
				//add to popcorn instance
				popcorn.footnote({
					start: i,
					end: i + 1,
					target: "footnotes",
					text: globalData[i]["text"]
				});
			}
		}
	});
}

function populatePageWithData(currentTime) {

	//add to annotation list
	globalData.sort(function(a, b) {
		if (a.start_timecode  b.start_timecode) {
			return 1;
		} else {
			return 0;
		}
	});

	var boldedIndex = 0;
	for (var j = 0; j < globalData.length; j++) {
		if (currentTime <= globalData[j].start_timecode) {
			boldedIndex = j - 1;
			break;
		}
	}
	if (boldedIndex < 0) {
		boldedIndex = 0;
	}
	if (lastBoldedIndex === boldedIndex) {
		return;
	} else {
		lastBoldedIndex = boldedIndex;
	}

	var content = "";
	for (var i = 0; i < globalData.length; i++) {
		var comment = globalData[i];
		content += '
';
		if (i === boldedIndex) {
			content += "";
		}
		content += comment.text;
		content += '';
		content += 'at ';
		content += '';
		if (comment.start_timecode > 59) {
			content += Math.floor(comment.start_timecode / 60);
			content += ":";
			content += comment.start_timecode % 60;
		} else if (comment.start_timecode < 10) {
			content += "0:0" + comment.start_timecode;
		} else {
			content += "0:" + comment.start_timecode;
		}
		if (i === boldedIndex) {
			content += "";
		}
		content += '
';
	}
	$("#annotation-container").empty();
	$("#annotation-container").append(content);
}<commit_msg>change footnotes to code<commit_after>var firstkey = true;
var startTime = 0;
var currentTime = 0;
var globalData;
var lastBoldedIndex = -1;

$('#comment-input').keydown(function(event) {
	if (event.keyCode >= 65 && event.keyCode <= 90) { // if a letter pressed
		if (firstkey) {
			firstkey = false;
			startTime = document.getElementById("main-video").currentTime;
		}

	}
});

$("#comment-input").keyup(function(e) {
	var code = (e.keyCode ? e.keyCode : e.which);
	if (code == 13) { //Enter keycode

		var comment = document.getElementById("comment-input").value;
		var endTime = document.getElementById("main-video").currentTime;

		console.log("Adding comment:" + comment);
		console.log("with StartTime:" + startTime);
		console.log("and endTime:" + endTime);

		//TODO: need to fix.
		//add comment to popcorn instance
		var popcorn = Popcorn("#main-video");
		popcorn.code({
			start: 8,
			end: 10,
			onStart:function(options){
				console.log(options);
				document.getElementById("blue-block").innerHTML = comment;
			},
			onEnd: function(options){
				document.getElementById("blue-block").innerHTML = '';
			}
		});

		//display new comment for 2 seconds
		var newFootnotes = document.getElementById("green-block");
		newFootnotes.style.visibility = 'visible';
		newFootnotes.innerHTML = comment;
		setTimeout(function() {
			newFootnotes.style.visibility = 'hidden';
			newFootnotes.innerHTML = '';
		}, 2000); // 2000 ms = 2 s

		//TODO:add comment to server

		//TODO:add to annotation-container

		//reset stuff
		startTime = 0;
		document.getElementById("comment-input").value = '';
		firstkey = true;
	}
});

function getServer() {
	var popcorn = Popcorn("#main-video");
	popcorn.on('timeupdate', function(number) {
		if (Math.floor(this.currentTime()) > currentTime) {
			currentTime = Math.floor(this.currentTime());
			populatePageWithData(currentTime);
		}
	});
	$.ajax({
		url: "http://vidersion.herokuapp.com/get?id=1",
		type: "GET",
		dataType: "jsonp",
		crossDomain: true,
		jsonp: "callback",
		// cache: false,
		jsonpCallback: "JSONPCallback",
		error: function(xhr, status, error) {
			console.log("error!");
			console.dir(error);
		},
		success: function(data) {
			globalData = data;
			populatePageWithData();
			//add to popcorn
			var popcorn = Popcorn("#main-video");
			for (var i = 0; i < globalData.length; i++) {
				popcorn.code({
					start:i,
					end:i+2,
					ie: i,
					onStart:function(options){
						console.log(options);
						document.getElementById("blue-block").innerHTML = globalData[options.ie]["text"];
					},
					onEnd: function(options){
						document.getElementById("blue-block").innerHTML = '';
					}
				});

			}
		}
	});
}

function populatePageWithData(currentTime) {

	//add to annotation list
	globalData.sort(function(a, b) {
		if (a.start_timecode  b.start_timecode) {
			return 1;
		} else {
			return 0;
		}
	});

	var boldedIndex = 0;
	for (var j = 0; j < globalData.length; j++) {
		if (currentTime <= globalData[j].start_timecode) {
			boldedIndex = j - 1;
			break;
		}
	}
	if (boldedIndex < 0) {
		boldedIndex = 0;
	}
	if (lastBoldedIndex === boldedIndex) {
		return;
	} else {
		lastBoldedIndex = boldedIndex;
	}

	var content = "";
	for (var i = 0; i < globalData.length; i++) {
		var comment = globalData[i];
		content += '
';
		if (i === boldedIndex) {
			content += "";
		}
		content += comment.text;
		content += '';
		content += 'at ';
		content += '';
		if (comment.start_timecode > 59) {
			content += Math.floor(comment.start_timecode / 60);
			content += ":";
			content += comment.start_timecode % 60;
		} else if (comment.start_timecode < 10) {
			content += "0:0" + comment.start_timecode;
		} else {
			content += "0:" + comment.start_timecode;
		}
		if (i === boldedIndex) {
			content += "";
		}
		content += '
';
	}
	$("#annotation-container").empty();
	$("#annotation-container").append(content);
}<|endoftext|>


<commit_before>// To the global namespace just for now
var theme = new Soundgun("sounds/long-test.ogg");

$(function () {
    engine = new PongEngine();
    engine.startEngine();

    // Some music
    theme.setVolume(0);
    theme.play();
    theme.fadeIn();
    theme.loop();

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
        engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            console.log("right");
            engine.ball.movingVector.elements[0]++;
        },
        leftPressed = function() {
            console.log("left");
            engine.ball.movingVector.elements[0]--;
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        keyHandlers[e.keyCode]();
        return true;
    });

    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
    });

});
<commit_msg>Fixed bug with prevent-scrolling-thingy<commit_after>// To the global namespace just for now
var theme = new Soundgun("sounds/long-test.ogg");

$(function () {
    engine = new PongEngine();
    engine.startEngine();

    // Some music
    theme.setVolume(0);
    theme.play();
    theme.fadeIn();
    theme.loop();

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
        engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            console.log("right");
            engine.ball.movingVector.elements[0]++;
        },
        leftPressed = function() {
            console.log("left");
            engine.ball.movingVector.elements[0]--;
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        keyHandlers[e.keyCode]();
        return false;
    });

    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
    });

});
<|endoftext|>


<commit_before>// ========================================================================
// viewModel class
// ========================================================================
function viewModel(){
    var self = this;

    // ========================================================================
    // Controls subpage
    // ========================================================================
    // | Section  | Option  |  Function |  Comment  |
    // | -------- | ------- | --------- | --------- |
    // | design   |  exp    |  exp_old  |           |
    // |          |         |  exp_new  |           |
    // |          |  lay    |  lay_old  |           |
    // |          |         |  lay_new  |           |
    // |          |  imp    |  imp_file |           |
    // |          |         |  imp_manu |           |
    // | vis      |  plate  |           |           |
    // |          |  genes  |           |           |
    // | analysis |  norm   |           |           |
    // |          |  expt   |           |           |
    //
    self.sec = ko.observable('design');  // Active section
    self.opt = ko.observable('exp');     // Active option
    self.fun = ko.observable('exp_old'); // Active function

    // Experiment subpage
    self.exp = new ExpVM();

    // ========================================================================
    // Layout subpage
    // ========================================================================
    //
    // Factor (independent variables)
    self.exp_fact = ko.observableArray([new ExpVar()]);
    self.layouts = ko.observableArray(['AAA', 'BBB']);
    self.layout_exps = ko.observableArray(['AAA','AAA']);

    // ========================================================================
    // Plates
    // ========================================================================

    // Visualize plate
    self.vis_plate = ko.observable(false);

    // ========================================================================
    // Genes Vis: Factor selection and query
    // ========================================================================
    // Available factor for visualization
    self.factors = getFactors();

    // Factor chosen to be added
    self.factor_chosen = ko.observable();

    // Factor selected
    self.factor_panels = ko.observableArray();

    // Add a factor selection panel
    self.add_panel = function() {
        if (self.factor_chosen()){
            self.factor_panels.push(self.factor_chosen());
            self.factors.remove(self.factor_chosen());
            self.factor_chosen();
        }
    };

    // Remove a factor
    self.del_panel = function(fact) {
        self.factor_panels.remove(fact);
        self.factors.push(fact);
        self.factors.sort(function(left, right) {
            return left.name == right.name ? 0 :
            (left.name < right.name ? -1 : 1)
        });
        self.factor_chosen();

        // console.log(fact);
        // self.factor_panels.remove(fact)
        // fact._destroy = false;
        // self.factors.valueHasMutated();
    };

    // ========================================================================
    // Genes Vis: Time series curve vis
    // ========================================================================
    // vis row
    self.row = ko.observableArray([ ['a', 'b'], ['c', 'd'] ]);

}

// ========================================================================
// Experiment viewModel class
// ========================================================================
function ExpVM() {
    var self = this;

    // Possible values: old, new
    self.fun = ko.observable('old');
    // Reset current_exp every time fun changes
    self.fun.subscribe(function(){self.current_exp(null);})

    self.experiments = ko.observableArray();
    self.current_exp = ko.observable();

    self.current_exp.subscribe(function(new_exp){
        self.exp_chnl(null);
        for (c in new_exp.channels){
            self.exp_chnl.push(new_exp.channels[c]);
        }
    })

    // General information
    self.name = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().name;
        }
    });

    self.user = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().user;
        }
    });

    // Well numbers
    self.well_types = [96, 384];
    self.well = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().well;
        }
    })

    // TODO: refresh button
    $.ajax({
        url: "/api/v2/experiment",
        type: "GET",
        success: function(data){
            for (e in data.experiment){
                self.experiments.push(data.experiment[e]);
            }
        }
    });

    // Factor (independent variables)
    self.exp_fact = ko.observableArray([new ExpVar()]);

    // Channels (dependent variables)
    self.exp_chnl = ko.observableArray();

    self.var_types = ['Category', 'Integer', 'Decimal'];

    // Add a new dependent
    self.add_chnl = function() { self.exp_chnl.push(new ExpVar()) };

    // Remove a channel
    self.del_chnl = function(chnl) { self.exp_chnl.remove(chnl) };

    // Add a new independent
    self.add_fact = function() { self.exp_fact.push(new ExpVar()) };

    // Remove a factor
    self.del_fact = function(fact) { self.exp_fact.remove(fact) };
}

// ========================================================================
// Experiment class
// ========================================================================
function Exp(name, user, well_num) {
    var self = this;
    self.name = name;
    self.user = user;
    self.well_num = 96;

    self.layouts = ko.observableArray();
}

// ========================================================================
// Experiment class
// ========================================================================
function Layout(name, well_num) {
    var self = this;
}

// Get Factor for experiment
// return a observableArray of FactorPanel
function getFactors(exp) {
    return ko.observableArray([new FactorPanel('A'),
                               new FactorPanel('B')]);
}

// Search
function searchLevel(val) {
    var self = this;
    // check if string is empty
    if (val){
        for (g in self.levels()){
            if (self.levels()[g].name.search(val) === -1){
                self.levels()[g]._destroy = true;
            } else {
                self.levels()[g]._destroy = false;
            }
        }
    } else {
        for (g in self.levels()){
            self.levels()[g]._destroy = false;
        }
    }
    self.levels.valueHasMutated();
}

// Factor class
var FactorPanel = function(name) {
    var self = this;
    self.name = name;
    self.query = ko.observable();
    self.query.subscribe(searchLevel, self);

    self.levels = ko.observableArray([new Level('1'), new Level('2')]);
    self.chosen_levels = ko.observable([]);
}

var Level = function(name){
    var self = this;
    self.name = name;
    self.value = 1;
}

var ExpVar = function() {
    var self = this;
    self.name = ko.observable();
    self.type = ko.observable();
};
var vm = new viewModel();
ko.applyBindings(vm);

// ========================================================================
// handsontable
// ========================================================================
var createSetting = function(nRow, nCol, fixRow){
    self.startRows = nRow;
    self.minRows = nRow;
    if (fixRow) {
        self.maxRows = nRow;
    }

    self.startCols = nCol;
    self.minCols = nCol;
    self.maxCols = nCol;

    self.manualColumnResize = true;
    self.manualRowResize = true;
    self.contextMenu = true;

    self.rowHeaders = function(i) { return String.fromCharCode(65 + i); };
    self.colHeaders = function(i) { return i+1; };
};

// TODO oop setting, make it dynamic for all types of tables
var setting = {
    startCols:12,
    minCols:12,
    maxCols:12,
    // colWidths: 28,
    startRows:8,
    manualColumnResize:true,
    manualRowResize:true,
    rowHeaders:function (i) { return String.fromCharCode(65 + i); },
    colHeaders:function (i) { return i+1; },
    contextMenu: true
};

var container1 = document.getElementById("well");
var hot1 = new Handsontable(container1, setting);
var container2 = document.getElementById("data_table");
var hot2 = new Handsontable(container2, setting);

$("#time-slider").slider();

<commit_msg>Update knockout <-> API interaction<commit_after>// ========================================================================
// viewModel class
// ========================================================================
function viewModel(){
    var self = this;

    // ========================================================================
    // Controls subpage
    // ========================================================================
    // | Section  | Option  |  Function |  Comment  |
    // | -------- | ------- | --------- | --------- |
    // | design   |  exp    |  exp_old  |           |
    // |          |         |  exp_new  |           |
    // |          |  lay    |  lay_old  |           |
    // |          |         |  lay_new  |           |
    // |          |  imp    |  imp_file |           |
    // |          |         |  imp_manu |           |
    // | vis      |  plate  |           |           |
    // |          |  genes  |           |           |
    // | analysis |  norm   |           |           |
    // |          |  expt   |           |           |
    //
    self.sec = ko.observable('design');  // Active section
    self.opt = ko.observable('exp');     // Active option
    self.fun = ko.observable('exp_old'); // Active function

    // Experiment subpage
    self.exp = new ExpVM();

    // ========================================================================
    // Layout subpage
    // ========================================================================
    //
    // Factor (independent variables)
    self.exp_fact = ko.observableArray([new ExpVar()]);
    self.layouts = ko.observableArray(['AAA', 'BBB']);
    self.layout_exps = ko.observableArray(['AAA','AAA']);

    // ========================================================================
    // Plates
    // ========================================================================

    // Visualize plate
    self.vis_plate = ko.observable(false);

    // ========================================================================
    // Genes Vis: Factor selection and query
    // ========================================================================
    // Available factor for visualization
    self.factors = getFactors();

    // Factor chosen to be added
    self.factor_chosen = ko.observable();

    // Factor selected
    self.factor_panels = ko.observableArray();

    // Add a factor selection panel
    self.add_panel = function() {
        if (self.factor_chosen()){
            self.factor_panels.push(self.factor_chosen());
            self.factors.remove(self.factor_chosen());
            self.factor_chosen();
        }
    };

    // Remove a factor
    self.del_panel = function(fact) {
        self.factor_panels.remove(fact);
        self.factors.push(fact);
        self.factors.sort(function(left, right) {
            return left.name == right.name ? 0 :
            (left.name < right.name ? -1 : 1)
        });
        self.factor_chosen();

        // console.log(fact);
        // self.factor_panels.remove(fact)
        // fact._destroy = false;
        // self.factors.valueHasMutated();
    };

    // ========================================================================
    // Genes Vis: Time series curve vis
    // ========================================================================
    // vis row
    self.row = ko.observableArray([ ['a', 'b'], ['c', 'd'] ]);

}

// ========================================================================
// Experiment viewModel class
// ========================================================================
function ExpVM() {
    var self = this;

    // =====================
    // Current functionality
    // =====================
    // Possible values: old, new
    self.fun = ko.observable('old');

    // Reset current_exp every time fun changes
    self.fun.subscribe(function(){self.current_exp(null);})

    // =====================
    // Experiment objs
    // =====================
    self.experiments = ko.observableArray();
    self.current_exp = ko.observable();
    // Factor (independent variables)
    self.exp_fact = ko.observableArray([new ExpVar()]);
    // Channels (dependent variables)
    self.exp_chnl = ko.observableArray();

    // Reset exp_fact everytime the current_exp is reset
    self.current_exp.subscribe(function(exp){
        self.exp_fact([]);
        if (exp) {
            for (f in exp.factors){
                self.exp_fact.push(exp.factors[f]);
            }
        }
    })

    // Reset exp_chnl everytime the current_exp is reset
    self.current_exp.subscribe(function(exp){
        self.exp_chnl([]);
        if (exp) {
            for (c in exp.channels){
                self.exp_chnl.push(exp.channels[c]);
            }
        }
    })

    // General information
    self.name = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().name;
        }
    });

    self.user = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().user;
        }
    });

    // Well numbers
    self.well_types = [96, 384];
    self.well = ko.computed(function(){
        if (self.current_exp()){
            return self.current_exp().well;
        }
    })

    // TODO: refresh button
    $.ajax({
        url: "/api/v2/experiment",
        type: "GET",
        success: function(data){
            for (e in data.experiment){
                self.experiments.push(data.experiment[e]);
            }
        }
    });

    // TODO disable update button if there is no change
    self.update_exp = function() {
        $.ajax({
            url: "/api/v2/experiment",
            type: "PUT",
            dataType: "json",
            data: JSON.stringify({experiment: [self.current_exp()]}),
            contentType: "application/json; charset=utf-8",
            success: function(data){
                self.current_exp(data);
            }
        });
    };

    self.var_types = ['Category', 'Integer', 'Decimal'];

    // Add a new dependent
    self.add_chnl = function() { self.exp_chnl.push(new ExpVar()) };

    // Remove a channel
    self.del_chnl = function(chnl) { self.exp_chnl.remove(chnl) };

    // Add a new independent
    self.add_fact = function() { self.exp_fact.push(new ExpVar()) };

    // Remove a factor
    self.del_fact = function(fact) { self.exp_fact.remove(fact) };
}

// ========================================================================
// Experiment class
// ========================================================================
function Exp(name, user, well_num) {
    var self = this;
    self.name = name;
    self.user = user;
    self.well_num = 96;

    self.layouts = ko.observableArray();
}

// ========================================================================
// Experiment class
// ========================================================================
function Layout(name, well_num) {
    var self = this;
}

// Get Factor for experiment
// return a observableArray of FactorPanel
function getFactors(exp) {
    return ko.observableArray([new FactorPanel('A'),
                               new FactorPanel('B')]);
}

// Search
function searchLevel(val) {
    var self = this;
    // check if string is empty
    if (val){
        for (g in self.levels()){
            if (self.levels()[g].name.search(val) === -1){
                self.levels()[g]._destroy = true;
            } else {
                self.levels()[g]._destroy = false;
            }
        }
    } else {
        for (g in self.levels()){
            self.levels()[g]._destroy = false;
        }
    }
    self.levels.valueHasMutated();
}

// Factor class
var FactorPanel = function(name) {
    var self = this;
    self.name = name;
    self.query = ko.observable();
    self.query.subscribe(searchLevel, self);

    self.levels = ko.observableArray([new Level('1'), new Level('2')]);
    self.chosen_levels = ko.observable([]);
}

var Level = function(name){
    var self = this;
    self.name = name;
    self.value = 1;
}

var ExpVar = function() {
    var self = this;
    self.name = ko.observable();
    self.type = ko.observable();
};
var vm = new viewModel();
ko.applyBindings(vm);

// ========================================================================
// handsontable
// ========================================================================
var createSetting = function(nRow, nCol, fixRow){
    self.startRows = nRow;
    self.minRows = nRow;
    if (fixRow) {
        self.maxRows = nRow;
    }

    self.startCols = nCol;
    self.minCols = nCol;
    self.maxCols = nCol;

    self.manualColumnResize = true;
    self.manualRowResize = true;
    self.contextMenu = true;

    self.rowHeaders = function(i) { return String.fromCharCode(65 + i); };
    self.colHeaders = function(i) { return i+1; };
};

// TODO oop setting, make it dynamic for all types of tables
var setting = {
    startCols:12,
    minCols:12,
    maxCols:12,
    // colWidths: 28,
    startRows:8,
    manualColumnResize:true,
    manualRowResize:true,
    rowHeaders:function (i) { return String.fromCharCode(65 + i); },
    colHeaders:function (i) { return i+1; },
    contextMenu: true
};

var container1 = document.getElementById("well");
var hot1 = new Handsontable(container1, setting);
var container2 = document.getElementById("data_table");
var hot2 = new Handsontable(container2, setting);

$("#time-slider").slider();

<|endoftext|>