<commit_before>/*
 * Copyright (c) 2015 Kasra Faghihi. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function updateTime() {
	var h, m, s;

	if (typeof timerStartDate !== 'undefined') {
		var timeDiff = Math.abs(new Date().getTime() - timerStartDate.getTime());
		s = Math.floor(timeDiff / 1000) % 60;
		m = Math.floor(timeDiff / 1000 / 60) % 60;
		h = Math.floor(timeDiff / 1000 / 60 / 60) % 24;
	} else {
	    var today = new Date();
	    h = today.getHours();
	    m = today.getMinutes();
	    s = today.getSeconds();
	}

    var padTimeElement = function padTimeElement(i) {
        if (i < 10) {
        	i = '0' + i
        };
        return i;
    };

    h = padTimeElement(h);
    m = padTimeElement(m);
    s = padTimeElement(s);
    document.querySelector('#time').textContent = h + ':' + m + ':' + s;
}

function updateBatteryState()  {
	var elem = document.querySelector('#battery_level');
	var elem_icon = document.querySelector('#battery_icon');
	var elem_outter = document.querySelector('#battery');

	var level = Math.floor(battery.level * 100);
	elem.textContent = Math.floor(battery.level * 100);

	if (level <= 20) {
		elem_outter.style.color = 'red';
		elem_icon.className = 'fa fa-battery-0';
	} else if (level <= 40) {
		elem_outter.style.color = 'yellow';
		elem_icon.className = 'fa fa-battery-1';
	} else if (level <= 60) {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-2';
	} else if (level < 80) {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-3';
	} else {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-4';
	}
}

SPINNER = ['|', '/', '-', '\\'];

function updateHeartRate(hrmInfo)  {
	var elem = document.querySelector('#heartrate_level');
	var elem_outter = document.querySelector('#heartrate');

	if (hrmInfo.heartRate == 0) {
		hrmFailCount++;

		elem.textContent = SPINNER[hrmFailCount % SPINNER.length];
		if (hrmFailCount % 200 == 0) {
			// If you get 201 0's in a row, the sensor gives up. Close it and re-open it to try again.
			tizen.humanactivitymonitor.stop('HRM');
			tizen.humanactivitymonitor.start('HRM', updateHeartRate);
		}

		elem_outter.style.color = '';
		lastHeartRate = hrmInfo.heartRate;
	} else if (hrmInfo.heartRate >= 0) {
		// Heartrate numbers were taken from calculations on http://www.livestrong.com/article/208307-how-to-calculate-heart-rate-for-fat-burn/
		// Adjusted for 31 yearold individual
		if (hrmInfo.heartRate < 103.95) {
			elem_outter.style.color = '';
			if (oldHeartRate >= 103.95) {
				navigator.vibrate(2000);
			}
		} else if (hrmInfo.heartRate >= 103.95 && hrmInfo.heartRate <= 132.3) {
			elem_outter.style.color = 'lime';
			if (oldHeartRate < 103.95 || oldHeartRate > 132.3) {
				navigator.vibrate(2000);
			}
		} else {
			elem_outter.style.color = 'red';
			if (oldHeartRate <= 132.3) {
				navigator.vibrate(2000);
			}
		}

		elem.textContent = hrmInfo.heartRate;
		lastHeartRate = hrmInfo.heartRate;
	} else if (hrmInfo.heartRate == -3){
		elem.textContent = 'OFF';
		elem_outter.style.color = '';
		lastHeartRate = 0;
	} else if (hrmInfo.heartRate == -2){
		elem.textContent = 'SHK';
		elem_outter.style.color = '';
		lastHeartRate = 0;
	}

	oldHeartRate = hrmInfo.heartRate;
}

function updatePedometer(pedometerInfo) {
	var elem = document.querySelector('#pedometer_level');
	var elem_outter = document.querySelector('#pedometer');

	if (pedometerInfo.stepStatus == 'WALKING') {
		elem_outter.style.color = 'lime';
		lastSpeed = pedometerInfo.speed;
	} else if (pedometerInfo.stepStatus == 'NOT_MOVING') {
		elem_outter.style.color = '';
		lastSpeed = 0;
	} else {
		elem_outter.style.color = 'yellow';
		lastSpeed = pedometerInfo.speed;
	}

	elem.textContent = pedometerInfo.speed;
}

function timerSwitched() {
	var checkbox = document.querySelector('#timerSwitch');
	if (checkbox.checked) {
		timerStartDate = new Date();
	} else {
		timerStartDate = undefined;
	}
}

function sportSwitched() {
	var elem = document.querySelector('#sport_chart');

	var checkbox = document.querySelector('#sportSwitch');
	if(checkbox.checked === true) {
		tizen.power.request('CPU', 'CPU_AWAKE');

		lastHeartRate = 0;
		lastSpeed = 0;

		sportChartMaxCount = 60 * 60 / 10; // number of seconds in an hour / 10
		sportChartCount = 60 * 60 / 10; // pretend like we've got a full count of points, because initial points is array of maxCount 0s

		var data = {
			    labels: Array.apply(null, new Array(sportChartMaxCount)).map(String.prototype.valueOf, ''),
			    labelsFilter: function (label) { return true },
			    datasets: [
			        {
			            label: 'HRM',
			            fillColor: 'rgba(220,220,220,0.2)',
			            strokeColor: "rgba(220,220,220,0.6)",
			            data: Array.apply(null, new Array(sportChartMaxCount)).map(Number.prototype.valueOf, 0),
			        },
			        {
			            label: 'Speed',
			            fillColor: 'rgba(151,187,205,0.2)',
			            strokeColor: "rgba(151,187,205,0.6)",
			            data: Array.apply(null, new Array(sportChartMaxCount)).map(Number.prototype.valueOf, 0),
			        }
			    ]
			};

		var options = {
				animation: false,
				responsive: false,
				maintainAspectRatio: false,
				showTooltips: false,
			    scaleShowGridLines : false,
			    scaleGridLineColor : 'rgba(0,0,0,.05)',
			    scaleGridLineWidth : 1,
			    scaleShowHorizontalLines: false,
			    scaleShowVerticalLines: false,
			    bezierCurve : false,
			    pointDot : false,
			    datasetStroke : true,
			    datasetStrokeWidth : 2,
			    datasetFill : true,
			};

		sportChart = new Chart(elem.getContext('2d')).Line(data, options);

		sportChartUpdater = setInterval(function() {
			while (sportChartCount >= sportChartMaxCount) {
				sportChart.removeData();
				sportChartCount--;
			}

			sportChart.addData([lastHeartRate, lastSpeed], '');
			sportChartCount++;
		}, 10000); // call once every 10 seconds
	} else {
		tizen.power.release('CPU');

		sportChart.clear();
		sportChart.destroy();
		clearInterval(sportChartUpdater);
	}
}

function init() {
	battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

	document.addEventListener('visibilitychange', function() {
	    if (document.hidden) {
	    	deactivate();
	    } else {
	    	activate();
	    }
	}, false);

	activate();
}

function activate() {
	rssInit();

	updateTime();
	timeUpdateTimer = setInterval(updateTime, 500);

	if (document.querySelector('#sportSwitch').checked === false) {
		document.querySelector('#pedometer').style.color = '';
		document.querySelector('#pedometer_level').textContent = '-';
		document.querySelector('#heartrate').style.color = '';
		document.querySelector('#heartrate_level').textContent = '-';
		oldHeartRate = 0;
		hrmFailCount = 0;
		tizen.humanactivitymonitor.start('HRM', updateHeartRate);
		tizen.humanactivitymonitor.setAccumulativePedometerListener(updatePedometer);
	}

	document.querySelector('#battery').style.color = '';
	document.querySelector('#battery_level').textContent = '-';
	battery.addEventListener('levelchange', updateBatteryState);
	updateBatteryState();
}

function deactivate() {
	clearInterval(timeUpdateTimer);

	if (document.querySelector('#sportSwitch').checked === false) {
		tizen.humanactivitymonitor.stop('HRM');
		tizen.humanactivitymonitor.unsetAccumulativePedometerListener();
	}

	battery.removeEventListener('levelchange', updateBatteryState);
}
<commit_msg>Vibrate while screen is off + multiply speed by 10 for better visualization<commit_after>/*
 * Copyright (c) 2015 Kasra Faghihi. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function updateTime() {
	var h, m, s;

	if (typeof timerStartDate !== 'undefined') {
		var timeDiff = Math.abs(new Date().getTime() - timerStartDate.getTime());
		s = Math.floor(timeDiff / 1000) % 60;
		m = Math.floor(timeDiff / 1000 / 60) % 60;
		h = Math.floor(timeDiff / 1000 / 60 / 60) % 24;
	} else {
	    var today = new Date();
	    h = today.getHours();
	    m = today.getMinutes();
	    s = today.getSeconds();
	}

    var padTimeElement = function padTimeElement(i) {
        if (i < 10) {
        	i = '0' + i
        };
        return i;
    };

    h = padTimeElement(h);
    m = padTimeElement(m);
    s = padTimeElement(s);
    document.querySelector('#time').textContent = h + ':' + m + ':' + s;
}

function updateBatteryState()  {
	var elem = document.querySelector('#battery_level');
	var elem_icon = document.querySelector('#battery_icon');
	var elem_outter = document.querySelector('#battery');

	var level = Math.floor(battery.level * 100);
	elem.textContent = Math.floor(battery.level * 100);

	if (level <= 20) {
		elem_outter.style.color = 'red';
		elem_icon.className = 'fa fa-battery-0';
	} else if (level <= 40) {
		elem_outter.style.color = 'yellow';
		elem_icon.className = 'fa fa-battery-1';
	} else if (level <= 60) {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-2';
	} else if (level < 80) {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-3';
	} else {
		elem_outter.style.color = '';
		elem_icon.className = 'fa fa-battery-4';
	}
}

SPINNER = ['|', '/', '-', '\\'];

function updateHeartRate(hrmInfo)  {
	var elem = document.querySelector('#heartrate_level');
	var elem_outter = document.querySelector('#heartrate');

	if (hrmInfo.heartRate == 0) {
		hrmFailCount++;

		elem.textContent = SPINNER[hrmFailCount % SPINNER.length];
		if (hrmFailCount % 200 == 0) {
			// If you get 201 0's in a row, the sensor gives up. Close it and re-open it to try again.
			tizen.humanactivitymonitor.stop('HRM');
			tizen.humanactivitymonitor.start('HRM', updateHeartRate);
		}

		elem_outter.style.color = '';
		lastHeartRate = hrmInfo.heartRate;
	} else if (hrmInfo.heartRate >= 0) {
		// Heartrate numbers were taken from calculations on http://www.livestrong.com/article/208307-how-to-calculate-heart-rate-for-fat-burn/
		// Adjusted for 31 yearold individual
		if (hrmInfo.heartRate < 103.95) {
			elem_outter.style.color = '';
			if (oldHeartRate >= 103.95) {
				// Vibrate won't work if the screen is off, so temporarily turn it on
				tizen.power.request('SCREEN', 'SCREEN_NORMAL');
				navigator.vibrate(2000);
				tizen.power.release('SCREEN');
			}
		} else if (hrmInfo.heartRate >= 103.95 && hrmInfo.heartRate <= 132.3) {
			elem_outter.style.color = 'lime';
			if (oldHeartRate < 103.95 || oldHeartRate > 132.3) {
				// Vibrate won't work if the screen is off, so temporarily turn it on
				tizen.power.request('SCREEN', 'SCREEN_NORMAL');
				navigator.vibrate(2000);
				tizen.power.release('SCREEN');
			}
		} else {
			elem_outter.style.color = 'red';
			if (oldHeartRate <= 132.3) {
				// Vibrate won't work if the screen is off, so temporarily turn it on
				tizen.power.request('SCREEN', 'SCREEN_NORMAL');
				navigator.vibrate(2000);
				tizen.power.release('SCREEN');
			}
		}

		elem.textContent = hrmInfo.heartRate;
		lastHeartRate = hrmInfo.heartRate;
	} else if (hrmInfo.heartRate == -3){
		elem.textContent = 'OFF';
		elem_outter.style.color = '';
		lastHeartRate = 0;
	} else if (hrmInfo.heartRate == -2){
		elem.textContent = 'SHK';
		elem_outter.style.color = '';
		lastHeartRate = 0;
	}

	oldHeartRate = hrmInfo.heartRate;
}

function updatePedometer(pedometerInfo) {
	var elem = document.querySelector('#pedometer_level');
	var elem_outter = document.querySelector('#pedometer');

	if (pedometerInfo.stepStatus == 'WALKING') {
		elem_outter.style.color = 'lime';
		lastSpeed = pedometerInfo.speed;
	} else if (pedometerInfo.stepStatus == 'NOT_MOVING') {
		elem_outter.style.color = '';
		lastSpeed = 0;
	} else {
		elem_outter.style.color = 'yellow';
		lastSpeed = pedometerInfo.speed;
	}

	elem.textContent = pedometerInfo.speed;
}

function timerSwitched() {
	var checkbox = document.querySelector('#timerSwitch');
	if (checkbox.checked) {
		timerStartDate = new Date();
	} else {
		timerStartDate = undefined;
	}
}

function sportSwitched() {
	var elem = document.querySelector('#sport_chart');

	var checkbox = document.querySelector('#sportSwitch');
	if(checkbox.checked === true) {
		tizen.power.request('CPU', 'CPU_AWAKE');

		lastHeartRate = 0;
		lastSpeed = 0;

		sportChartMaxCount = 60 * 60 / 10; // number of seconds in an hour / 10
		sportChartCount = 60 * 60 / 10; // pretend like we've got a full count of points, because initial points is array of maxCount 0s

		var data = {
			    labels: Array.apply(null, new Array(sportChartMaxCount)).map(String.prototype.valueOf, ''),
			    labelsFilter: function (label) { return true },
			    datasets: [
			        {
			            label: 'HRM',
			            fillColor: 'rgba(220,220,220,0.2)',
			            strokeColor: "rgba(220,220,220,0.6)",
			            data: Array.apply(null, new Array(sportChartMaxCount)).map(Number.prototype.valueOf, 0),
			        },
			        {
			            label: 'Speed',
			            fillColor: 'rgba(151,187,205,0.2)',
			            strokeColor: "rgba(151,187,205,0.6)",
			            data: Array.apply(null, new Array(sportChartMaxCount)).map(Number.prototype.valueOf, 0),
			        }
			    ]
			};

		var options = {
				animation: false,
				responsive: false,
				maintainAspectRatio: false,
				showTooltips: false,
			    scaleShowGridLines : false,
			    scaleGridLineColor : 'rgba(0,0,0,.05)',
			    scaleGridLineWidth : 1,
			    scaleShowHorizontalLines: false,
			    scaleShowVerticalLines: false,
			    bezierCurve : false,
			    pointDot : false,
			    datasetStroke : true,
			    datasetStrokeWidth : 2,
			    datasetFill : true,
			};

		sportChart = new Chart(elem.getContext('2d')).Line(data, options);

		sportChartUpdater = setInterval(function() {
			while (sportChartCount >= sportChartMaxCount) {
				sportChart.removeData();
				sportChartCount--;
			}

			sportChart.addData([lastHeartRate, lastSpeed * 10], '');
			sportChartCount++;
		}, 10000); // call once every 10 seconds
	} else {
		tizen.power.release('CPU');

		sportChart.clear();
		sportChart.destroy();
		clearInterval(sportChartUpdater);
	}
}

function init() {
	battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

	document.addEventListener('visibilitychange', function() {
	    if (document.hidden) {
	    	deactivate();
	    } else {
	    	activate();
	    }
	}, false);

	activate();
}

function activate() {
	rssInit();

	updateTime();
	timeUpdateTimer = setInterval(updateTime, 500);

	if (document.querySelector('#sportSwitch').checked === false) {
		document.querySelector('#pedometer').style.color = '';
		document.querySelector('#pedometer_level').textContent = '-';
		document.querySelector('#heartrate').style.color = '';
		document.querySelector('#heartrate_level').textContent = '-';
		oldHeartRate = 0;
		hrmFailCount = 0;
		tizen.humanactivitymonitor.start('HRM', updateHeartRate);
		tizen.humanactivitymonitor.setAccumulativePedometerListener(updatePedometer);
	}

	document.querySelector('#battery').style.color = '';
	document.querySelector('#battery_level').textContent = '-';
	battery.addEventListener('levelchange', updateBatteryState);
	updateBatteryState();
}

function deactivate() {
	clearInterval(timeUpdateTimer);

	if (document.querySelector('#sportSwitch').checked === false) {
		tizen.humanactivitymonitor.stop('HRM');
		tizen.humanactivitymonitor.unsetAccumulativePedometerListener();
	}

	battery.removeEventListener('levelchange', updateBatteryState);
}
<|endoftext|>


<commit_before>/**
 * @author: Hans Christian Reinl
 * @date: 30.06.2013
 */

(function () {
	'use strict';

	var meetupsData;

	// Some helpers
	var Helper = {

		createElement: function (htmlString) {
			var fragment = document.createDocumentFragment();
			var temp = document.createElement('div');

			temp.innerHTML = htmlString;

			while (temp.firstChild) {
				fragment.appendChild(temp.firstChild);
			}

			return fragment;
		},

		// Content injection
		setContent: function (selector, content) {
			var fragment;
			var element = document.querySelector(selector);

			// Delete all content from content element
			element.innerHTML = '';

			// Create a fragment from the input
			fragment = Helper.createElement(content);

			// Append the content
			element.appendChild(fragment);
		}
	};

	// The loader
	var L = function () {
		var pathPrefix = 'content/';
		var fileSuffix = '.html';

		// Main loading function
		var _load = function (what, where, callback) {
			var file;

			// Initialize XHR
			var xhr = new XMLHttpRequest();

			var _ensureReadiness = function () {
				if (xhr.readyState < 4) {
					return;
				}

				if (xhr.status !== 200) {
					return;
				}

				// We're ok
				if (xhr.readyState === 4) {

					// If we want to create a new element
					if (where !== '') {
						Helper.setContent(where, xhr.responseText);
					}

					// Call a callback
					if (typeof callback === 'function') {
						callback.call(this, xhr.responseText);
					}
				}
			};

			// Correct file path
			if (what.indexOf('.') > -1) {
				fileSuffix = '';
			}

			file = pathPrefix + what + fileSuffix;

			// New XHR
			xhr.onreadystatechange = _ensureReadiness;
			xhr.open('GET', file, true);
			xhr.send();
		};

		// Public API
		return {
			load: _load
		};
	};

	// Class to website's functionality
	var D = function () {

		// Initialize Loader
		var Loader = new L();

		var _mainAction = 'index';
		var _allowedActions = ['index', 'teaser'];

		// Compiled templates
		var templates = {
			archive: Hogan.compile(document.getElementById('template-archive').innerHTML),
			single: Hogan.compile(document.getElementById('template-single').innerHTML)
		};

		// Inject script for twitter
		var _injectTwitterButton = function () {
			if (document.querySelector('.twitter-share-button')) {
				(function (d,s,id) {
					var js;
					var fjs = d.getElementsByTagName(s)[0];

					if (!d.getElementById(id)) {
						js = d.createElement(s);
						js.id = id;
						js.src = "//platform.twitter.com/widgets.js";
						fjs.parentNode.insertBefore(js, fjs);
					}
				}(document, 'script', 'twitter-wjs'));
			}
		};

		// Filter single view and return correct one if available
		var _findSingleMeetup = function (url) {
			var i = 0;
			for (; i < meetupsData.meetups.length; i++) {
				if (meetupsData.meetups[i].url === url) {
					return meetupsData.meetups[i];
				}
			}

			return undefined;
		};

		// Handler for meetup: either load single view or list
		var _handleMeetup = function (action, data) {
			var content;
			var single;

			action = action.split('/');

			if (action[1]) {
				single = _findSingleMeetup(action[1]);

				content = templates.single.render(single);
			} else {
				content = templates.archive.render(data);
			}

			Helper.setContent('.site-content', content);
		};

		var _mainHandler = function () {
			var action = window.location.hash.replace('#/', '');

			document.querySelector('.site-teaser').innerHTML = '';

			// Load index content
			if (action === '' || action === '!') {

				Loader.load(_mainAction, '.site-content', _injectTwitterButton);

				// And load teaser
				Loader.load('teaser', '.site-teaser');

				return;
			}

			// Otherwise load some other content
			if (_allowedActions.indexOf(action) > -1) {
				document.querySelector('.site-teaser').innerHTML = '';

				Loader.load(action, '.site-content');

				window.scrollTo(0);
			} else if (action.indexOf('meetup') > -1) {

				// Meetup data already available
				if (meetupsData) {
					_handleMeetup(action, meetupsData);

				// Load meetup data
				} else {
					Loader.load('meetups.json', '', function (data) {

						// Parse data
						data = JSON.parse(data);

						// Put data in a wrapper object
						data.meetups = data;

						// Set data globalls
						meetupsData = data;

						_handleMeetup(action, data);
					});
				}

				window.scrollTo(0);
			}
		};

		return {
			init: function () {

				// Initialize hash change events
				window.addEventListener('hashchange', _mainHandler, false);
				window.addEventListener('load', _mainHandler, false);
			}
		};

	};

	// Initialize all functionality
	var d = D();

	d.init();

}());

<commit_msg>Fix back button on overview<commit_after>/**
 * @author: Hans Christian Reinl
 * @date: 30.06.2013
 */

(function () {
	'use strict';

	var meetupsData;

	// Some helpers
	var Helper = {

		createElement: function (htmlString) {
			var fragment = document.createDocumentFragment();
			var temp = document.createElement('div');

			temp.innerHTML = htmlString;

			while (temp.firstChild) {
				fragment.appendChild(temp.firstChild);
			}

			return fragment;
		},

		// Content injection
		setContent: function (selector, content) {
			var fragment;
			var element = document.querySelector(selector);

			// Delete all content from content element
			element.innerHTML = '';

			// Create a fragment from the input
			fragment = Helper.createElement(content);

			// Append the content
			element.appendChild(fragment);
		}
	};

	// The loader
	var L = function () {

		// Main loading function
		var _load = function (what, where, callback) {
			var pathPrefix = 'content/';
			var fileSuffix = '.html';
			var file;

			// Initialize XHR
			var xhr = new XMLHttpRequest();

			var _ensureReadiness = function () {
				if (xhr.readyState < 4) {
					return;
				}

				if (xhr.status !== 200) {
					return;
				}

				// We're ok
				if (xhr.readyState === 4) {

					// If we want to create a new element
					if (where !== '') {
						Helper.setContent(where, xhr.responseText);
					}

					// Call a callback
					if (typeof callback === 'function') {
						callback.call(this, xhr.responseText);
					}
				}
			};

			// Correct file path
			if (what.indexOf('.') > -1) {
				fileSuffix = '';
			}

			file = pathPrefix + what + fileSuffix;

			// New XHR
			xhr.onreadystatechange = _ensureReadiness;
			xhr.open('GET', file, true);
			xhr.send();
		};

		// Public API
		return {
			load: _load
		};
	};

	// Class to website's functionality
	var D = function () {

		// Initialize Loader
		var Loader = new L();

		var _mainAction = 'index';
		var _allowedActions = ['index', 'teaser'];

		// Compiled templates
		var templates = {
			archive: Hogan.compile(document.getElementById('template-archive').innerHTML),
			single: Hogan.compile(document.getElementById('template-single').innerHTML)
		};

		// Inject script for twitter
		var _injectTwitterButton = function () {
			if (document.querySelector('.twitter-share-button')) {
				(function (d,s,id) {
					var js;
					var fjs = d.getElementsByTagName(s)[0];

					if (!d.getElementById(id)) {
						js = d.createElement(s);
						js.id = id;
						js.src = "//platform.twitter.com/widgets.js";
						fjs.parentNode.insertBefore(js, fjs);
					}
				}(document, 'script', 'twitter-wjs'));
			}
		};

		// Filter single view and return correct one if available
		var _findSingleMeetup = function (url) {
			var i = 0;
			for (; i < meetupsData.meetups.length; i++) {
				if (meetupsData.meetups[i].url === url) {
					return meetupsData.meetups[i];
				}
			}

			return undefined;
		};

		// Handler for meetup: either load single view or list
		var _handleMeetup = function (action, data) {
			var content;
			var single;

			action = action.split('/');

			if (action[1]) {
				single = _findSingleMeetup(action[1]);

				content = templates.single.render(single);
			} else {
				content = templates.archive.render(data);
			}

			Helper.setContent('.site-content', content);
		};

		var _mainHandler = function () {
			var action = window.location.hash.replace('#/', '');

			document.querySelector('.site-teaser').innerHTML = '';

			// Load index content
			if (action === '' || action === '!') {

				Loader.load(_mainAction, '.site-content', _injectTwitterButton);

				// And load teaser
				Loader.load('teaser', '.site-teaser');

				return;
			}

			// Otherwise load some other content
			if (_allowedActions.indexOf(action) > -1) {
				document.querySelector('.site-teaser').innerHTML = '';

				Loader.load(action, '.site-content');

				window.scrollTo(0);
			} else if (action.indexOf('meetup') > -1) {

				// Meetup data already available
				if (meetupsData) {
					_handleMeetup(action, meetupsData);

				// Load meetup data
				} else {
					Loader.load('meetups.json', '', function (data) {

						// Parse data
						data = JSON.parse(data);

						// Put data in a wrapper object
						data.meetups = data;

						// Set data globalls
						meetupsData = data;

						_handleMeetup(action, data);
					});
				}

				window.scrollTo(0);
			}
		};

		return {
			init: function () {

				// Initialize hash change events
				window.addEventListener('hashchange', _mainHandler, false);
				window.addEventListener('load', _mainHandler, false);
			}
		};

	};

	// Initialize all functionality
	var d = D();

	d.init();

}());

<|endoftext|>


<commit_before>$(function() {
    $('main').slideDown(300).animate({'opacity': 1}, {'queue': false, 'duration': 300});
    $('footer').fadeIn(1200);

    // get data stored in localStorage and display it on page load.
    var storageData = JSON.parse(localStorage.getItem("notes"));
    if (!$.isEmptyObject(storageData)) {
        var allNotes = '';
        for (var day in storageData) {
            var string = '
' + day + '';
            var note = '';
            for (var uid in storageData[day]) {
                var text = storageData[day][uid].note;
                var time = storageData[day][uid].time;
                var noteString = '' + text + '' + time + '';
                var wellWrapper = wrapNotes(noteString, uid);
                note += wellWrapper;
            }
            var dayNotes = string + note + '
';
            allNotes += dayNotes;
        }
        $('.panel-body').show();
        $('.user-notes').append(allNotes);
    }

    // enter button is 'add'
    $('#input-note').keypress(function(e) {
        if(e.which == 13) {
            $('#add-note-btn').trigger('click');
        }
    });

    // get the input and store it in localStorage
    $('#add-note-btn').click(function(e) {
        var inputVal = $('#input-note').val();
        if (inputVal) {
            if (typeof(localStorage) !== "undefined") {
                var notesStorage = localStorage.getItem("notes");
                var uniqueId = getRandomId();
                if (notesStorage) {
                    var data = JSON.parse(notesStorage);
                    updateLocalstorageData(inputVal, data, uniqueId);
                }
                else {
                    setLocalstorageData(inputVal, uniqueId);
                }
                appendNotes(inputVal, uniqueId);
                $('.panel-body').show();
            }
            else {
                $(".panel").effect("shake");
            }
            $('#input-note').val('').focus();
        }
        else {
            $('#input-note').effect("highlight", {color: '#ef9a9a'}, 500).focus();
        }
    });

    // delete functionality
    $('.user-notes').on('click', '.trash-icon', function() {
        var noteElement = $(this).closest('.notes-list');
        var thisElement = $(this);
        deleteNote(thisElement, noteElement);
    });

    // checked functionality
    $('.user-notes').on('click', '.check-icon', function() {
        var id = $(this).attr('id').substring(4);
        var day = $(this).closest('.notes-list').siblings('.day').text();
        var notesStorage = JSON.parse(localStorage.getItem("notes"));
        if ($(this).hasClass('fa-check-circle-o')) {
            $(this).closest('.well').animate({'background-color':'#f7f2c5'}, 300);
            $(this).addClass('fa-check-circle').removeClass('fa-check-circle-o');
            var timeStamp = $.now();
            notesStorage[day][id].checked = timeStamp;
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
        else {
            $(this).closest('.well').animate({'background-color':'white'}, 300);
            $(this).addClass('fa-check-circle-o').removeClass('fa-check-circle');
            delete notesStorage[day][id].checked;
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
    });

    // delete items which are checked for 5 minutes.
    setInterval(function() {
        var currentTime = $.now();
        var notesStorage = JSON.parse(localStorage.getItem("notes"));
        if (!$.isEmptyObject(notesStorage)) {
            for (var day in notesStorage) {
                for (var id in notesStorage[day]) {
                    if (notesStorage[day][id].hasOwnProperty('checked')) {
                        var checkedTime = notesStorage[day][id].checked;
                        if (((currentTime - checkedTime)/1000/60) >= 5) {
                            notesStorage = animateDelete(notesStorage, id, day, 'pulsate');
                        }
                    }
                }
            }
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
    }, 5000);
});

function appendNotes(note, uniqueId) {
    var datetime = getCurrentDatetime();
    note = '' + note + '' + datetime.time + '';
    var wellWrapper = wrapNotes(note, uniqueId);
    var day = datetime.day;
    var dayPresent = $('span:contains('+day+')');
    if (dayPresent.length == 1) {
        $(dayPresent).after(wellWrapper);
    }
    else {
        var noteBlock = '
' + day + '' + wellWrapper + '
';
        $('.user-notes').append(noteBlock);
    }
}

function wrapNotes(note, uniqueId) {
    if (isCheckedNote(uniqueId)) {
        return '
' + note + '
';
    }
    else {
        return '
' + note + '
';
    }
}

function setLocalStorageData(note, uniqueId) {
    datetime = getCurrentDatetime();
    var notesStorageData = {};
    notesStorageData[datetime.day] = {};
    notesStorageData[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
    localStorage.setItem("notes", JSON.stringify(notesStorageData));
}

function updateLocalstorageData(note, data, uniqueId) {
    datetime = getCurrentDatetime();
    if (data[datetime.day]) {
        data[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
        localStorage.setItem("notes", JSON.stringify(data));
    }
    else {
        data[datetime.day] = {};
        data[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
        localStorage.setItem("notes", JSON.stringify(data));
    }
}

function getCurrentDatetime() {
    var dt = new Date();
    var day = dt.toDateString();
    var hours = dt.getHours();
    var minutes = (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12 ? hours % 12 : 12;
    var time =  hours + ":" + minutes + ' ' + ampm;
    return {day: day, time: time};
}

function deleteNote(element, noteElement) {
    var id = $(element).attr('id').substring(4);
    var day = $(noteElement).siblings('.day').text();
    var notesStorage = JSON.parse(localStorage.getItem("notes"));
    notesStorage = animateDelete(notesStorage, id, day, 'drop');
    localStorage.setItem("notes", JSON.stringify(notesStorage));
}

function getRandomId() {
    return (Math.random() + 1).toString(16).substring(2,7);
}

function isCheckedNote(uid) {
    var notesStorage = JSON.parse(localStorage.getItem("notes"));
    for (var day in notesStorage) {
        for (var id in notesStorage[day]) {
            if (id == uid) {
                if (notesStorage[day][id].hasOwnProperty('checked')) {
                    return true;
                }
            }
        }
    }
    return false;
}

function animateDelete(notesStorage, id, day, effectType) {
    delete notesStorage[day][id];
    if ($.isEmptyObject(notesStorage[day])) {
        delete notesStorage[day];
        var noteSection = $('span:contains('+day+')');
        $(noteSection).parent().effect(effectType, function() {
            $(this).remove();
        });
        if ($.isEmptyObject(notesStorage)) {
            $('.panel-body').hide(300);
        }
    }
    else {
        $('#del-'+id).closest('.notes-list').effect(effectType, function() {
            $(this).remove();
        });
    }
    return notesStorage;
}<commit_msg>typo fix<commit_after>$(function() {
    $('main').slideDown(300).animate({'opacity': 1}, {'queue': false, 'duration': 300});
    $('footer').fadeIn(1200);

    // get data stored in localStorage and display it on page load.
    var storageData = JSON.parse(localStorage.getItem("notes"));
    if (!$.isEmptyObject(storageData)) {
        var allNotes = '';
        for (var day in storageData) {
            var string = '
' + day + '';
            var note = '';
            for (var uid in storageData[day]) {
                var text = storageData[day][uid].note;
                var time = storageData[day][uid].time;
                var noteString = '' + text + '' + time + '';
                var wellWrapper = wrapNotes(noteString, uid);
                note += wellWrapper;
            }
            var dayNotes = string + note + '
';
            allNotes += dayNotes;
        }
        $('.panel-body').show();
        $('.user-notes').append(allNotes);
    }

    // enter button is 'add'
    $('#input-note').keypress(function(e) {
        if(e.which == 13) {
            $('#add-note-btn').trigger('click');
        }
    });

    // get the input and store it in localStorage
    $('#add-note-btn').click(function(e) {
        var inputVal = $('#input-note').val();
        if (inputVal) {
            if (typeof(localStorage) !== "undefined") {
                var notesStorage = localStorage.getItem("notes");
                var uniqueId = getRandomId();
                if (notesStorage) {
                    var data = JSON.parse(notesStorage);
                    updateLocalstorageData(inputVal, data, uniqueId);
                }
                else {
                    setLocalstorageData(inputVal, uniqueId);
                }
                appendNotes(inputVal, uniqueId);
                $('.panel-body').show();
            }
            else {
                $(".panel").effect("shake");
            }
            $('#input-note').val('').focus();
        }
        else {
            $('#input-note').effect("highlight", {color: '#ef9a9a'}, 500).focus();
        }
    });

    // delete functionality
    $('.user-notes').on('click', '.trash-icon', function() {
        var noteElement = $(this).closest('.notes-list');
        var thisElement = $(this);
        deleteNote(thisElement, noteElement);
    });

    // checked functionality
    $('.user-notes').on('click', '.check-icon', function() {
        var id = $(this).attr('id').substring(4);
        var day = $(this).closest('.notes-list').siblings('.day').text();
        var notesStorage = JSON.parse(localStorage.getItem("notes"));
        if ($(this).hasClass('fa-check-circle-o')) {
            $(this).closest('.well').animate({'background-color':'#f7f2c5'}, 300);
            $(this).addClass('fa-check-circle').removeClass('fa-check-circle-o');
            var timeStamp = $.now();
            notesStorage[day][id].checked = timeStamp;
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
        else {
            $(this).closest('.well').animate({'background-color':'white'}, 300);
            $(this).addClass('fa-check-circle-o').removeClass('fa-check-circle');
            delete notesStorage[day][id].checked;
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
    });

    // delete items which are checked for 5 minutes.
    setInterval(function() {
        var currentTime = $.now();
        var notesStorage = JSON.parse(localStorage.getItem("notes"));
        if (!$.isEmptyObject(notesStorage)) {
            for (var day in notesStorage) {
                for (var id in notesStorage[day]) {
                    if (notesStorage[day][id].hasOwnProperty('checked')) {
                        var checkedTime = notesStorage[day][id].checked;
                        if (((currentTime - checkedTime)/1000/60) >= 5) {
                            notesStorage = animateDelete(notesStorage, id, day, 'pulsate');
                        }
                    }
                }
            }
            localStorage.setItem("notes", JSON.stringify(notesStorage));
        }
    }, 5000);
});

function appendNotes(note, uniqueId) {
    var datetime = getCurrentDatetime();
    note = '' + note + '' + datetime.time + '';
    var wellWrapper = wrapNotes(note, uniqueId);
    var day = datetime.day;
    var dayPresent = $('span:contains('+day+')');
    if (dayPresent.length == 1) {
        $(dayPresent).after(wellWrapper);
    }
    else {
        var noteBlock = '
' + day + '' + wellWrapper + '
';
        $('.user-notes').append(noteBlock);
    }
}

function wrapNotes(note, uniqueId) {
    if (isCheckedNote(uniqueId)) {
        return '
' + note + '
';
    }
    else {
        return '
' + note + '
';
    }
}

function setLocalstorageData(note, uniqueId) {
    datetime = getCurrentDatetime();
    var notesStorageData = {};
    notesStorageData[datetime.day] = {};
    notesStorageData[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
    localStorage.setItem("notes", JSON.stringify(notesStorageData));
}

function updateLocalstorageData(note, data, uniqueId) {
    datetime = getCurrentDatetime();
    if (data[datetime.day]) {
        data[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
        localStorage.setItem("notes", JSON.stringify(data));
    }
    else {
        data[datetime.day] = {};
        data[datetime.day][uniqueId] = {'note': note, 'time': datetime.time};
        localStorage.setItem("notes", JSON.stringify(data));
    }
}

function getCurrentDatetime() {
    var dt = new Date();
    var day = dt.toDateString();
    var hours = dt.getHours();
    var minutes = (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12 ? hours % 12 : 12;
    var time =  hours + ":" + minutes + ' ' + ampm;
    return {day: day, time: time};
}

function deleteNote(element, noteElement) {
    var id = $(element).attr('id').substring(4);
    var day = $(noteElement).siblings('.day').text();
    var notesStorage = JSON.parse(localStorage.getItem("notes"));
    notesStorage = animateDelete(notesStorage, id, day, 'drop');
    localStorage.setItem("notes", JSON.stringify(notesStorage));
}

function getRandomId() {
    return (Math.random() + 1).toString(16).substring(2,7);
}

function isCheckedNote(uid) {
    var notesStorage = JSON.parse(localStorage.getItem("notes"));
    for (var day in notesStorage) {
        for (var id in notesStorage[day]) {
            if (id == uid) {
                if (notesStorage[day][id].hasOwnProperty('checked')) {
                    return true;
                }
            }
        }
    }
    return false;
}

function animateDelete(notesStorage, id, day, effectType) {
    delete notesStorage[day][id];
    if ($.isEmptyObject(notesStorage[day])) {
        delete notesStorage[day];
        var noteSection = $('span:contains('+day+')');
        $(noteSection).parent().effect(effectType, function() {
            $(this).remove();
        });
        if ($.isEmptyObject(notesStorage)) {
            $('.panel-body').hide(300);
        }
    }
    else {
        $('#del-'+id).closest('.notes-list').effect(effectType, function() {
            $(this).remove();
        });
    }
    return notesStorage;
}
<|endoftext|>


<commit_before>window.onload = function(){

	//initialize portfolio
	var myApp = new portfolio_app('developer');
	myApp.initialize();

	//start router
	myApp.initRouter();
	//var router = new ApplicationRouter($('.body-wrap'), routeConfig);
	//	Backbone.history.start();

}

/* Main Portfolio App  ---------------------------------------------------------------------------------*/
var portfolio_app = function(mode){

	var current_work_index;

	//INITIALIZE PORTFOLIO APP
	function initialize(){

		//sets all needed components, listeners, etc
		setScrollListeners();
		//setSmoothScrolling();
		setMobileMenuListener();
	}

	/*----------------------------------------------------------------------
	// initRouter: instantiates and starts backbone router
	/---------------------------------------------------------------------*/
	function initRouter (){
		var router = new ApplicationRouter($('.body-wrap'), routeConfig);
		Backbone.history.start({root:'/'});
	}

	/*----------------------------------------------------------------------
	// fomartBodyPages: sets basic structure for all body pages
	/---------------------------------------------------------------------*/
	function setScrollListeners(){
		//when scrolling off about
		var distance = $('.body-main-header').height();
		$(window).scroll(function(){
		    if( $(window).scrollTop() >= distance ){
		        $('.body-main-header').addClass('scrolled');
		    }
		    else{
		    	$('.body-main-header').removeClass('scrolled');
		    }
		})

		/*
		//when scroll to work section
		var done = false;
		$(window).scroll(function(){
		    if( $(window).scrollTop() >= $('#work').offset().top - 100){
		    	if(!done){
			    	//window.location.hash ='work';
			        $('.work-piece').each(function(i){
			        	$(this).delay(100*i).fadeIn(180);
			        })
			        done = true;
		    	}
		    }
		}) */

	}

	function setSmoothScrolling() {
		$('.nav-links li a, .nav-logo, .more-link').click(function() {
		      var target = $(this.hash);
		      if (target.length) {
		        $('html,body').animate({
		          scrollTop: target.offset().top
		        }, 500);
		        return false;
		      }

		});
	}

	function setMobileMenuListener(){
		$('.mobile-header-container .menu-btn').click(function(){
			var toggle = $(this).data('toggle')||0
			switch(toggle){
				case 0:
					$(this).addClass('clicked');
					$('.mobile-header-container .nav-links').removeClass('closed');
					$('.mobile-header-container .nav-links').show();
					break;
				case 1:
					$(this).removeClass('clicked');
					$('.mobile-header-container .nav-links').addClass('closed');
					$('.mobile-header-container .nav-links').delay(100).fadeOut(100);
					break;
			}
			toggle ++;
			if(toggle > 1) toggle = 0;
			$(this).data('toggle', toggle);
		});

		//close mobile nav when a link is clicked
		$('.mobile-header-container .nav-links li a').click(function(){
			$('.mobile-header-container .menu-btn').data('toggle',0);
			$('.mobile-header-container .menu-btn').removeClass('clicked');
			$('.mobile-header-container .nav-links').addClass('closed');
			$('.mobile-header-container .nav-links').delay(100).fadeOut(100);
		})

	}

	return{
		initialize: initialize,
		initRouter: initRouter,
	}

};<commit_msg>testing<commit_after>window.onload = function(){

	//initialize portfolio
	var myApp = new portfolio_app('developer');
	myApp.initialize();

	//start router
	myApp.initRouter();
	//var router = new ApplicationRouter($('.body-wrap'), routeConfig);
	//	Backbone.history.start();

}

/* Main Portfolio App  ---------------------------------------------------------------------------------*/
var portfolio_app = function(mode){

	var current_work_index;

	//INITIALIZE PORTFOLIO APP
	function initialize(){

		//sets all needed components, listeners, etc
		setScrollListeners();
		//setSmoothScrolling();
		setMobileMenuListener();
	}

	/*----------------------------------------------------------------------
	// initRouter: instantiates and starts backbone router
	/---------------------------------------------------------------------*/
	function initRouter (){
		var router = new ApplicationRouter($('.body-wrap'), routeConfig);
		Backbone.history.start({});
	}

	/*----------------------------------------------------------------------
	// fomartBodyPages: sets basic structure for all body pages
	/---------------------------------------------------------------------*/
	function setScrollListeners(){
		//when scrolling off about
		var distance = $('.body-main-header').height();
		$(window).scroll(function(){
		    if( $(window).scrollTop() >= distance ){
		        $('.body-main-header').addClass('scrolled');
		    }
		    else{
		    	$('.body-main-header').removeClass('scrolled');
		    }
		})

		/*
		//when scroll to work section
		var done = false;
		$(window).scroll(function(){
		    if( $(window).scrollTop() >= $('#work').offset().top - 100){
		    	if(!done){
			    	//window.location.hash ='work';
			        $('.work-piece').each(function(i){
			        	$(this).delay(100*i).fadeIn(180);
			        })
			        done = true;
		    	}
		    }
		}) */

	}

	function setSmoothScrolling() {
		$('.nav-links li a, .nav-logo, .more-link').click(function() {
		      var target = $(this.hash);
		      if (target.length) {
		        $('html,body').animate({
		          scrollTop: target.offset().top
		        }, 500);
		        return false;
		      }

		});
	}

	function setMobileMenuListener(){
		$('.mobile-header-container .menu-btn').click(function(){
			var toggle = $(this).data('toggle')||0
			switch(toggle){
				case 0:
					$(this).addClass('clicked');
					$('.mobile-header-container .nav-links').removeClass('closed');
					$('.mobile-header-container .nav-links').show();
					break;
				case 1:
					$(this).removeClass('clicked');
					$('.mobile-header-container .nav-links').addClass('closed');
					$('.mobile-header-container .nav-links').delay(100).fadeOut(100);
					break;
			}
			toggle ++;
			if(toggle > 1) toggle = 0;
			$(this).data('toggle', toggle);
		});

		//close mobile nav when a link is clicked
		$('.mobile-header-container .nav-links li a').click(function(){
			$('.mobile-header-container .menu-btn').data('toggle',0);
			$('.mobile-header-container .menu-btn').removeClass('clicked');
			$('.mobile-header-container .nav-links').addClass('closed');
			$('.mobile-header-container .nav-links').delay(100).fadeOut(100);
		})

	}

	return{
		initialize: initialize,
		initRouter: initRouter,
	}

};<|endoftext|>


<commit_before>var gl;
var triangleVertexPositionBuffer;
var triangleVertexColorBuffer;
var cubeVertexPositionBuffer;
var cubeVertexColorBuffer;
var cubeVertexIndexBuffer;
var cubeVertexTextureCoordBuffer;
var mvMatrix = mat4.create();
var mvMatrixStack = [];
var pMatrix = mat4.create();
var rTri = 0;
var rCube = 0;
var shaderProgram;
var dogeTexture;
var currentlyPressedKeys = {};

// utils
function mvPushMatrix() {
  var copy = mat4.clone(mvMatrix);
  mvMatrixStack.push(copy);
}

function mvPopMatrix() {
  if (mvMatrixStack.length === 0) {
    throw "Invalid popMatrix";
  }
  mvMatrix = mvMatrixStack.pop();
}

function degToRad(degrees) {
  return degrees * Math.PI / 180;
}

function handleKeyDown(event) {
  // maintain key status
  currentlyPressedKeys[event.keyCode] = true;

  // handle keys once
}

function handleKeyUp(event) {
  currentlyPressedKeys[event.keyCode] = false;
}

function webGLStart() {
  var canvas = document.getElementById("main-frame");
  initGL(canvas);
  initShaders();
  initBuffers();
  initTexture();

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);

  document.onkeydown = handleKeyDown;
  document.onkeyup = handleKeyUp;

  tick();
}

function tick() {
  window.requestAnimationFrame(tick);
  handleKeys();
  drawScene();
  animate();
}

function handleKeys() {
  // handle keys per tick
}

var lastTime = 0;
function animate() {
  var timeNow = new Date().getTime();
  if (lastTime != 0) {
    var elapsed = new Date().getTime();
    rTri += 1;
    rCube += 1;
  }
  lastTime = timeNow;
}

function initTexture() {
  dogeTexture = gl.createTexture();
  dogeTexture.image = new Image();
  dogeTexture.image.onload = function() {
    handleLoadedTexture(dogeTexture);
  }

  dogeTexture.image.src = "img/doge.png";
}

function handleLoadedTexture(texture) {
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, texture.image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function initGL(canvas) {
  try {
    gl = canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
    alert("not support webGL!");
  }

  if (!gl) {
    alert("cannot load WebGL.");
  }
}

function initShaders() {
  var fragmentShader = getShader(gl, "shader-fs");
  var vertexShader = getShader(gl, "shader-vs");

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert("cannot init shaders.");
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
  gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);

  //shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
  //gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
  shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
}

function getShader(gl, id) {
  var shaderScript = document.getElementById(id);
  if (!shaderScript)
    return null;

  var str = "";
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType === 3)
      str += k.textContent;
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type === "x-shader/x-fragment") {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  } else if (shaderScript.type === "x-shader/x-vertex") {
    shader = gl.createShader(gl.VERTEX_SHADER);
  } else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initBuffers() {
  /*
   * Triangle
   */

  /*
  // position
  triangleVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
  var vertices = [
     0.0,  1.0,  0.0,
    -1.0, -1.0,  0.0,
     1.0, -1.0,  0.0
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  triangleVertexPositionBuffer.itemSize = 3;
  triangleVertexPositionBuffer.numItems = 3;

  // color
  triangleVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
  var colors = [
    1.0, 0.0, 0.0, 1.0,
    0.0, 1.0, 0.0, 1.0,
    0.0, 0.0, 1.0, 1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
  triangleVertexColorBuffer.itemSize = 4;
  triangleVertexColorBuffer.numItems = 3;
  */

  /*
   * Cube
   */

  // position
  cubeVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
  vertices = [
    // Front
    -1.0, -1.0, 1.0,
    1.0, -1.0, 1.0,
    1.0, 1.0, 1.0,
    -1.0, 1.0, 1.0,

    // Back
    -1.0, -1.0, -1.0,
    -1.0, 1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, -1.0, -1.0,

    // Top
    -1.0, 1.0, -1.0,
    -1.0, 1.0, 1.0,
    1.0, 1.0, 1.0,
    1.0, 1.0, -1.0,

    // Bottom
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    1.0, -1.0, 1.0,
    -1.0, -1.0, 1.0,

    // Right
    1.0, -1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, 1.0, 1.0,
    1.0, -1.0, 1.0,

    // Left
    -1.0, -1.0, -1.0,
    -1.0, -1.0, 1.0,
    -1.0, 1.0, 1.0,
    -1.0, 1.0, -1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  cubeVertexPositionBuffer.itemSize = 3;
  cubeVertexPositionBuffer.numItems = 24;

  // color
  /*
  cubeVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
  colors = [
    [1.0, 0.0, 0.0, 1.0],
    [1.0, 1.0, 0.0, 1.0],
    [1.0, 0.0, 1.0, 1.0],
    [1.0, 0.5, 0.0, 1.0],
    [1.0, 0.0, 0.5, 1.0],
    [0.5, 0.0, 0.0, 1.0],
  ];
  var unpackedColors = colors.reduce(function(prev, color) {
    return prev.concat(color);
  });
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(unpackedColors), gl.STATIC_DRAW);
  cubeVertexColorBuffer.itemSize = 4;
  cubeVertexColorBuffer.numItems = 24;
  */

  // index
  cubeVertexIndexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
  var cubeVertexIndices = [
    0, 1, 2,    0, 2, 3,
    4, 5, 6,    4, 6, 7,
    8, 9, 10,   8, 10, 11,
    12, 13, 14, 12, 14, 15,
    16, 17, 18, 16, 18, 19,
    20, 21, 22, 20, 22, 23
  ];
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
  cubeVertexIndexBuffer.itemSize = 1;
  cubeVertexIndexBuffer.numItems = 36;

  // texture
  cubeVertexTextureCoordBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
  var textureCoords = [
    // Front
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,

    // Back
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,

    // Top
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,

    // Bottom
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,

    // Right
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,

    // Left
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW);
  cubeVertexTextureCoordBuffer.itemSize = 2;
  cubeVertexTextureCoordBuffer.numItems = 24;
}

function setMatrixUniforms() {
  gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
  gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
}

function drawScene() {
  gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  mat4.perspective(pMatrix, 45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
  mat4.identity(mvMatrix);

  /*
   * Tranigle
   */
  /*
  mat4.translate(mvMatrix, mvMatrix, [-1.5, 0.0, -7.0]);

  mvPushMatrix();
  mat4.rotateY(mvMatrix, mvMatrix, degToRad(rTri));

  // draw triangle
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

  // draw color
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

  setMatrixUniforms();
  gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);

  mvPopMatrix();
  */

  /*
   * Cube
   */
  mat4.translate(mvMatrix, mvMatrix, [0.0, 0.0, -5.0]);

  mvPushMatrix();
  mat4.rotate(mvMatrix, mvMatrix, degToRad(rCube), vec3.fromValues(1, 1, 1));
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
  /*
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, cubeVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
  */
  // texture
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
  gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, cubeVertexTextureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);
  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, dogeTexture);
  gl.uniform1i(shaderProgram.samplerUniform, 0);

  // index
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
  setMatrixUniforms();
  gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

  mvPopMatrix();
}

window.onload = webGLStart;

<commit_msg>Add lighting<commit_after>var gl;
var triangleVertexPositionBuffer;
var triangleVertexColorBuffer;
var cubeVertexPositionBuffer;
var cubeVertexColorBuffer;
var cubeVertexIndexBuffer;
var cubeVertexTextureCoordBuffer;
var cubeVertexNormalBuffer;
var mvMatrix = mat4.create();
var mvMatrixStack = [];
var pMatrix = mat4.create();
var rTri = 0;
var rCube = 0;
var shaderProgram;
var dogeTexture;
var currentlyPressedKeys = {};

// utils
function mvPushMatrix() {
  var copy = mat4.clone(mvMatrix);
  mvMatrixStack.push(copy);
}

function mvPopMatrix() {
  if (mvMatrixStack.length === 0) {
    throw "Invalid popMatrix";
  }
  mvMatrix = mvMatrixStack.pop();
}

function degToRad(degrees) {
  return degrees * Math.PI / 180;
}

function handleKeyDown(event) {
  // maintain key status
  currentlyPressedKeys[event.keyCode] = true;

  // handle keys once
}

function handleKeyUp(event) {
  currentlyPressedKeys[event.keyCode] = false;
}

function webGLStart() {
  var canvas = document.getElementById("main-frame");
  initGL(canvas);
  initShaders();
  initBuffers();
  initTexture();

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.enable(gl.DEPTH_TEST);

  document.onkeydown = handleKeyDown;
  document.onkeyup = handleKeyUp;

  tick();
}

function tick() {
  window.requestAnimationFrame(tick);
  handleKeys();
  drawScene();
  animate();
}

function handleKeys() {
  // handle keys per tick
}

var lastTime = 0;
function animate() {
  var timeNow = new Date().getTime();
  if (lastTime != 0) {
    var elapsed = new Date().getTime();
    rTri += 1;
    rCube += 1;
  }
  lastTime = timeNow;
}

function initTexture() {
  dogeTexture = gl.createTexture();
  dogeTexture.image = new Image();
  dogeTexture.image.onload = function() {
    handleLoadedTexture(dogeTexture);
  }

  dogeTexture.image.src = "img/doge.png";
}

function handleLoadedTexture(texture) {
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function initGL(canvas) {
  try {
    gl = canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
  } catch(e) {
    alert("not support webGL!");
  }

  if (!gl) {
    alert("cannot load WebGL.");
  }
}

function initShaders() {
  var fragmentShader = getShader(gl, "shader-fs");
  var vertexShader = getShader(gl, "shader-vs");

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert("cannot init shaders.");
  }

  gl.useProgram(shaderProgram);

  shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
  gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

  shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, "aVertexNormal");
  gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);

  shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");
  gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);

  //shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
  //gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

  shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
  shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
  shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, "uNMatrix");
  shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler");
  shaderProgram.useLightingUniform = gl.getUniformLocation(shaderProgram, "uUseLighting");
  shaderProgram.ambientColorUniform = gl.getUniformLocation(shaderProgram, "uAmbientColor");
  shaderProgram.lightingDirectionUniform = gl.getUniformLocation(shaderProgram, "uLightingDirection");
  shaderProgram.directionalColorUniform = gl.getUniformLocation(shaderProgram, "uDirectionalColor");
}

function getShader(gl, id) {
  var shaderScript = document.getElementById(id);
  if (!shaderScript)
    return null;

  var str = "";
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType === 3)
      str += k.textContent;
    k = k.nextSibling;
  }

  var shader;
  if (shaderScript.type === "x-shader/x-fragment") {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  } else if (shaderScript.type === "x-shader/x-vertex") {
    shader = gl.createShader(gl.VERTEX_SHADER);
  } else {
    return null;
  }

  gl.shaderSource(shader, str);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert(gl.getShaderInfoLog(shader));
    return null;
  }

  return shader;
}

function initBuffers() {
  /*
   * Triangle
   */

  /*
  // position
  triangleVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
  var vertices = [
     0.0,  1.0,  0.0,
    -1.0, -1.0,  0.0,
     1.0, -1.0,  0.0
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  triangleVertexPositionBuffer.itemSize = 3;
  triangleVertexPositionBuffer.numItems = 3;

  // color
  triangleVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
  var colors = [
    1.0, 0.0, 0.0, 1.0,
    0.0, 1.0, 0.0, 1.0,
    0.0, 0.0, 1.0, 1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
  triangleVertexColorBuffer.itemSize = 4;
  triangleVertexColorBuffer.numItems = 3;
  */

  /*
   * Cube
   */

  // position
  cubeVertexPositionBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
  vertices = [
    // Front
    -1.0, -1.0, 1.0,
    1.0, -1.0, 1.0,
    1.0, 1.0, 1.0,
    -1.0, 1.0, 1.0,

    // Back
    -1.0, -1.0, -1.0,
    -1.0, 1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, -1.0, -1.0,

    // Top
    -1.0, 1.0, -1.0,
    -1.0, 1.0, 1.0,
    1.0, 1.0, 1.0,
    1.0, 1.0, -1.0,

    // Bottom
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    1.0, -1.0, 1.0,
    -1.0, -1.0, 1.0,

    // Right
    1.0, -1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, 1.0, 1.0,
    1.0, -1.0, 1.0,

    // Left
    -1.0, -1.0, -1.0,
    -1.0, -1.0, 1.0,
    -1.0, 1.0, 1.0,
    -1.0, 1.0, -1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  cubeVertexPositionBuffer.itemSize = 3;
  cubeVertexPositionBuffer.numItems = 24;

  // color
  /*
  cubeVertexColorBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
  colors = [
    [1.0, 0.0, 0.0, 1.0],
    [1.0, 1.0, 0.0, 1.0],
    [1.0, 0.0, 1.0, 1.0],
    [1.0, 0.5, 0.0, 1.0],
    [1.0, 0.0, 0.5, 1.0],
    [0.5, 0.0, 0.0, 1.0],
  ];
  var unpackedColors = colors.reduce(function(prev, color) {
    return prev.concat(color);
  });
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(unpackedColors), gl.STATIC_DRAW);
  cubeVertexColorBuffer.itemSize = 4;
  cubeVertexColorBuffer.numItems = 24;
  */

  // index
  cubeVertexIndexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
  var cubeVertexIndices = [
    0, 1, 2,    0, 2, 3,
    4, 5, 6,    4, 6, 7,
    8, 9, 10,   8, 10, 11,
    12, 13, 14, 12, 14, 15,
    16, 17, 18, 16, 18, 19,
    20, 21, 22, 20, 22, 23
  ];
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(cubeVertexIndices), gl.STATIC_DRAW);
  cubeVertexIndexBuffer.itemSize = 1;
  cubeVertexIndexBuffer.numItems = 36;

  // texture
  cubeVertexTextureCoordBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
  var textureCoords = [
    // Front
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,

    // Back
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,

    // Top
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,

    // Bottom
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,
    1.0, 0.0,

    // Right
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
    0.0, 0.0,

    // Left
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,
    0.0, 1.0,
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(textureCoords), gl.STATIC_DRAW);
  cubeVertexTextureCoordBuffer.itemSize = 2;
  cubeVertexTextureCoordBuffer.numItems = 24;

  // normal
  cubeVertexNormalBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexNormalBuffer);
  var vertexNormals = [
    // Front
    0.0, 0.0, 1.0,
    0.0, 0.0, 1.0,
    0.0, 0.0, 1.0,
    0.0, 0.0, 1.0,

    // Back
    0.0, 0.0, -1.0,
    0.0, 0.0, -1.0,
    0.0, 0.0, -1.0,
    0.0, 0.0, -1.0,

    // Top
    0.0, 1.0, 0.0,
    0.0, 1.0, 0.0,
    0.0, 1.0, 0.0,
    0.0, 1.0, 0.0,

    // Bottom
    0.0, -1.0, 0.0,
    0.0, -1.0, 0.0,
    0.0, -1.0, 0.0,
    0.0, -1.0, 0.0,

    // Right
    1.0, 0.0, 0.0,
    1.0, 0.0, 0.0,
    1.0, 0.0, 0.0,
    1.0, 0.0, 0.0,

    // Left
    -1.0, 0.0, 0.0,
    -1.0, 0.0, 0.0,
    -1.0, 0.0, 0.0,
    -1.0, 0.0, 0.0
  ];
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexNormals), gl.STATIC_DRAW);
  cubeVertexNormalBuffer.itemSize = 3;
  cubeVertexNormalBuffer.numItems = 24;
}

function setMatrixUniforms() {
  gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
  gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);

  var normalMatrix = mat3.create();
  mat3.normalFromMat4(normalMatrix, mvMatrix);
  gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, normalMatrix);
}

function drawScene() {
  gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  mat4.perspective(pMatrix, 45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0);
  mat4.identity(mvMatrix);

  /*
   * Tranigle
   */
  /*
  mat4.translate(mvMatrix, mvMatrix, [-1.5, 0.0, -7.0]);

  mvPushMatrix();
  mat4.rotateY(mvMatrix, mvMatrix, degToRad(rTri));

  // draw triangle
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

  // draw color
  gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, triangleVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);

  setMatrixUniforms();
  gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);

  mvPopMatrix();
  */

  /*
   * Cube
   */
  mat4.translate(mvMatrix, mvMatrix, [0.0, 0.0, -5.0]);

  mvPushMatrix();
  mat4.rotate(mvMatrix, mvMatrix, degToRad(rCube), vec3.fromValues(1, 1, 1));
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexPositionBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
  /*
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexColorBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, cubeVertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0);
  */

  // normal
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexNormalBuffer);
  gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute, cubeVertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);

  // texture
  gl.bindBuffer(gl.ARRAY_BUFFER, cubeVertexTextureCoordBuffer);
  gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, cubeVertexTextureCoordBuffer.itemSize, gl.FLOAT, false, 0, 0);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, dogeTexture);
  gl.uniform1i(shaderProgram.samplerUniform, 0);

  // always use lighting, for now
  // maybe use a key to toggle in the future
  var lighting = true;
  gl.uniform1i(shaderProgram.useLightingUniform, lighting);
  if (lighting) {
    // use white light as default
    gl.uniform3f(shaderProgram.ambientColorUniform, 0.2, 0.2, 0.2);

    var lightingDirection = [0.0, 0.0, -0.8];
    var adjustedLD = vec3.create();
    // scale its length to one
    vec3.normalize(adjustedLD, lightingDirection);
    vec3.scale(adjustedLD, adjustedLD, -1);
    gl.uniform3fv(shaderProgram.lightingDirectionUniform, adjustedLD);
    gl.uniform3f(shaderProgram.directionalColorUniform, 1.0, 1.0, 1.0);
  }

  // index
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
  setMatrixUniforms();
  gl.drawElements(gl.TRIANGLES, cubeVertexIndexBuffer.numItems, gl.UNSIGNED_SHORT, 0);

  mvPopMatrix();
}

window.onload = webGLStart;

<|endoftext|>


<commit_before>"use strict";
var inceptionHost = inceptionHost || {};
inceptionHost.sub = (function() {
    var command,type,target,resource;
    var url = new URL(location);

    command = url.searchParams.get("command");
    type = url.searchParams.get("type");
    target = url.searchParams.get("target");
    resource = getHashPayload(location);

    if(!resource){
        init();
    }
    else
    {
        if(!command){
            command = "create";
            target = "hyperlink";
        }
        main();
    }

    function init(){
        var quill = new Quill('#editor-container', {
          modules: {
            syntax: true,
            toolbar: false
          },
          placeholder: 'type or paste html code here...'
          //theme: 'bubble'  // or 'snow'
        });
        document.getElementsByClassName("ql-editor")[0].innerHTML="

"

        function onPublish() {
            var myLink = document.getElementById('mylink');
            var html = quill.getText();
            myLink.onclick = function(){
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = "./js/main.js";
                document.getElementsByTagName("head")[0].appendChild(script);
                document.location.hash=serialize(html.replace(/"/g, "'"));
                return false;
            }
            document.getElementById('mylink').click();
        }
        document.getElementById("btnPublish").addEventListener("click", onPublish);

    }
    function main(){
        if(command === "create"){
            createHyperlink(resource);
        }
        else if(command === "load"){
            var deserializedPayload = deserialize(resource);
            loadHyperlink(deserializedPayload);
        }
    }

    function createHyperlink(){
        //change the command to load so the hyperlink instructs the api to load the resource
        command = "load";
        url.searchParams.set("command",command);
        url.searchParams.delete("source");
        url.searchParams.delete("target");
        url.searchParams.delete("resource");
        url.hash = "";
        var hyperlink = url.href + "#?" + resource;
        if(target === 'newWindow'){
            document.location=hyperlink;
        }
        else if(target === 'hyperlink'){
            document.body.innerHTML = "" + "Inception. It is possible." + "";
        }
    }

    function loadHyperlink(deserializedPayload){
        document.body.innerHTML=deserializedPayload;
    }

    function getHashPayload(url) {
        // read the hash
        var hash = url.hash
          , dataPos
          , payload
          ;
        if(hash)
            // remove hashtag
            hash = hash.slice(1);
        if(!hash)
            return false;

        dataPos = hash.indexOf("?") + 1;
        if(dataPos === -1)
            return false;

        return hash.slice(dataPos);
    }

    function serialize(data) {
        return btoa(pako.deflate( JSON.stringify(data), { to: 'string' }));
    }

    function deserialize(payload) {
        if(type=="data"){
            return "
" + pako.inflate( atob(payload), { to: 'string' }) + "
";
        }
        else{
            return JSON.parse( pako.inflate( atob(payload), { to: 'string' }));
        }
    }

})();<commit_msg>adding back type<commit_after>"use strict";
var inceptionHost = inceptionHost || {};
inceptionHost.sub = (function() {
    var command,type,target,resource;
    var url = new URL(location);

    command = url.searchParams.get("command");
    type = url.searchParams.get("type");
    target = url.searchParams.get("target");
    resource = getHashPayload(location);

    if(!resource){
        init();
    }
    else
    {
        if(!command){
            command = "create";
            target = "hyperlink";
        }
        main();
    }

    function init(){
        var quill = new Quill('#editor-container', {
          modules: {
            syntax: true,
            toolbar: false
          },
          placeholder: 'type or paste html code here...'
          //theme: 'bubble'  // or 'snow'
        });
        document.getElementsByClassName("ql-editor")[0].innerHTML="

"

        function onPublish() {
            var myLink = document.getElementById('mylink');
            var html = quill.getText();
            myLink.onclick = function(){
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = "./js/main.js";
                document.getElementsByTagName("head")[0].appendChild(script);
                document.location.hash=serialize(html.replace(/"/g, "'"));
                return false;
            }
            document.getElementById('mylink').click();
        }
        document.getElementById("btnPublish").addEventListener("click", onPublish);

    }
    function main(){
        if(command === "create"){
            createHyperlink(resource);
        }
        else if(command === "load"){
            var deserializedPayload = deserialize(resource)
            loadHyperlink(deserializedPayload);
        }
    }

    function createHyperlink(){
        //change the command to load so the hyperlink instructs the api to load the resource
        command = "load";
        url.searchParams.set("command",command);
        url.searchParams.delete("source");
        url.searchParams.delete("target");
        url.searchParams.delete("resource");
        url.hash = "";
        var hyperlink = url.href + "#?" + resource;
        if(target === 'newWindow'){
            document.location=hyperlink;
        }
        else if(target === 'hyperlink'){
            document.body.innerHTML = "" + "Inception. It is possible." + "";
        }
    }

    function loadHyperlink(deserializedPayload){
        document.body.innerHTML=deserializedPayload;
    }

    function getHashPayload(url) {
        // read the hash
        var hash = url.hash
          , dataPos
          , payload
          ;
        if(hash)
            // remove hashtag
            hash = hash.slice(1);
        if(!hash)
            return false;

        dataPos = hash.indexOf("?") + 1;
        if(dataPos === -1)
            return false;

        return hash.slice(dataPos);
    }

    function serialize(data) {
        return btoa(pako.deflate( JSON.stringify(data), { to: 'string' }));
    }

    function deserialize(payload) {
        if(type=="data"){
            return "
" + pako.inflate( atob(payload), { to: 'string' }) + "
";
        }
        else{
            return JSON.parse( pako.inflate( atob(payload), { to: 'string' }));
        }
    }

})();<|endoftext|>


<commit_before>//visual and interactions
$(document).ready(function(){
	// toggler
	$('a.toggler').click(function(){
		var $form = $(this).parent();
		if($form.hasClass('visible'))
			$form.animate({top:'-360px'}, 300).removeClass('visible');
		else {
			$form.animate({top:'0px'}, 300).addClass('visible');
			$form.find('input#title').focus();
		}

	});
});
<commit_msg>Design Layout<commit_after>//visual and interactions
$(document).ready(function(){
	// toggler
	$('#page').on('click','a.toggler, li.js-clickable',function(){
		var $interaction = $('div#interaction');
		if($interaction.hasClass('visible'))
			$interaction.animate({top:'-360px'}, 300).removeClass('visible');
		else {
			$interaction.animate({top:'0px'}, 300).addClass('visible');
			$interaction.find('input#title').focus();
		}
	});
});
<|endoftext|>


<commit_before>(function() {

	'use strict';

	var masterfile = 'locales/master.json',
		$article = $('article'),
		$alert = $('.alert'),
		htmlPattern = /<[a-z][\s\S]*>/i,
		json, currentValue,

	throwAlert = function ( type, msg ) {
		setTimeout(function(){
			$alert.hide().attr('class', 'alert');
		}, 2500);

		$alert.addClass('alert-'+type).html(msg).show();
	},

	render = function ( obj ) {
		json = obj;
		$article.empty().renderJSON(obj);

		$('.renderjson-scalar', $article).each(function( key, el ) {
			htmlToMarkdown(key, el);
			stylise(el);
		});

		$('textarea').elastic();
	},

	stylise = function ( el ) {
		$(el).attr('class', 'col-xs-5 value')
			.prev().attr('class', 'col-xs-2 key')
			.parent().attr('class', 'row');
	},

	htmlToMarkdown = function ( i, el ) {
		var txt = el.value;

		if ( htmlPattern.test(txt) ) {
			var md = HTML2Markdown(txt);
			$article.find('[title=\''+el.title+'\']').val(md);
		}
	},

	storeCurrent = function ( ev ) {
		ev.stopPropagation();
		currentValue = ev.currentTarget.value.trim();
	},

	checkEdit = function ( ev ) {
		ev.currentTarget.value = ev.currentTarget.value.trim();

		if ( currentValue !== ev.currentTarget.value ){
			$(ev.currentTarget).addClass('modified').data('original', currentValue);

			previewChanges(ev.currentTarget);
		}
	},

	previewChanges = function ( el ) {
		var html = marked(el.value);

		if ( !el.$preview) {
			el.$preview = $('
').insertAfter(el);
		}

		// if el has only one p tag remove it.
		if ( html.split('
').length-1 === 1 )
			html = html.replace(/(\
|\<\/p\>)/gi, '').replace(/(\r\n|\n|\r)/gm,'');

		el.$preview.html(html);
	},

	mergeObj = function (a, b) {
		for (var key in b) {
			if (key in a) {
				a[key] = typeof a[key] === 'object' &&
						typeof b[key] === 'object' ? mergeObj(a[key], b[key]) : b[key];
			}
		}
		return a;
	},

	uploadFile = function ( ev ) {
		var file = this.files[0],
			fd = new FormData(),
			xhr;

		fd.append('uploadfile', file);

		xhr = new XMLHttpRequest();
		xhr.open('POST', 'upload.php', true);

		xhr.onload = function() {
			if (this.status == 200) {
				var response;
				try {
					response = JSON.parse(this.response);

				} catch(error) {
					alert('Your file is not correctly formatted');
				}

				if ( response ) {
					var obj;

					if ( ev.currentTarget.name === 'master' ){
						obj = response.dataObj
					} else {
						obj = mergeObj(jQuery.extend({}, json), response.dataObj);
					}

					render(obj);
				}
			}
		};

		xhr.send(fd);
	},

	reset = function () {
		location.reload();
	},

	// update value in json object to match what changed in editor
	changeJsonValue = function ( obj, strProp, newValue ) {
		var re = /\["?([^"\]]+)"?\]/g,
			m, p;

		while ((m = re.exec(strProp)) && typeof obj[p = m[1]] === 'object')
			obj = obj[p];

		if (p)
			obj[p] = newValue;
	},

	save = function () {
		var saveObj = {
				filename: json.code || 'locale',
				json: json
			}, isModified;

		$(':focus').blur();

		$('.modified').each(function(key, el) {
			var node = el.title,
				newValue = el.$preview.html();

			changeJsonValue(json, node, newValue);
			isModified = 1;
		}).removeClass('modified');

		if ( !isModified ) return;

		$.post('save.php', saveObj, function ( response ){
			json = saveObj.json;
			// window.open(response);
			throwAlert('success', 'Your file was saved succesfully as '+response+'')
		});
	};

	// upload initial file
	// $.get(masterfile, render);

	// initialise markdown preview renderer
	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: false,
		breaks: true,
		sanitize: true,
		smartLists: true,
		smartypants: true
	});

	// set events
	$article.on('focus', '.value', storeCurrent);
	$article.on('blur', '.value', checkEdit);

	$('.uploadfile').on('change', uploadFile);
	$('#reset').on('click', reset);
	$('#save').on('click', save);

	// add support for old browsers
	if (typeof String.prototype.trim !== 'function') {
		String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/g, '');
		}
	}
})();<commit_msg>comma added<commit_after>(function() {

	'use strict';

	var masterfile = 'locales/master.json',
		$article = $('article'),
		$alert = $('.alert'),
		htmlPattern = /<[a-z][\s\S]*>/i,
		json, currentValue,

	throwAlert = function ( type, msg ) {
		setTimeout(function(){
			$alert.hide().attr('class', 'alert');
		}, 2500);

		$alert.addClass('alert-'+type).html(msg).show();
	},

	render = function ( obj ) {
		json = obj;
		$article.empty().renderJSON(obj);

		$('.renderjson-scalar', $article).each(function( key, el ) {
			htmlToMarkdown(key, el);
			stylise(el);
		});

		$('textarea').elastic();
	},

	stylise = function ( el ) {
		$(el).attr('class', 'col-xs-5 value')
			.prev().attr('class', 'col-xs-2 key')
			.parent().attr('class', 'row');
	},

	htmlToMarkdown = function ( i, el ) {
		var txt = el.value;

		if ( htmlPattern.test(txt) ) {
			var md = HTML2Markdown(txt);
			$article.find('[title=\''+el.title+'\']').val(md);
		}
	},

	storeCurrent = function ( ev ) {
		ev.stopPropagation();
		currentValue = ev.currentTarget.value.trim();
	},

	checkEdit = function ( ev ) {
		ev.currentTarget.value = ev.currentTarget.value.trim();

		if ( currentValue !== ev.currentTarget.value ){
			$(ev.currentTarget).addClass('modified').data('original', currentValue);

			previewChanges(ev.currentTarget);
		}
	},

	previewChanges = function ( el ) {
		var html = marked(el.value);

		if ( !el.$preview) {
			el.$preview = $('
').insertAfter(el);
		}

		// if el has only one p tag remove it.
		if ( html.split('
').length-1 === 1 )
			html = html.replace(/(\
|\<\/p\>)/gi, '').replace(/(\r\n|\n|\r)/gm,'');

		el.$preview.html(html);
	},

	mergeObj = function (a, b) {
		for (var key in b) {
			if (key in a) {
				a[key] = typeof a[key] === 'object' &&
						typeof b[key] === 'object' ? mergeObj(a[key], b[key]) : b[key];
			}
		}
		return a;
	},

	uploadFile = function ( ev ) {
		var file = this.files[0],
			fd = new FormData(),
			xhr;

		fd.append('uploadfile', file);

		xhr = new XMLHttpRequest();
		xhr.open('POST', 'upload.php', true);

		xhr.onload = function() {
			if (this.status == 200) {
				var response;
				try {
					response = JSON.parse(this.response);

				} catch(error) {
					alert('Your file is not correctly formatted');
				}

				if ( response ) {
					var obj;

					if ( ev.currentTarget.name === 'master' ){
						obj = response.dataObj
					} else {
						obj = mergeObj(jQuery.extend({}, json), response.dataObj);
					}

					render(obj);
				}
			}
		};

		xhr.send(fd);
	},

	reset = function () {
		location.reload();
	},

	// update value in json object to match what changed in editor
	changeJsonValue = function ( obj, strProp, newValue ) {
		var re = /\["?([^"\]]+)"?\]/g,
			m, p;

		while ((m = re.exec(strProp)) && typeof obj[p = m[1]] === 'object')
			obj = obj[p];

		if (p)
			obj[p] = newValue;
	},

	save = function () {
		var saveObj = {
				filename: json.code || 'locale',
				json: json
			}, isModified;

		$(':focus').blur();

		$('.modified').each(function(key, el) {
			var node = el.title,
				newValue = el.$preview.html();

			changeJsonValue(json, node, newValue);
			isModified = 1;
		}).removeClass('modified');

		if ( !isModified ) return;

		$.post('save.php', saveObj, function ( response ){
			json = saveObj.json;
			// window.open(response);
			throwAlert('success', 'Your file was saved succesfully as '+response+'')
		});
	};

	// upload initial file
	// $.get(masterfile, render);

	// initialise markdown preview renderer
	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: false,
		breaks: true,
		sanitize: true,
		smartLists: true,
		smartypants: true
	});

	// set events
	$article.on('focus', '.value', storeCurrent);
	$article.on('blur', '.value', checkEdit);

	$('.uploadfile').on('change', uploadFile);
	$('#reset').on('click', reset);
	$('#save').on('click', save);

	// add support for old browsers
	if (typeof String.prototype.trim !== 'function') {
		String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/g, '');
		};
	}
})();<|endoftext|>


<commit_before>require(['require-config'], function(config) {
  "use strict";
  console.log("main.");
  require.config(config);

  require(['views/mainview'], function(MainView) {
      console.log("main()");
      mainView = new MainView();
    }
  );
});
<commit_msg>Update main.js<commit_after>require(['require-config'], function(config) {
  "use strict";

  console.log("main.");
  require.config(config);

  require(['views/mainview'], function(MainView) {
      console.log("main()");
      var mainView = new MainView();
    }
  );
});
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var SShost= data['hosteeId']
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];

                    if(SShost == ""){
            var SShost = "None"
        }
         var html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
Host ID: ' + SShost+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var SubscribeNotify = data['preferences']['channel:notify:subscribe'];
         var TweetNotify = data['preferences']['channel:tweet:enabled'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var SShost= data['hosteeId']
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];

            var SShost = "None"
            if(SShost == "null"){
        }
         var html = '';
         html += '
' + Username + '
';
         html += '
----------'
          html += '
Url Link: Beam.pro/'+ Username +'';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid+ '';
         html += '
Channel ID: ' + ChannelID+ '';
         html += '
Cover ID: ' + Coverid+ '';
         html += '
Thumbnail ID: ' + Thumbnail+ '';
         html += '
Host ID: ' + SShost+ '';
         html += '
---Preference---'
         html += '
interactive:' + Tetris +'';
         html += '
Audience:' + Audience +'';
         html += '
SelfStreamMute:' + StreamMute +'';
         html += '
BeamBot FollowNotify:' + FollowNotify +'';
         html += '
BeamBot SubNotify:' + SubscribeNotify +'';
         html += '
TweetNotify:' + TweetNotify +'';
         html += '
Transcoding:' + te +'';
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>import React from 'react';
import {BrowserRouter, Match, Miss, Link} from 'react-router';

import Home from './Home';
import Login from './Login';
import NoMatch from './NoMatch';
import LoginButton from './LoginButton';

export default () => (
    <BrowserRouter>

                            <Link to="/" className="simple-text">REST-ON-COUCH</Link>

                                <Link to="/login" activeClassName="active">

Login

                                </Link>

                                <Link to="/logout" activeClassName="active">

Logout

                                </Link>

                                Dashboard

                                        <LoginButton/>

                            <Match exactly pattern="/" component={Home}/>
                            <Match pattern="/login" component={Login}/>
                            <Miss component={NoMatch}/>

    </BrowserRouter>
);
<commit_msg>redirect if user is logged in<commit_after>import React, {PropTypes} from 'react';
import {BrowserRouter, Match, Miss, Link, Redirect} from 'react-router';
import {connect} from 'react-redux';

import Home from './Home';
import Login from './Login';
import NoMatch from './NoMatch';
import LoginButton from './LoginButton';

const App = (props) => (
    <BrowserRouter>

                            <Link to="/" className="simple-text">REST-ON-COUCH</Link>

                                <Link to="/login" activeClassName="active">

Login

                                </Link>

                                <Link to="/logout" activeClassName="active">

Logout

                                </Link>

                                Dashboard

                                        <LoginButton/>

                            <Match exactly pattern="/" component={Home}/>
                            <Match pattern="/login" render={() => {
                                if (props.loggedIn) {
                                    return <Redirect to="/"/>;
                                } else {
                                    return <Login/>;
                                }
                            }} />
                            <Miss component={NoMatch}/>

    </BrowserRouter>
);

App.propTypes = {
    loggedIn: PropTypes.bool.isRequired
};

export default connect(
    (state) => ({loggedIn: state.login.loggedIn})
)(App);
<|endoftext|>