<commit_before>(function($) {

	Config.defaultserver = {
		server: 'sim.smogon.com',
		serverid: 'dev',
		serverport: 8001,
		serverprotocol: 'ws',
		registered: true
	};
	Config.sockjsprefix = '/showdown';
	Config.root = '/';

	var User = this.User = Backbone.Model.extend({
		defaults: {
			name: "Guest",
			registered: false,
			named: false,
			avatar: 0
		}
	});

	var App = this.App = Backbone.Router.extend({
		root: '/',
		routes: {
			'*path': 'dispatchFragment'
		},
		initialize: function() {
			window.app = this;
			$('#main').html('');
			this.initializeRooms();
			this.user = new User();
			this.topbar = new Topbar({el: $('#header')});
			Backbone.history.start({pushState: true});
			this.addRoom('');
		},
		dispatchFragment: function(fragment) {
			this.joinRoom(fragment||'');
		},
		/**
		 * Send to sim server
		 */
		send: function(data, type) {
			if (!this.socket) return;
			if (typeof data === 'object') {
				if (type) data.type = type;
				this.socket.send($.toJSON(data));
			} else {
				this.socket.send('|'+data);
			}
		},
		/**
		 * Receive from sim server
		 */
		receive: function() {
			//
		},

		// Room management

		initializeRooms: function() {
			this.rooms = {};

			$(window).on('resize', _.bind(this.updateLayout, this));
		},
		// the currently active room
		curRoom: null,
		curSideRoom: null,
		sideRoom: null,
		joinRoom: function(id, type) {
			if (this.rooms[id]) {
				this.focusRoom(id);
				return this.rooms[id];
			}

			var room = this.addRoom(id, type);
			this.focusRoom(id);
			return room;
		},
		addRoom: function(id, type) {
			if (this.rooms[id]) return this.rooms[id];

			var el = $('

').appendTo('body');
			type = type || {
				'': MainMenuRoom,
				'teambuilder': TeambuilderRoom,
				'ladder': LadderRoom
			}[id];
			if (!type) type = ChatRoom;
			var room = this.rooms[id] = new type({
				id: id,
				el: el
			});
			return room;
		},
		focusRoom: function(id) {
			var room = this.rooms[id];
			if (!room) return false;
			if (this.curRoom === room || this.curSideRoom === room) return true;

			this.updateSideRoom(id);
			this.updateLayout();
			if (this.curSideRoom !== room) {
				if (this.curRoom) {
					this.curRoom.hide();
					this.curRoom = null;
				}
				this.curRoom = window.room = room;
				this.updateLayout();
				if (this.curRoom.id === id) this.navigate(id);
			}

			return;
		},
		updateLayout: function() {
			if (!this.curRoom) return; // can happen during initialization
			if (!this.sideRoom) {
				this.curRoom.show('full');
				this.topbar.updateTabbar();
				return;
			}
			var leftMin = (this.curRoom.minWidth || this.curRoom.bestWidth);
			var rightMin = (this.sideRoom.minWidth || this.sideRoom.bestWidth);
			var available = $('body').width();
			if (this.curRoom.isSideRoom) {
				// we're trying to focus a side room
				if (available >= this.rooms[''].minWidth + leftMin) {
					// it fits to the right of the main menu, so do that
					this.curSideRoom = this.sideRoom = this.curRoom;
					this.curRoom = this.rooms[''];
					leftMin = (this.curRoom.minWidth || this.curRoom.bestWidth);
					rightMin = (this.sideRoom.minWidth || this.sideRoom.bestWidth);
				} else if (this.sideRoom) {
					// nooo
					if (this.curSideRoom) {
						this.curSideRoom.hide();
						this.curSideRoom = null;
					}
					this.curRoom.show('full');
					this.topbar.updateTabbar();
					return;
				}
			}
			if (available < leftMin + rightMin) {
				if (this.curSideRoom) {
					this.curSideRoom.hide();
					this.curSideRoom = null;
				}
				this.curRoom.show('full');
				this.topbar.updateTabbar();
				return;
			}
			this.curSideRoom = this.sideRoom;
			var leftMax = (this.curRoom.maxWidth || this.curRoom.bestWidth);
			var rightMax = (this.sideRoom.maxWidth || this.sideRoom.bestWidth);
			var rightWidth = rightMin;
			if (leftMax + rightMax <= available) {
				rightWidth = rightMax;
			} else {
				available -= leftMin + rightMin;
				var wanted = leftMax - leftMin + rightMax - rightMin;
				if (wanted) rightWidth = Math.floor(rightMin + (rightMax - rightMin) * available / wanted);
			}
			this.curRoom.show('left', rightWidth);
			this.curSideRoom.show('right', rightWidth);
			this.topbar.updateTabbar();
		},
		updateSideRoom: function(id) {
			if (id && this.rooms[id].isSideRoom) {
				this.sideRoom = this.rooms[id];
				if (this.curSideRoom && this.curSideRoom !== this.sideRoom) {
					this.curSideRoom.hide();
					this.curSideRoom = this.sideRoom;
				}
				// updateLayout will null curSideRoom if there's
				// no room for this room
			}
		},
		leaveRoom: function(id) {
			var room = this.rooms[id];
			if (!room) return false;
			if (room.requestLeave && !room.requestLeave()) return false;
			return this.removeRoom(id);
		},
		removeRoom: function(id) {
			var room = this.rooms[id];
			if (room) {
				if (room === this.curRoom) this.focusRoom('');
				delete this.rooms[id];
				room.destroy();
				if (room === this.sideRoom) {
					this.sideRoom = null;
					this.curSideRoom = null;
					this.updateSideRoom();
				}
				this.updateLayout();
				return true;
			}
			return false;
		}
	});

	var Topbar = this.Topbar = Backbone.View.extend({
		events: {
			'click a': 'click'
		},
		initialize: function() {
			this.$el.html('

');
			this.$tabbar = this.$('.maintabbar');
			this.$sidetabbar = this.$('.sidetabbar');
			this.updateTabbar();
		},
		'$tabbar': null,
		updateTabbar: function() {
			var curId = (app.curRoom ? app.curRoom.id : '');
			var curSideId = (app.curSideRoom ? app.curSideRoom.id : '');

			var buf = '

 Home

';
			var atLeastOne = false;
			var sideBuf = '';
			for (var id in app.rooms) {
				if (!id) continue;
				var name = id;
				if (id === 'lobby') name = ' Lobby chat';
				else if (id === 'teambuilder') name = ' Teambuilder';
				else if (id === 'ladder') name = ' Ladder';
				if (app.rooms[id].isSideRoom) {
					if (!sideBuf) sideBuf = '
';
					sideBuf += '
'+name+'
';
					continue;
				}
				if (!atLeastOne) {
					buf += '
';
					atLeastOne = true;
				}
				buf += '
'+name+'
';
			}
			if (atLeastOne) buf += '
';
			if (app.curSideRoom) {
				var sideWidth = app.curSideRoom.width;
				this.$tabbar.css({right:sideWidth}).html(buf);
				this.$sidetabbar.css({left:'auto',width:sideWidth,right:0}).show().html(sideBuf);
			} else {
				buf += sideBuf;
				this.$tabbar.css({right:0}).html(buf);
				this.$sidetabbar.hide();
			}

			if (app.rooms['']) app.rooms[''].updateRightMenu();
		},
		click: function(e) {
			e.preventDefault();
			var $target = $(e.currentTarget);
			var id = $target.attr('href');
			if (id.substr(0, app.root.length) === app.root) {
				id = id.substr(app.root.length);
			}
			if ($target.hasClass('closebutton')) {
				app.leaveRoom(id);
			} else {
				app.focusRoom(id);
			}
		}
	});

	var Room = this.Room = Backbone.View.extend({

		// communication

		/**
		 * Send to sim server
		 */
		send: function(data, type) {
			if (!app.socket) return;
			if (typeof data === 'object') {
				if (type) data.type = type;
				data.room = this.id;
				app.socket.send($.toJSON(data));
			} else {
				app.socket.send(''+this.id+'|'+data);
			}
		},
		/**
		 * Receive from sim server
		 */
		receive: function(data) {
			//
		},

		// graphical

		bestWidth: 640,
		show: function(position, rightWidth) {
			switch (position) {
			case 'left':
				this.$el.css({left: 0, width: 'auto', right: rightWidth});
				break;
			case 'right':
				this.$el.css({left: 'auto', width: rightWidth, right: 0});
				this.width = rightWidth;
				break;
			case 'full':
				this.$el.css({left: 0, width: 'auto', right: 0});
				break;
			}
			this.$el.show();
			this.focus();
		},
		hide: function() {
			this.blur();
			this.$el.hide();
		},
		focus: function() {},
		blur: function() {},

		// allocation

		destroy: function() {
			this.remove();
			delete this.app;
		}
	});

	var ChatRoom = this.ChatRoom = Room.extend({
		minWidth: 320,
		isSideRoom: true,
		initialize: function() {
			var buf = '

Connecting...
';
			this.$el.addClass('ps-room-light').html(buf);
			app.user.on('change', this.updateUser, this);
		},
		updateUser: function() {
			//
		}
	});

}).call(this, jQuery);
<commit_msg>Tab group Teambuilder/Ladder with Home<commit_after>(function($) {

	Config.defaultserver = {
		server: 'sim.smogon.com',
		serverid: 'dev',
		serverport: 8001,
		serverprotocol: 'ws',
		registered: true
	};
	Config.sockjsprefix = '/showdown';
	Config.root = '/';

	var User = this.User = Backbone.Model.extend({
		defaults: {
			name: "Guest",
			registered: false,
			named: false,
			avatar: 0
		}
	});

	var App = this.App = Backbone.Router.extend({
		root: '/',
		routes: {
			'*path': 'dispatchFragment'
		},
		initialize: function() {
			window.app = this;
			$('#main').html('');
			this.initializeRooms();
			this.user = new User();
			this.topbar = new Topbar({el: $('#header')});
			Backbone.history.start({pushState: true});
			this.addRoom('');
		},
		dispatchFragment: function(fragment) {
			this.joinRoom(fragment||'');
		},
		/**
		 * Send to sim server
		 */
		send: function(data, type) {
			if (!this.socket) return;
			if (typeof data === 'object') {
				if (type) data.type = type;
				this.socket.send($.toJSON(data));
			} else {
				this.socket.send('|'+data);
			}
		},
		/**
		 * Receive from sim server
		 */
		receive: function() {
			//
		},

		// Room management

		initializeRooms: function() {
			this.rooms = {};

			$(window).on('resize', _.bind(this.updateLayout, this));
		},
		// the currently active room
		curRoom: null,
		curSideRoom: null,
		sideRoom: null,
		joinRoom: function(id, type) {
			if (this.rooms[id]) {
				this.focusRoom(id);
				return this.rooms[id];
			}

			var room = this.addRoom(id, type);
			this.focusRoom(id);
			return room;
		},
		addRoom: function(id, type) {
			if (this.rooms[id]) return this.rooms[id];

			var el = $('

').appendTo('body');
			type = type || {
				'': MainMenuRoom,
				'teambuilder': TeambuilderRoom,
				'ladder': LadderRoom
			}[id];
			if (!type) type = ChatRoom;
			var room = this.rooms[id] = new type({
				id: id,
				el: el
			});
			return room;
		},
		focusRoom: function(id) {
			var room = this.rooms[id];
			if (!room) return false;
			if (this.curRoom === room || this.curSideRoom === room) return true;

			this.updateSideRoom(id);
			this.updateLayout();
			if (this.curSideRoom !== room) {
				if (this.curRoom) {
					this.curRoom.hide();
					this.curRoom = null;
				}
				this.curRoom = window.room = room;
				this.updateLayout();
				if (this.curRoom.id === id) this.navigate(id);
			}

			return;
		},
		updateLayout: function() {
			if (!this.curRoom) return; // can happen during initialization
			if (!this.sideRoom) {
				this.curRoom.show('full');
				this.topbar.updateTabbar();
				return;
			}
			var leftMin = (this.curRoom.minWidth || this.curRoom.bestWidth);
			var rightMin = (this.sideRoom.minWidth || this.sideRoom.bestWidth);
			var available = $('body').width();
			if (this.curRoom.isSideRoom) {
				// we're trying to focus a side room
				if (available >= this.rooms[''].minWidth + leftMin) {
					// it fits to the right of the main menu, so do that
					this.curSideRoom = this.sideRoom = this.curRoom;
					this.curRoom = this.rooms[''];
					leftMin = (this.curRoom.minWidth || this.curRoom.bestWidth);
					rightMin = (this.sideRoom.minWidth || this.sideRoom.bestWidth);
				} else if (this.sideRoom) {
					// nooo
					if (this.curSideRoom) {
						this.curSideRoom.hide();
						this.curSideRoom = null;
					}
					this.curRoom.show('full');
					this.topbar.updateTabbar();
					return;
				}
			}
			if (available < leftMin + rightMin) {
				if (this.curSideRoom) {
					this.curSideRoom.hide();
					this.curSideRoom = null;
				}
				this.curRoom.show('full');
				this.topbar.updateTabbar();
				return;
			}
			this.curSideRoom = this.sideRoom;
			var leftMax = (this.curRoom.maxWidth || this.curRoom.bestWidth);
			var rightMax = (this.sideRoom.maxWidth || this.sideRoom.bestWidth);
			var rightWidth = rightMin;
			if (leftMax + rightMax <= available) {
				rightWidth = rightMax;
			} else {
				available -= leftMin + rightMin;
				var wanted = leftMax - leftMin + rightMax - rightMin;
				if (wanted) rightWidth = Math.floor(rightMin + (rightMax - rightMin) * available / wanted);
			}
			this.curRoom.show('left', rightWidth);
			this.curSideRoom.show('right', rightWidth);
			this.topbar.updateTabbar();
		},
		updateSideRoom: function(id) {
			if (id && this.rooms[id].isSideRoom) {
				this.sideRoom = this.rooms[id];
				if (this.curSideRoom && this.curSideRoom !== this.sideRoom) {
					this.curSideRoom.hide();
					this.curSideRoom = this.sideRoom;
				}
				// updateLayout will null curSideRoom if there's
				// no room for this room
			}
		},
		leaveRoom: function(id) {
			var room = this.rooms[id];
			if (!room) return false;
			if (room.requestLeave && !room.requestLeave()) return false;
			return this.removeRoom(id);
		},
		removeRoom: function(id) {
			var room = this.rooms[id];
			if (room) {
				if (room === this.curRoom) this.focusRoom('');
				delete this.rooms[id];
				room.destroy();
				if (room === this.sideRoom) {
					this.sideRoom = null;
					this.curSideRoom = null;
					this.updateSideRoom();
				}
				this.updateLayout();
				return true;
			}
			return false;
		}
	});

	var Topbar = this.Topbar = Backbone.View.extend({
		events: {
			'click a': 'click'
		},
		initialize: function() {
			this.$el.html('

');
			this.$tabbar = this.$('.maintabbar');
			this.$sidetabbar = this.$('.sidetabbar');
			this.updateTabbar();
		},
		'$tabbar': null,
		updateTabbar: function() {
			var curId = (app.curRoom ? app.curRoom.id : '');
			var curSideId = (app.curSideRoom ? app.curSideRoom.id : '');

			var buf = '

 Home
';
			if (app.rooms.teambuilder) buf += '
 Teambuilder
';
			if (app.rooms.ladder) buf += '
 Ladder
';
			buf += '
';
			var atLeastOne = false;
			var sideBuf = '';
			for (var id in app.rooms) {
				if (!id || id === 'teambuilder' || id === 'ladder') continue;
				var name = id;
				if (id === 'lobby') name = ' Lobby chat';
				if (app.rooms[id].isSideRoom) {
					if (!sideBuf) sideBuf = '
';
					sideBuf += '
'+name+'
';
					continue;
				}
				if (!atLeastOne) {
					buf += '
';
					atLeastOne = true;
				}
				buf += '
'+name+'
';
			}
			if (atLeastOne) buf += '
';
			if (app.curSideRoom) {
				var sideWidth = app.curSideRoom.width;
				this.$tabbar.css({right:sideWidth}).html(buf);
				this.$sidetabbar.css({left:'auto',width:sideWidth,right:0}).show().html(sideBuf);
			} else {
				buf += sideBuf;
				this.$tabbar.css({right:0}).html(buf);
				this.$sidetabbar.hide();
			}

			if (app.rooms['']) app.rooms[''].updateRightMenu();
		},
		click: function(e) {
			e.preventDefault();
			var $target = $(e.currentTarget);
			var id = $target.attr('href');
			if (id.substr(0, app.root.length) === app.root) {
				id = id.substr(app.root.length);
			}
			if ($target.hasClass('closebutton')) {
				app.leaveRoom(id);
			} else {
				app.focusRoom(id);
			}
		}
	});

	var Room = this.Room = Backbone.View.extend({

		// communication

		/**
		 * Send to sim server
		 */
		send: function(data, type) {
			if (!app.socket) return;
			if (typeof data === 'object') {
				if (type) data.type = type;
				data.room = this.id;
				app.socket.send($.toJSON(data));
			} else {
				app.socket.send(''+this.id+'|'+data);
			}
		},
		/**
		 * Receive from sim server
		 */
		receive: function(data) {
			//
		},

		// graphical

		bestWidth: 640,
		show: function(position, rightWidth) {
			switch (position) {
			case 'left':
				this.$el.css({left: 0, width: 'auto', right: rightWidth});
				break;
			case 'right':
				this.$el.css({left: 'auto', width: rightWidth, right: 0});
				this.width = rightWidth;
				break;
			case 'full':
				this.$el.css({left: 0, width: 'auto', right: 0});
				break;
			}
			this.$el.show();
			this.focus();
		},
		hide: function() {
			this.blur();
			this.$el.hide();
		},
		focus: function() {},
		blur: function() {},

		// allocation

		destroy: function() {
			this.remove();
			delete this.app;
		}
	});

	var ChatRoom = this.ChatRoom = Room.extend({
		minWidth: 320,
		isSideRoom: true,
		initialize: function() {
			var buf = '

Connecting...
';
			this.$el.addClass('ps-room-light').html(buf);
			app.user.on('change', this.updateUser, this);
		},
		updateUser: function() {
			//
		}
	});

}).call(this, jQuery);
<|endoftext|>


<commit_before>/*!
 * common
 * xiewulong <xiewulong@vip.qq.com>
 * create: 2016/4/1
 * version: 1.0.0
 */

/**
 * common module
 * @module common
 * @since 1.0.0
 */
define(['jquery', 'config', 'bootstrap'], function($, config) {

	var	$win	= $(window),
		$doc	= $(document),
		Fn		= function() {},
		exports	= {};

	/**
	 * 获取get数据
	 * @method common.getQuerys
	 * @since 1.0.0
	 * @return {object}
	 */
	exports.getQuerys = function() {
		return location.search ? new Function('return {' + location.search.substring(1).replace(/&/g, '",').replace(/=/g, ':"') + '"}')() : {};
	};

	/**
	 * 生成query
	 * @method common.buldQuery
	 * @since 1.0.0
	 * @return {string}
	 */
	exports.buldQuery = function(querys, hasQuerys) {
		var i, key,
			_querys		= [];
		if(querys) {
			i = 0;
			for(key in querys) {
				_querys.push((!i && !hasQuerys ? '?' : '&') + key + '=' + querys[key]);
				i++;
			}
		}
		return _querys.join('');
	};

	//获取链接
	exports.getUrl = function(action, querys) {
		return config.path + action + exports.buldQuery(querys, action.indexOf('?') >= 0);
	};

	//获取请求链接
	exports.getRequestUrl = function(action, querys) {
		return config.api + action + exports.buldQuery(querys, action.indexOf('?') >= 0);
	};

	/**
	 * 开启模态框
	 * @method $.modal
	 * @since 1.0.0
	 * @param {string} html html结构
	 * @param {object} options bootstrap模态框参数
	 * @return {object}
	 */
	$.modal = function(html, options) {
		return $(html).modal(options).on('shown.bs.modal', function() {
			$(this).find('[autofocus=autofocus]').focus();
		}).on('hidden.bs.modal', function() {
			$(this).remove();
		});
	};

	/**
	 * ajax全局配置
	 * @since 1.0.0
	 */
	$.ajaxSetup({
		//contentType: 'application/json',
		//crossDomain: true,
		//xhrFields: {withCredentials: true},
		dataType: 'json',
		error: function(xhr, status, error) {
			console.log(error);
		}
	});

	return exports;

});
<commit_msg>samples<commit_after>/*!
 * common
 * xiewulong <xiewulong@vip.qq.com>
 * create: 2016/4/1
 * version: 1.0.0
 */

/**
 * common module
 * @module common
 * @since 1.0.0
 */
define(['jquery', 'config', 'bootstrap'], function($, config) {

	var	$win	= $(window),
		$doc	= $(document),
		Fn		= function() {},
		exports	= {};

	/**
	 * 获取get数据
	 * @method common.getQuerys
	 * @since 1.0.0
	 * @return {object}
	 */
	exports.getQuerys = function() {
		return location.search ? new Function('return {' + location.search.substring(1).replace(/&/g, '",').replace(/=/g, ':"') + '"}')() : {};
	};

	/**
	 * 生成query
	 * @method common.buldQuery
	 * @since 1.0.0
	 * @return {string}
	 */
	exports.buldQuery = function(querys, hasQuerys) {
		var i, key,
			_querys		= [];
		if(querys) {
			i = 0;
			for(key in querys) {
				_querys.push((!i && !hasQuerys ? '?' : '&') + key + '=' + querys[key]);
				i++;
			}
		}
		return _querys.join('');
	};

	//获取链接
	exports.getUrl = function(action, querys) {
		return config.path + action + exports.buldQuery(querys, action.indexOf('?') >= 0);
	};

	//获取请求链接
	exports.getRequestUrl = function(action, querys) {
		return config.api + action + exports.buldQuery(querys, action.indexOf('?') >= 0);
	};

	//获取元素在数组中的索引
	exports.inArray = function(item, arr) {
		for(var i = 0, len = arr.length; i < len; i++) {
			if(item.toString() == arr[i].toString()) return i;
		}
		return -1;
	};

	/**
	 * 开启模态框
	 * @method $.modal
	 * @since 1.0.0
	 * @param {string} html html结构
	 * @param {object} options bootstrap模态框参数
	 * @return {object}
	 */
	$.modal = function(html, options) {
		return $(html).modal(options).on('shown.bs.modal', function() {
			$(this).find('[autofocus=autofocus]').focus();
		}).on('hidden.bs.modal', function() {
			$(this).remove();
		});
	};

	/**
	 * ajax全局配置
	 * @since 1.0.0
	 */
	$.ajaxSetup({
		//contentType: 'application/json',
		//crossDomain: true,
		//xhrFields: {withCredentials: true},
		dataType: 'json',
		error: function(xhr, status, error) {
			console.log(error);
		}
	});

	return exports;

});
<|endoftext|>


<commit_before>// Mobile navigation toggle
$('#nav-icon-menu').click(function(){
    $(this).toggleClass('open');
    $('body').toggleClass('navigation-opened');
});

// Add the 'external' class to every outbound link on the site.
// The css will add a small right arrow after the link.
$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

// Remove external mark on Octocat icons, that already look external enough.
$("i.fa-github-alt").parent().removeClass("external");

// Prettyprint
$('pre').addClass("prettyprint");
$.getScript("/libs/prettify/js/run_prettify.js", function(){});
$.getScript("/libs/prettify/js/lang-css.js", function(){});
$.getScript("/libs/prettify/js/lang-go.js", function(){});
$.getScript("/libs/prettify/js/lang-proto.js", function(){});
$.getScript("/libs/prettify/js/lang-swift.js", function(){});
$.getScript("/libs/prettify/js/lang-yaml.js", function(){});

const initialHeadHeight = $('#header').innerHeight();
const tocNav = $('#toc');
const headerFixPosition = $('.nav-hero-container').innerHeight();
const stickyElement = $('.sticky-element');
const stickyElementPosition = 140; // Sticky element top-offset

$(function() {
    expandItemOnHashChange();
    preventDefaultScroll();
    initTocTocify();
    showScrollTopBtn();
});

jQuery(window).on('load', function() {
    scrollToAnchor();
    ifCookiesExist();
    tocHeight();
});

// Make functions works immediately on hash change
window.onhashchange = function() {
    expandItemOnHashChange();
    scrollToAnchor();
};

window.onscroll = function() {
    fixStickyElement();
    fixHead();
    tocHeight();
    showScrollTopBtn();
};

$(window).resize(function() {
    resizeTocHeightWithWindow();
    ifCookiesExist();
});

/**
 * Inits `toc` navigation if a page has more than 2 headers.
 *
 * @see {@link http://gregfranko.com/jquery.tocify.js/ Toc Tocify}
 */
function initTocTocify() {
    const docsContainer = $('.docs-content-text');
    const headersQuantity = docsContainer.find('h2, h3, h4');
    const topOffset = 12; // Offset from the `header` navigation

    if (headersQuantity.length >= 3) {
        tocNav.tocify({
            context: docsContainer,
            selectors: 'h2, h3, h4',
            showAndHide: false,
            scrollTo: initialHeadHeight + topOffset,
            extendPage: false,
            hashGenerator: 'Pretty'
        });
    }
}

/**
 * Fix sticky element on page while scrolling.
 */
function fixStickyElement() {
    if (stickyElement.length) {
        if (window.pageYOffset > stickyElementPosition) {
            stickyElement.addClass('sticky');
        }
        else {
            stickyElement.removeClass('sticky');
        }
    }
}

// Animation header on scroll
function fixHead() {
    var header = $('#header');
    if (header.length) {
        if (window.pageYOffset > headerFixPosition) {
            header.addClass("not-top"); // When navigation below offset
            header.addClass("pinned"); // When navigation below hero section
            header.removeClass("unpinned");
        }
        else {
            header.removeClass("pinned");
            header.addClass("unpinned");
        }

        // Return classes to the initial state when the navigation at the top of the page
        if (window.pageYOffset < initialHeadHeight) {
            header.removeClass("not-top");
            header.removeClass("unpinned");
        }
    }
}

function tocHeight() {
    if (tocNav.length) {
        var windowHeight = $(window).height();
        var scrollPosition = $(window).scrollTop();
        var footerTopPoint = $(".footer").position().top;
        var cookieContainerHeight = $("#cookieChoiceInfo").innerHeight();
        var contentMarginBottom = 60; /* The distance from the TOC to the bottom of the window. The value the same
        as a docs content. So the content and the TOC will be ended at the same line */

        /* Initial TOC max-height when the scroll at the top or middle of the page */
        var initialTocHeight = windowHeight - stickyElementPosition - contentMarginBottom - cookieContainerHeight;

        /* Dynamic value that changes on scroll. When the scroll at the bottom of the page, TOC height decreases. */
        var maxHeightValue = footerTopPoint - scrollPosition - stickyElementPosition - contentMarginBottom;

        /*The max-height value can be bigger than browser window if the scroll at the top of page.
        * So here is added the check*/
        if (maxHeightValue < initialTocHeight) {
            $(tocNav).css('max-height', maxHeightValue);
        }

        else {
            $(tocNav).css('max-height', initialTocHeight);
        }
    }
}

// Resize TOC height when window height is changing
function resizeTocHeightWithWindow() {
    if ($(window).height() > 600) {
        tocHeight();
    }
}

// Expand FAQ item on hash change
function expandItemOnHashChange() {
    if ("onhashchange" in window) {
        $(location.hash).collapse('show');
    }
}

// Prevent default scroll and double click on the same hash
function preventDefaultScroll() {
    $('.anchor-link').click(function(event) {
        var anchor = $(this).attr("href");
        var x = window.pageXOffset;
        var y = window.pageYOffset;
        event.preventDefault();
        window.location.hash = anchor;
        window.scrollTo(x, y);
    });
}

function scrollToAnchor() {
    var anchor = location.hash;
    var offset = -150; // Top offset for move header below fixed header

    if ($(anchor).length) {
        $(window).scrollTo($(anchor), 500, {offset: offset});
    }
}

var goTopBtn = $("#go-top-btn");
var copyrightEl = $(".copyright");

/**
 * Adds additional padding values if the `cookieChoiceInfo` exist on the page.
 */
function ifCookiesExist() {
    var cookieInfo = $("#cookieChoiceInfo");
    var cookieAgreeBtn = $("#cookieChoiceDismiss");
    var cookieContainerHeight = cookieInfo.innerHeight();
    var marginBottom = 10; // A bottom margin for the `Go to Top` button
    var copyrightPaddingBottom = 24; // A bottom padding for the `Copyright` div element

    if(cookieInfo.length){
        $(goTopBtn).css('bottom', cookieContainerHeight + marginBottom);
        $(copyrightEl).css('padding-bottom', cookieContainerHeight + copyrightPaddingBottom);

        /**
         * Removes additional padding values on the `Agree` button click.
         */
        $(cookieAgreeBtn).click(function(){
            $(goTopBtn).css('bottom', marginBottom);
            $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
        });
    }

    else {
        $(goTopBtn).css('bottom', marginBottom);
        $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
    }
}

// When the user scrolls down 1500px from the top of the document, show the button ”Go to Top“
function showScrollTopBtn() {
    if ($(this).scrollTop() > 1500 ) {
        $(goTopBtn).show();

    } else {
        $(goTopBtn).hide();
    }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    $("html, body").stop().animate({scrollTop: 0}, 500, 'swing'); return false;
}
<commit_msg>Cleanup the function and extract calculate variables to use them for `side-nav`<commit_after>// Mobile navigation toggle
$('#nav-icon-menu').click(function(){
    $(this).toggleClass('open');
    $('body').toggleClass('navigation-opened');
});

// Add the 'external' class to every outbound link on the site.
// The css will add a small right arrow after the link.
$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

// Remove external mark on Octocat icons, that already look external enough.
$("i.fa-github-alt").parent().removeClass("external");

// Prettyprint
$('pre').addClass("prettyprint");
$.getScript("/libs/prettify/js/run_prettify.js", function(){});
$.getScript("/libs/prettify/js/lang-css.js", function(){});
$.getScript("/libs/prettify/js/lang-go.js", function(){});
$.getScript("/libs/prettify/js/lang-proto.js", function(){});
$.getScript("/libs/prettify/js/lang-swift.js", function(){});
$.getScript("/libs/prettify/js/lang-yaml.js", function(){});

const initialHeadHeight = $('#header').innerHeight();
const tocNav = $('#toc');
const headerFixPosition = $('.nav-hero-container').innerHeight();
const stickyElement = $('.sticky-element');
const stickyElementPosition = 140; // Sticky element top-offset

$(function() {
    expandItemOnHashChange();
    preventDefaultScroll();
    initTocTocify();
    showScrollTopBtn();
});

jQuery(window).on('load', function() {
    scrollToAnchor();
    ifCookiesExist();
    tocHeight();
});

// Make functions works immediately on hash change
window.onhashchange = function() {
    expandItemOnHashChange();
    scrollToAnchor();
};

window.onscroll = function() {
    fixStickyElement();
    fixHead();
    tocHeight();
    showScrollTopBtn();
};

$(window).resize(function() {
    resizeTocHeightWithWindow();
    ifCookiesExist();
});

/**
 * Inits `toc` navigation if a page has more than 2 headers.
 *
 * @see {@link http://gregfranko.com/jquery.tocify.js/ Toc Tocify}
 */
function initTocTocify() {
    const docsContainer = $('.docs-content-text');
    const headersQuantity = docsContainer.find('h2, h3, h4');
    const topOffset = 12; // Offset from the `header` navigation

    if (headersQuantity.length >= 3) {
        tocNav.tocify({
            context: docsContainer,
            selectors: 'h2, h3, h4',
            showAndHide: false,
            scrollTo: initialHeadHeight + topOffset,
            extendPage: false,
            hashGenerator: 'Pretty'
        });
    }
}

/**
 * Fix sticky element on page while scrolling.
 */
function fixStickyElement() {
    if (stickyElement.length) {
        if (window.pageYOffset > stickyElementPosition) {
            stickyElement.addClass('sticky');
        }
        else {
            stickyElement.removeClass('sticky');
        }
    }
}

// Animation header on scroll
function fixHead() {
    var header = $('#header');
    if (header.length) {
        if (window.pageYOffset > headerFixPosition) {
            header.addClass("not-top"); // When navigation below offset
            header.addClass("pinned"); // When navigation below hero section
            header.removeClass("unpinned");
        }
        else {
            header.removeClass("pinned");
            header.addClass("unpinned");
        }

        // Return classes to the initial state when the navigation at the top of the page
        if (window.pageYOffset < initialHeadHeight) {
            header.removeClass("not-top");
            header.removeClass("unpinned");
        }
    }
}

function tocHeight() {
    if (tocNav.length) {
        const elHeights = calcStickyElHeight();

        /**
         * Determines that the max-height value is less than browser window when the scroll
         * position at the top of the page.
         */
        if (elHeights.maxHeight < elHeights.initialHeight) {
            $(tocNav).css('max-height', elHeights.maxHeight);
        } else {
            $(tocNav).css('max-height', elHeights.initialHeight);
        }
    }
}

/**
 * Calculates a sticky element heights to make sure that it always fits on the page.
 *
 * @return {{initialHeight: number, maxHeight: number}}
 */
function calcStickyElHeight() {
    const windowHeight = $(window).height();
    const scrollPosition = $(window).scrollTop();
    const footerTopPoint = $('.footer').position().top;
    const cookieContainerHeight = $('#cookieChoiceInfo').innerHeight();

    /** The distance from the element to the bottom of the window. */
    const contentMarginBottom = 8;

    /** Initial element max-height when the scroll at the top or middle of the page */
    const initialHeight = windowHeight - stickyElementPosition - contentMarginBottom - cookieContainerHeight;

    /** Dynamic value that changes on scroll. When the scroll at the bottom of the page,
     * element height decreases.
     */
    const maxHeight = footerTopPoint - scrollPosition - stickyElementPosition - contentMarginBottom;

    return {initialHeight, maxHeight};
}

// Resize TOC height when window height is changing
function resizeTocHeightWithWindow() {
    if ($(window).height() > 600) {
        tocHeight();
    }
}

// Expand FAQ item on hash change
function expandItemOnHashChange() {
    if ("onhashchange" in window) {
        $(location.hash).collapse('show');
    }
}

// Prevent default scroll and double click on the same hash
function preventDefaultScroll() {
    $('.anchor-link').click(function(event) {
        var anchor = $(this).attr("href");
        var x = window.pageXOffset;
        var y = window.pageYOffset;
        event.preventDefault();
        window.location.hash = anchor;
        window.scrollTo(x, y);
    });
}

function scrollToAnchor() {
    var anchor = location.hash;
    var offset = -150; // Top offset for move header below fixed header

    if ($(anchor).length) {
        $(window).scrollTo($(anchor), 500, {offset: offset});
    }
}

var goTopBtn = $("#go-top-btn");
var copyrightEl = $(".copyright");

/**
 * Adds additional padding values if the `cookieChoiceInfo` exist on the page.
 */
function ifCookiesExist() {
    var cookieInfo = $("#cookieChoiceInfo");
    var cookieAgreeBtn = $("#cookieChoiceDismiss");
    var cookieContainerHeight = cookieInfo.innerHeight();
    var marginBottom = 10; // A bottom margin for the `Go to Top` button
    var copyrightPaddingBottom = 24; // A bottom padding for the `Copyright` div element

    if(cookieInfo.length){
        $(goTopBtn).css('bottom', cookieContainerHeight + marginBottom);
        $(copyrightEl).css('padding-bottom', cookieContainerHeight + copyrightPaddingBottom);

        /**
         * Removes additional padding values on the `Agree` button click.
         */
        $(cookieAgreeBtn).click(function(){
            $(goTopBtn).css('bottom', marginBottom);
            $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
        });
    }

    else {
        $(goTopBtn).css('bottom', marginBottom);
        $(copyrightEl).css('padding-bottom', copyrightPaddingBottom);
    }
}

// When the user scrolls down 1500px from the top of the document, show the button ”Go to Top“
function showScrollTopBtn() {
    if ($(this).scrollTop() > 1500 ) {
        $(goTopBtn).show();

    } else {
        $(goTopBtn).hide();
    }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    $("html, body").stop().animate({scrollTop: 0}, 500, 'swing'); return false;
}
<|endoftext|>


<commit_before>
// Based on https://github.com/dcodeIO/AssemblyScript/blob/gh-pages/assets/sexpr.js

export default function registerWastSyntax(monaco) {
    monaco.languages.register({ id: 'wast' });

    monaco.languages.setLanguageConfiguration('wast', {
        comments: {
		    lineComment: ';;',
		    blockComment: ['\\(;', ';\\)'],
        },
        brackets: [
            ['(', ')']
        ],
        autoClosingPairs: [
            { open: '(', close: ')' },
            { open: '"', close: '"' }
        ],
        surroundingPairs: [
            { open: '(', close: ')' },
            { open: '"', close: '"' }
        ]
    });

    monaco.languages.setMonarchTokensProvider('wast', {

        tokenPostfix: '.wast',

        keywords: [
            "module",
            "type",
            "memory",
            "data",
            "export",
            "import",
            "func",
            "struct",
            "start",
            "table",
            "elem",
            "element",
            "global",
            "mut",
            "local",
            "param",
            "result",
            "offset",
            "code",
            "segment",
            "invoke",
            "label",

            // Control
            "unreachable",
            "nop",
            "block",
            "loop",
            "if",
            "else",
            "end",
            "br",
            "br_if",
            "br_table",
            "return",

            // Call
            "call",
            "call_indirect",
            "call_import"
        ],

        types: [
            "i32",
            "i64",
            "f32",
            "f64",
            "anyfunc",
            "func",
            "void"
        ],

        operations: [
            // Parametric
            "drop",
            "select",

            // Variable access
            "get_local",
            "set_local",
            "tee_local",
            "get_global",
            "set_global",

            // Memory related
            "load",
            "load8_s",
            "load8_u",
            "load16_s",
            "load16_u",
            "load32_s",
            "load32_u",
            "store",
            "store8",
            "store16",
            "store32",
            "current_memory",
            "grow_memory",

            // Constants
            "const",

            // Comparison
            "eqz",
            "eq",
            "ne",
            "lt_s",
            "lt_u",
            "lt",
            "gt_s",
            "gt_u",
            "gt",
            "le_s",
            "le_u",
            "le",
            "ge_s",
            "ge_u",
            "ge",

            // Numeric
            "clz",
            "ctz",
            "popcnt",
            "add",
            "sub",
            "mul",
            "div_s",
            "div_u",
            "div",
            "rem_s",
            "rem_u",
            "and",
            "xor",
            "or",
            "shl",
            "shr_s",
            "shr_u",
            "rotl",
            "rotr",
            "abs",
            "neg",
            "ceil",
            "floor",
            "trunc",
            "nearest",
            "sqrt",
            "min",
            "max",
            "copysign",

            // Conversion
            "wrap",
            "trunc_s",
            "trunc_u",
            "extend_s",
            "extend_u",
            "convert_s",
            "convert_u",
            "demote",
            "promote",

            // Reinterpretations
            "reinterpret",

            // Misc
            "tableswitch",
            "has_feature",

            // Assertion
            "failure",
            "assert_invalid",
            "assert_trap",
            "assert_return_nan",
            "assert_return"
        ],

        escapes:      /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
        digits:       /\d+(_+\d+)*/,
        octaldigits:  /[0-7]+(_+[0-7]+)*/,
        binarydigits: /[0-1]+(_+[0-1]+)*/,
        hexdigits:    /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,

    	tokenizer: {
    		root: [
                { include: '@whitespace' },

                [/"([^"\\]|\\.)*$/, 'string.invalid'],
                [/"/, 'string', '@string'],

                [/(@digits)[eE]([+\-]?(@digits))?[fFdD]?/, 'number.float'],
                [/(@digits)\.(@digits)([eE][+\-]?(@digits))?[fFdD]?/, 'number.float'],
                [/0[xX](@hexdigits)[Ll]?/, 'number.hex'],
                [/0(@octaldigits)[Ll]?/, 'number.octal'],
                [/0[bB](@binarydigits)[Ll]?/, 'number.binary'],
                [/(@digits)[fFdD]/, 'number.float'],
                [/(@digits)[lL]?/, 'number'],
                [/[+\-]?(infinity|inf|nan)/, 'constant.number'],

                [/\./, 'punctuation.separator.dot'],

                [/\$[^\s"\(\)\{\}\[\]]+/, { token: 'variable' }],

                [/[a-zA-Z_$][\w$]*/, {
                    cases: {
                        '@keywords':   { token: 'keyword.$0' },
                        '@types':      { token: 'entity.name.type.class.$0' },
                        '@operations': { token: 'keyword.operator.$0' },
                        '@default':    'identifier'
                    }
                }]
            ],

            string: [
                [/[^\\"]+/,  'string'],
                [/@escapes/, 'string.escape'],
                [/\\./,      'string.escape.invalid'],
                [/"/,        'string', '@pop']
            ],

            whitespace: [
                [/[ \t\r\n]+/,           ''],
                [/(^;{2}.*$)/,           'comment.line'],
                [/(^\(;[\n\t\r\w]+;\))/, 'comment.block']
            ],

            comment: [
                [/(;{2})(.*)$/, 'comment.line']
            ]
        }
    });
}
<commit_msg>update wast grammar<commit_after>
// Based on https://github.com/dcodeIO/AssemblyScript/blob/gh-pages/assets/sexpr.js

export default function registerWastSyntax(monaco) {
    monaco.languages.register({ id: 'wast' });

    monaco.languages.setLanguageConfiguration('wast', {
        comments: {
		    lineComment: ';;',
		    blockComment: ['\\(;', ';\\)'],
        },
        brackets: [
            ['(', ')']
        ],
        autoClosingPairs: [
            { open: '(', close: ')' },
            { open: '"', close: '"' }
        ],
        surroundingPairs: [
            { open: '(', close: ')' },
            { open: '"', close: '"' }
        ]
    });

    monaco.languages.setMonarchTokensProvider('wast', {

        tokenPostfix: '.wast',

        keywords: [
            "module",
            "type",
            "memory",
            "data",
            "export",
            "import",
            "func",
            "struct",
            "start",
            "table",
            "elem",
            "element",
            "global",
            "mut",
            "local",
            "param",
            "result",
            "offset",
            "code",
            "segment",
            "invoke",
            "label",
            "binary",

            // Control
            "unreachable",
            "nop",
            "block",
            "loop",
            "if",
            "else",
            "end",
            "br",
            "br_if",
            "br_table",
            "return",

            // Call
            "call",
            "call_indirect",
            "call_import"
        ],

        types: [
            "i32",
            "i64",
            "f32",
            "f64",
            "anyfunc",
            "func",
            "void"
        ],

        operations: [
            // Parametric
            "drop",
            "select",

            // Variable access
            "get_local",
            "set_local",
            "tee_local",
            "get_global",
            "set_global",

            // Memory related
            "load",
            "load8_s",
            "load8_u",
            "load16_s",
            "load16_u",
            "load32_s",
            "load32_u",
            "store",
            "store8",
            "store16",
            "store32",
            "current_memory",
            "grow_memory",

            // Constants
            "const",

            // Comparison
            "eqz",
            "eq",
            "ne",
            "lt_s",
            "lt_u",
            "lt",
            "gt_s",
            "gt_u",
            "gt",
            "le_s",
            "le_u",
            "le",
            "ge_s",
            "ge_u",
            "ge",

            // Numeric
            "clz",
            "ctz",
            "popcnt",
            "add",
            "sub",
            "mul",
            "div_s",
            "div_u",
            "div",
            "rem_s",
            "rem_u",
            "and",
            "xor",
            "or",
            "shl",
            "shr_s",
            "shr_u",
            "rotl",
            "rotr",
            "abs",
            "neg",
            "ceil",
            "floor",
            "trunc",
            "nearest",
            "sqrt",
            "min",
            "max",
            "copysign",

            // Conversion
            "wrap",
            "trunc_s",
            "trunc_u",
            "extend_s",
            "extend_u",
            "convert_s",
            "convert_u",
            "demote",
            "promote",

            // Reinterpretations
            "reinterpret",

            // Misc
            "tableswitch",
            "has_feature",

            // Assertion
            "failure",
            "assert_invalid",
            "assert_trap",
            "assert_return",
            "assert_return_nan",
            "assert_return_arithmetic_nan",
            "assert_return_canonical_nan",
            "assert_unlinkable"
        ],

        escapes:      /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
        digits:       /\d+(_+\d+)*/,
        octaldigits:  /[0-7]+(_+[0-7]+)*/,
        binarydigits: /[0-1]+(_+[0-1]+)*/,
        hexdigits:    /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,

    	tokenizer: {
    		root: [
                { include: '@whitespace' },

                [/"([^"\\]|\\.)*$/, 'string.invalid'],
                [/"/, 'string', '@string'],

                [/(@digits)[eE]([+\-]?(@digits))?[fFdD]?/, 'number.float'],
                [/(@digits)\.(@digits)([eE][+\-]?(@digits))?[fFdD]?/, 'number.float'],
                [/0[xX](@hexdigits)[Ll]?/, 'number.hex'],
                [/0(@octaldigits)[Ll]?/, 'number.octal'],
                [/0[bB](@binarydigits)[Ll]?/, 'number.binary'],
                [/(@digits)[fFdD]/, 'number.float'],
                [/(@digits)[lL]?/, 'number'],
                [/[+\-]?(infinity|inf|nan)/, 'constant.number'],

                [/\./, 'punctuation.separator.dot'],

                [/\$[^\s"\(\)\{\}\[\]]+/, { token: 'variable' }],

                [/[a-zA-Z_$][\w$]*/, {
                    cases: {
                        '@keywords':   { token: 'keyword.$0' },
                        '@types':      { token: 'entity.name.type.class.$0' },
                        '@operations': { token: 'keyword.operator.$0' },
                        '@default':    'identifier'
                    }
                }]
            ],

            string: [
                [/[^\\"]+/,  'string'],
                [/@escapes/, 'string.escape'],
                [/\\./,      'string.escape.invalid'],
                [/"/,        'string', '@pop']
            ],

            whitespace: [
                [/[ \t\r\n]+/,           ''],
                [/(^;{2}.*$)/,           'comment.line'],
                [/(^\(;[\n\t\r\w]+;\))/, 'comment.block']
            ],

            comment: [
                [/(;{2})(.*)$/, 'comment.line']
            ]
        }
    });
}
<|endoftext|>


<commit_before>
// returns the map provider for a given TileStache layer name
function getProvider(layer) {
    return new MM.StamenTileLayer(layer);
}

// cancels all double-click events on the supplied element
function preventDoubleClick(el) {
    MM.addEvent(el, "dblclick", function(e) {
        return MM.cancelEvent(e);
    });
}

// set up zoom controls for the given map (assumed one per page,
// with in and out buttons having ids "zoom-in" and "zoom-out", respectively
function setupZoomControls(map) {
    var zoomIn = document.getElementById("zoom-in"),
        zoomOut = document.getElementById("zoom-out");

    preventDoubleClick(zoomIn);
    MM.addEvent(zoomIn, "click", function(e) {
        try { map.zoomIn(); } catch (err) { }
        return MM.cancelEvent(e);
    });
    preventDoubleClick(zoomOut);
    MM.addEvent(zoomOut, "click", function(e) {
        try { map.zoomOut(); } catch (err) { }
        return MM.cancelEvent(e);
    });

}

function syncMapLinks(map, links, modifyHashParts) {
    var len = links.length,
        timeout,
        delay = 200;
    function formatHash() {
        var center = map.getCenter(),
            zoom = map.getZoom(),
            precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)),
            parts = [zoom,
                center.lat.toFixed(precision),
                center.lon.toFixed(precision)
            ];
        if (modifyHashParts) {
            modifyHashParts.call(null, parts);
        }
        return parts.join("/");
    }
    map.addCallback("drawn", function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            var hash = formatHash();
            for (var i = 0; i < len; i++) {
                var link = links[i],
                    href = link.href || "",
                    uri = link.href.split("#").shift();
                link.href = [uri, hash].join("#");
            }
        }, delay);
    });
}

// get the pixel offset of an element from the top left of its offset parent
function getOffset(el) {
    var offset = {left: 0, top: 0},
        offsetParent = el.offsetParent;
    while (el && el != offsetParent) {
        offset.left += el.offsetLeft;
        offset.top += el.offsetTop;
        el = el.parentNode;
    }
    return offset;
}

// create a toggling interface
function createToggle(link, target, callback) {
    var showing = target.style.display != "none",
        originalClass = link.className,
        toggler = function(s) {
            showing = s;
            if (showing) {
                target.style.display = "";
                link.className = [originalClass, "active"].join(" ");
            } else {
                target.style.display = "none";
                link.className = originalClass;
            }
            callback.call(target, showing);
        };

    MM.addEvent(link, "click", function(e) {
        toggler.toggle();
        return MM.cancelEvent(e);
    });

    toggler.toggle = function() { toggler(!showing); };
    toggler.show = function() { toggler(true); };
    toggler.hide = function() { toggler(false); };

    return toggler;
}

// add browser-specific classes to the given element
var addBrowserClasses = (function() {
    var ua = navigator.userAgent,
        matches = {
            ie: ua.match(/MSIE\s([^;]*)/) ? true : false,
            ios: ua.match(/like Mac OS X/i) ? true : false,
            iphone: ua.match(/iPhone/i) ? true : false,
            ipad: ua.match(/iPad/i) ? true : false,
            firefox: ua.match(/Firefox/i) ? true : false,
            webkit: ua.match(/WebKit/i) ? true : false,
            safari: ua.match(/Safari/i) ? true : false,
            chrome: ua.match(/Chrome/i) ? true : false,
            opera: ua.match(/Opera/i) ? true : false
        },
        classes = [];
    for (var klass in matches) {
        if (matches[klass]) classes.push(klass);
    }
    classes = classes.join(" ");
    return function(el) {
        el.className = el.className
            ? [el.className, classes].join(" ")
            : classes;
    };
})();

// a simple Yahoo! Place Search API
var YahooPlaceSearch = {
    appid: "1DiQEyLV34HbAVHyl0iWC5tAZ8wpLMPzIeFE9QsTukhx6H.Cn9bM70c_5dYgh7cR8w--",
    url: "http://where.yahooapis.com/v1/places.q({q});count=1?callback=?",
    geocode: function(query, success, error) {
        var data = {};
        data.appid = YahooPlaceSearch.appid;
        data.select = "long";
        data.format = "json";
        return reqwest({
            url: YahooPlaceSearch.url.replace("{q}", encodeURIComponent(query)),
            type: "jsonp",
            jsonpCallback: "callback",
            data: data,
            success: function(response) {
                var results = response.places;
                if (results) {
                    success.call(null, results);
                } else {
                    error.call(null, "No results", response);
                }
            },
            error: error
        });
    }
};

var QueryString = function(params) {
    if (params) {
        if (typeof params === "string") {
            params = this.parse(params);
        }
    }
    this.params = params || {};
};

QueryString.parse = function(str) {
    if (str.charAt(0) === "?") {
        str = str.substr(1);
    }
    var parts = str.split("&"),
        len = parts.length;
        params = {};
    for (var i = 0; i < len; i++) {
        var kv = parts[i].split("=");
        params[decodeURIComponent(kv[0])] = (kv.length === 2)
            ? decodeURIComponent(kv[1])
            : true;
    }
    return params;
};

QueryString.format = function(params) {
    var parts = [],
        i = 0;
    for (var key in params) {
        if (i++ > 0) parts.push("&");
        var value = params[key];
        if (value !== null) {
            parts.push(encodeURIComponent(key), "=", encodeURIComponent(value));
        }
    }
    return parts.join("");
};

QueryString.prototype = {
    clear: function() {
        this.params = {};
    },
    parse: function(str) {
        var parsed = QueryString.parse(str);
        return this.update(parsed);
    },
    update: function(params) {
        var old = this.params;
        this.params = {};
        var changed = {};
        for (var key in params) {
            var value = params[key];
            if (old[key] != value) {
                changed[key] = value;
            }
            this.params[key] = value;
        }
        return changed;
    },
    toString: function() {
        var str = QueryString.format(this.params);
        return str.length ? "?" + str : "";
    }
};

MM.QueryHash = function(map, onQueryChange) {
    this.query = new QueryString();
    this.onQueryChange = onQueryChange;
    MM.Hash.call(this, map);
};

MM.QueryHash.prototype = {
    query: null,
    parseHash: function(hash) {
        var qs = "";
        if (hash.indexOf("?") > -1) {
            var parts = hash.split("?");
            hash = parts[0];
            qs = parts[1];
        }
        var parsed = MM.Hash.prototype.parseHash.call(this, hash);
        if (parsed) {
            this.query.params = this.onQueryChange.call(this, this.query.parse(qs));
        }
        return parsed;
    },
    formatHash: function(hash) {
        return MM.Hash.prototype.formatHash.call(this, hash) + this.query.toString();
    }
};

MM.extend(MM.QueryHash, MM.Hash);

/**
 * The ProviderHash is a class that looks for a provider name at the beginning
 * of the hash and calls the supplied setProvider(provider) function whenever it
 * changes.
 *
 * One feature of this parser is that it substitutes the center and zoom back in
 * if the hash changes to just "#provider", so you can link to new providers by
 * setting a link's href to simply "#provider" and ProviderHash will update the
 * hash accordingly.
 *
 * setProvider(provider) should accept a string and return true if the supplied
 * provider name was valid, or return false in any other case.
 *
 * Note also that ProviderHash requires a valid providerName in the constructor
 * to correctly set the initial hash value.
 */
var ProviderHash = function(map, providerName, setProvider) {
    this.providerName = providerName;
    this.setProvider = setProvider;
    MM.Hash.call(this, map);
};

ProviderHash.prototype = {
    // the currently selected provider name
    providerName: null,

    /**
     * Our parseHash() function looks for a provider name in the beginning of
     * the URL.
     */
    parseHash: function(hash) {
        var parts = hash.split("/");
        if (parts.length > 0) {
            // ignore the trailing slash
            if (parts[parts.length - 1] === "") {
                parts.pop();
            }
            var provider = parts.shift();
            var parsed = parts.length
                ? MM.Hash.prototype.parseHash.call(this, parts.join("/"))
                : {center: this.map.getCenter(), zoom: this.map.getZoom()};
            if (parsed) {
                // console.log("parsed hash:", provider, parsed);
                var didSetProvider = this.setProvider.call(this.map, provider);
                if (didSetProvider) {
                    this.providerName = provider;
                    return parsed;
                } else {
                    return false;
                }
            } else {
                // console.log("parse error:", hash, parts, this.providerName);
            }
            return parsed;
        } else {
            // console.warn("(zero length, unable to parse");
            return false;
        }
    },

    /**
     * Our formatHash() function inserts the provider name as the first
     * slash-delimited element in the URL.
     */
    formatHash: function(hash) {
        var format = MM.Hash.prototype.formatHash.call(this, hash);
        return "#" + this.providerName + "/" + format.substr(1);
    }
};

MM.extend(ProviderHash, MM.Hash);
<commit_msg>added track()<commit_after>
// returns the map provider for a given TileStache layer name
function getProvider(layer) {
    return new MM.StamenTileLayer(layer);
}

// cancels all double-click events on the supplied element
function preventDoubleClick(el) {
    MM.addEvent(el, "dblclick", function(e) {
        return MM.cancelEvent(e);
    });
}

// set up zoom controls for the given map (assumed one per page,
// with in and out buttons having ids "zoom-in" and "zoom-out", respectively
function setupZoomControls(map) {
    var zoomIn = document.getElementById("zoom-in"),
        zoomOut = document.getElementById("zoom-out");

    preventDoubleClick(zoomIn);
    MM.addEvent(zoomIn, "click", function(e) {
        try { map.zoomIn(); } catch (err) { }
        return MM.cancelEvent(e);
    });
    preventDoubleClick(zoomOut);
    MM.addEvent(zoomOut, "click", function(e) {
        try { map.zoomOut(); } catch (err) { }
        return MM.cancelEvent(e);
    });

}

function syncMapLinks(map, links, modifyHashParts) {
    var len = links.length,
        timeout,
        delay = 200;
    function formatHash() {
        var center = map.getCenter(),
            zoom = map.getZoom(),
            precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2)),
            parts = [zoom,
                center.lat.toFixed(precision),
                center.lon.toFixed(precision)
            ];
        if (modifyHashParts) {
            modifyHashParts.call(null, parts);
        }
        return parts.join("/");
    }
    map.addCallback("drawn", function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            var hash = formatHash();
            for (var i = 0; i < len; i++) {
                var link = links[i],
                    href = link.href || "",
                    uri = link.href.split("#").shift();
                link.href = [uri, hash].join("#");
            }
        }, delay);
    });
}

// get the pixel offset of an element from the top left of its offset parent
function getOffset(el) {
    var offset = {left: 0, top: 0},
        offsetParent = el.offsetParent;
    while (el && el != offsetParent) {
        offset.left += el.offsetLeft;
        offset.top += el.offsetTop;
        el = el.parentNode;
    }
    return offset;
}

// create a toggling interface
function createToggle(link, target, callback) {
    var showing = target.style.display != "none",
        originalClass = link.className,
        toggler = function(s) {
            showing = s;
            if (showing) {
                target.style.display = "";
                link.className = [originalClass, "active"].join(" ");
            } else {
                target.style.display = "none";
                link.className = originalClass;
            }
            callback.call(target, showing);
        };

    MM.addEvent(link, "click", function(e) {
        toggler.toggle();
        return MM.cancelEvent(e);
    });

    toggler.toggle = function() { toggler(!showing); };
    toggler.show = function() { toggler(true); };
    toggler.hide = function() { toggler(false); };

    return toggler;
}

// add browser-specific classes to the given element
var addBrowserClasses = (function() {
    var ua = navigator.userAgent,
        matches = {
            ie: ua.match(/MSIE\s([^;]*)/) ? true : false,
            ios: ua.match(/like Mac OS X/i) ? true : false,
            iphone: ua.match(/iPhone/i) ? true : false,
            ipad: ua.match(/iPad/i) ? true : false,
            firefox: ua.match(/Firefox/i) ? true : false,
            webkit: ua.match(/WebKit/i) ? true : false,
            safari: ua.match(/Safari/i) ? true : false,
            chrome: ua.match(/Chrome/i) ? true : false,
            opera: ua.match(/Opera/i) ? true : false
        },
        classes = [];
    for (var klass in matches) {
        if (matches[klass]) classes.push(klass);
    }
    classes = classes.join(" ");
    return function(el) {
        el.className = el.className
            ? [el.className, classes].join(" ")
            : classes;
    };
})();

// a simple Yahoo! Place Search API
var YahooPlaceSearch = {
    appid: "1DiQEyLV34HbAVHyl0iWC5tAZ8wpLMPzIeFE9QsTukhx6H.Cn9bM70c_5dYgh7cR8w--",
    url: "http://where.yahooapis.com/v1/places.q({q});count=1?callback=?",
    geocode: function(query, success, error) {
        var data = {};
        data.appid = YahooPlaceSearch.appid;
        data.select = "long";
        data.format = "json";
        return reqwest({
            url: YahooPlaceSearch.url.replace("{q}", encodeURIComponent(query)),
            type: "jsonp",
            jsonpCallback: "callback",
            data: data,
            success: function(response) {
                var results = response.places;
                if (results) {
                    success.call(null, results);
                } else {
                    error.call(null, "No results", response);
                }
            },
            error: error
        });
    }
};

var QueryString = function(params) {
    if (params) {
        if (typeof params === "string") {
            params = this.parse(params);
        }
    }
    this.params = params || {};
};

QueryString.parse = function(str) {
    if (str.charAt(0) === "?") {
        str = str.substr(1);
    }
    var parts = str.split("&"),
        len = parts.length;
        params = {};
    for (var i = 0; i < len; i++) {
        var kv = parts[i].split("=");
        params[decodeURIComponent(kv[0])] = (kv.length === 2)
            ? decodeURIComponent(kv[1])
            : true;
    }
    return params;
};

QueryString.format = function(params) {
    var parts = [],
        i = 0;
    for (var key in params) {
        if (i++ > 0) parts.push("&");
        var value = params[key];
        if (value !== null) {
            parts.push(encodeURIComponent(key), "=", encodeURIComponent(value));
        }
    }
    return parts.join("");
};

QueryString.prototype = {
    clear: function() {
        this.params = {};
    },
    parse: function(str) {
        var parsed = QueryString.parse(str);
        return this.update(parsed);
    },
    update: function(params) {
        var old = this.params;
        this.params = {};
        var changed = {};
        for (var key in params) {
            var value = params[key];
            if (old[key] != value) {
                changed[key] = value;
            }
            this.params[key] = value;
        }
        return changed;
    },
    toString: function() {
        var str = QueryString.format(this.params);
        return str.length ? "?" + str : "";
    }
};

MM.QueryHash = function(map, onQueryChange) {
    this.query = new QueryString();
    this.onQueryChange = onQueryChange;
    MM.Hash.call(this, map);
};

MM.QueryHash.prototype = {
    query: null,
    parseHash: function(hash) {
        var qs = "";
        if (hash.indexOf("?") > -1) {
            var parts = hash.split("?");
            hash = parts[0];
            qs = parts[1];
        }
        var parsed = MM.Hash.prototype.parseHash.call(this, hash);
        if (parsed) {
            this.query.params = this.onQueryChange.call(this, this.query.parse(qs));
        }
        return parsed;
    },
    formatHash: function(hash) {
        return MM.Hash.prototype.formatHash.call(this, hash) + this.query.toString();
    }
};

MM.extend(MM.QueryHash, MM.Hash);

/**
 * The ProviderHash is a class that looks for a provider name at the beginning
 * of the hash and calls the supplied setProvider(provider) function whenever it
 * changes.
 *
 * One feature of this parser is that it substitutes the center and zoom back in
 * if the hash changes to just "#provider", so you can link to new providers by
 * setting a link's href to simply "#provider" and ProviderHash will update the
 * hash accordingly.
 *
 * setProvider(provider) should accept a string and return true if the supplied
 * provider name was valid, or return false in any other case.
 *
 * Note also that ProviderHash requires a valid providerName in the constructor
 * to correctly set the initial hash value.
 */
var ProviderHash = function(map, providerName, setProvider) {
    this.providerName = providerName;
    this.setProvider = setProvider;
    MM.Hash.call(this, map);
};

ProviderHash.prototype = {
    // the currently selected provider name
    providerName: null,

    /**
     * Our parseHash() function looks for a provider name in the beginning of
     * the URL.
     */
    parseHash: function(hash) {
        var parts = hash.split("/");
        if (parts.length > 0) {
            // ignore the trailing slash
            if (parts[parts.length - 1] === "") {
                parts.pop();
            }
            var provider = parts.shift();
            var parsed = parts.length
                ? MM.Hash.prototype.parseHash.call(this, parts.join("/"))
                : {center: this.map.getCenter(), zoom: this.map.getZoom()};
            if (parsed) {
                // console.log("parsed hash:", provider, parsed);
                var didSetProvider = this.setProvider.call(this.map, provider);
                if (didSetProvider) {
                    this.providerName = provider;
                    return parsed;
                } else {
                    return false;
                }
            } else {
                // console.log("parse error:", hash, parts, this.providerName);
            }
            return parsed;
        } else {
            // console.warn("(zero length, unable to parse");
            return false;
        }
    },

    /**
     * Our formatHash() function inserts the provider name as the first
     * slash-delimited element in the URL.
     */
    formatHash: function(hash) {
        var format = MM.Hash.prototype.formatHash.call(this, hash);
        return "#" + this.providerName + "/" + format.substr(1);
    }
};

MM.extend(ProviderHash, MM.Hash);

// Google Analytics tracking
function track() {
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-32986126-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
}
<|endoftext|>


<commit_before>$(function() {

	CMS.init({

		// Name of your site or location of logo file ,relative to root directory (img/logo.png)
		siteName: 'Recursos',

		// Tagline for your site
		siteTagline: 'para aprender',

		// Email address
		siteEmail: 'GersonLazaro@GersonLazaro.com',

		// Name
		siteAuthor: 'Gerson Lázaro',

		// Navigation items
		siteNavItems: [
			{ name: 'Github', href: 'https://github.com/GersonLazaro', newWindow: true},
			{ name: 'About'},
			{ name: 'Libros'},
			{ name: 'Cursos'},
			{ name: 'Otros'}
		],

		// Posts folder name
		postsFolder: 'posts',

		// Homepage posts snippet length
		postSnippetLength: 120,

		// Pages folder name
		pagesFolder: 'pages',

		// Site fade speed
		fadeSpeed: 300,

		// Site footer text
		footerText: 'Gerson Lázaro © ' + new Date().getFullYear(),

		// Mode 'Github' for Github Pages, 'Apache' for Apache server. Defaults
		// to Github
		mode: 'Github',

		// If Github mode is set, your Github username and repo name. Defaults
		// to Github pages branch (gh-pages)
		githubUserSettings: {
			username: 'GersonLazaro',
			repo: 'recursos-para-aprender'
		}

	});

	// Markdown settings
	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: true,
		tables: true,
		breaks: false,
		pedantic: false,
		sanitize: true,
		smartLists: true,
		smartypants: false
	});

});
<commit_msg>Corrección error sintáctico<commit_after>$(function() {

	CMS.init({

		// Name of your site or location of logo file ,relative to root directory (img/logo.png)
		siteName: 'Recursos',

		// Tagline for your site
		siteTagline: 'para aprender',

		// Email address
		siteEmail: 'GersonLazaro@GersonLazaro.com',

		// Name
		siteAuthor: 'Gerson Lázaro',

		// Navigation items
		siteNavItems: [
			{ name: 'Github', href: 'https://github.com/GersonLazaro', newWindow: false},
			{ name: 'About'},
			{ name: 'Libros'},
			{ name: 'Cursos'},
			{ name: 'Otros'},
		],

		// Posts folder name
		postsFolder: 'posts',

		// Homepage posts snippet length
		postSnippetLength: 120,

		// Pages folder name
		pagesFolder: 'pages',

		// Site fade speed
		fadeSpeed: 300,

		// Site footer text
		footerText: 'Gerson Lázaro © ' + new Date().getFullYear(),

		// Mode 'Github' for Github Pages, 'Apache' for Apache server. Defaults
		// to Github
		mode: 'Github',

		// If Github mode is set, your Github username and repo name. Defaults
		// to Github pages branch (gh-pages)
		githubUserSettings: {
			username: 'GersonLazaro',
			repo: 'recursos-para-aprender'
		}

	});

	// Markdown settings
	marked.setOptions({
		renderer: new marked.Renderer(),
		gfm: true,
		tables: true,
		breaks: false,
		pedantic: false,
		sanitize: true,
		smartLists: true,
		smartypants: false
	});

});
<|endoftext|>


<commit_before>configReactDriveCms = {
    author: 'Andrew Henderson',
    /**
     * Add the Id for the Google Sheets Dashboard file
     */
    dashboardId: '1hBDOdFlc6OmQI5gKIkpGsNtbRTgpubM5EBH2qUK9EOU',
    /**
     * Add the Url Id for the Google Web App Script to forward email from the Contact Form
     */
    sendMailUrlId: 'THE-URL-ID-TO-YOUR-GOOGLE-APPS-SCRIPT-PUBLISHED-WEB-APP',
    /**
     * Add your Disqus shortname
     */
    shortname: 'your-disqus-shortname'
};<commit_msg>fixed dshboard sheet id<commit_after>configReactDriveCms = {
    author: 'Andrew Henderson',
    /**
     * Add the Id for the Google Sheets Dashboard file
     */
    dashboardId: 'd/1hBDOdFlc6OmQI5gKIkpGsNtbRTgpubM5EBH2qUK9EOU',
    /**
     * Add the Url Id for the Google Web App Script to forward email from the Contact Form
     */
    sendMailUrlId: 'THE-URL-ID-TO-YOUR-GOOGLE-APPS-SCRIPT-PUBLISHED-WEB-APP',
    /**
     * Add your Disqus shortname
     */
    shortname: 'your-disqus-shortname'
};<|endoftext|>


<commit_before>/*
 *** CUSTOM JS ***
*/

// Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
// Only enable it if you actually need to.
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);

// Append the canvas element created by the renderer to document body element.
document.body.appendChild(renderer.domElement);

// Create a three.js scene.
var scene = new THREE.Scene();

// Create a three.js camera.
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

var controls = new THREE.VRControls(camera);
controls.standing = true; //raise user above ground

/*** VR Controls ***/
// https://github.com/brianpeiris/three-firstperson-vr-controls
// https://brian.peiris.io/three-firstperson-vr-controls/demo/
// Create VRControls in addition to FirstPersonVRControls.
var vrControls = new THREE.VRControls(camera);
//vrControls.standing = true;
var fpVrControls = new THREE.FirstPersonVRControls(camera, scene);
// Optionally enable vertical movement.
fpVrControls.verticalMovement = true;
fpVrControls.movementSpeed = 5; //normal
fpVrControls.movementSpeed = 10;

// Apply VR stereo rendering to renderer.
var effect = new THREE.VREffect(renderer);
effect.setSize(window.innerWidth, window.innerHeight);

// Add a repeating grid as a skybox.
var boxSize = 40;
//var boxSize = 20;
var loader = new THREE.TextureLoader();
loader.load('img/box.png', onTextureLoaded);
//loader.load('assets/textures/crate.gif', onTextureLoaded);
//loader.load('assets/mc-textures/leaves_big_oak_opaque.png', onTextureLoaded);
var dirt_texture = new THREE.TextureLoader().load( "assets/textures/dirt.png" );

/* see: https://threejs.org/docs/api/textures/Texture.html */
function onTextureLoaded(texture) {
  //texture.wrapS = THREE.RepeatWrapping;
  //texture.wrapT = THREE.RepeatWrapping;
  //texture.repeat.set(boxSize, boxSize);
  //texture.repeat.set( 5, 5 ); //how many times the texture is repeated across the surface, in each direction U and V

  var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
  var material = new THREE.MeshBasicMaterial({
    map: dirt_texture,
    //map: texture,
    color: 0x01BE00,
    //side: THREE.BackSide //inside
    //side: THREE.FrontSide //outsiWde (nothing / default)
    side: THREE.DoubleSide //both
  });

  // Align the skybox to the floor (which is at y=0).
  skybox = new THREE.Mesh(geometry, material);
  //skybox.position.y = boxSize/2;
  skybox.position.y = 2.5; //grid box way above
  //scene.add(skybox);

  // For high end VR devices like Vive and Oculus, take into account the stage parameters provided.
  setupStage();
}

///////////
// FLOOR //
///////////
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
//var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/dirt.png' );
//floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
//floor.position.y = -0.5;
floor.position.y = -4.8; //lower = floor lowers
floor.rotation.x = Math.PI / 2; // 1.57
scene.add(floor);

///////////
// WALL //
///////////
var wall_y_pos = -2.3;
//var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/wall.png' );
wallTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var wallMaterial = new THREE.MeshBasicMaterial( { map: wallTexture, side: THREE.DoubleSide } );
var wallGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
//var wallGeometry = new THREE.PlaneGeometry(600, 40, 1, 1); // extended
var wall1 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall2 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall3 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall4 = new THREE.Mesh(wallGeometry, wallMaterial);
//floor.position.y = -0.5;
/* Front Wall */
wall1.position.x = 0;
wall1.position.y = wall_y_pos;
wall1.position.z = -15; //further away
var wall_rotation = 0.01;
console.log(wall_rotation);
//wall1.rotation.x = wall_rotation;
scene.add(wall1);
/* Back Wall */
wall2.position.x = 0;
wall2.position.y = wall_y_pos;
wall2.position.z = 15; //further away
//wall2.rotation.x = wall_rotation;
scene.add(wall2);
/* Left Side Wall */
wall3.position.x = -15;
wall3.position.y = wall_y_pos;
wall3.position.z = 0; //further away
//wall3.rotation.x = wall_rotation;
//wall3.rotation.y = 2;
wall3.rotation.y = Math.PI / 2;
scene.add(wall3);
/* Right Side Wall */
wall4.position.x = 15;
wall4.position.y = wall_y_pos;
wall4.position.z = 0; //further away
wall4.rotation.y = Math.PI / 2;
scene.add(wall4);

// Create a VR manager helper to enter and exit VR mode.
var params = {
  hideButton: false, // Default: false.
  isUndistorted: false // Default: false.
};
var manager = new WebVRManager(renderer, effect, params);

/////////////
// OBJECTS //
/////////////
// Create 3D objects.
var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
var sign = new THREE.Mesh(geometry, material);
//cube.position.set(0, controls.userHeight, -1);
cube.position.set(0, 3.5, -1); //move cube higher
scene.add(cube);
//sign.position.set(-2.25, 0.25, -2.5); //left-right, top-down, forward-back
sign.position.set(-4.75, 0.25, -4.75); //left-right, top-down, forward-back
scene.add(sign);

///////////
// SOUND //
///////////
var listener = new THREE.AudioListener();
camera.add( listener );

// sound spheres
//var sphere = new THREE.SphereGeometry( 5, 8, 4 );
var sphere = new THREE.SphereGeometry( 2.5, 4, 2 );
material_sphere1 = new THREE.MeshPhongMaterial( { color: 0xffaa00, shading: THREE.FlatShading, shininess: 0 } );

var audioLoader = new THREE.AudioLoader();

var mesh1 = new THREE.Mesh( sphere, material_sphere1 );
mesh1.position.set(0, 2.5, -40);
//mesh1.position.set(0, 2.5, -20);
//mesh1.position.set(-4.75, 0.25, -4.75);
scene.add( mesh1 );

var sound1 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/358232_j_s_song.ogg', function( buffer ) {
  sound1.setBuffer( buffer );
  //sound1.setRefDistance( 20 ); //higher = louder
  sound1.setRefDistance( 5 );
  sound1.play();
});
mesh1.add( sound1 );

///////////////////
// LIGHT / MODEL //
///////////////////
var ambient = new THREE.AmbientLight( 0x444444 );
//var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );

var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );

var onProgress = function ( xhr ) {
  if ( xhr.lengthComputable ) {
    var percentComplete = xhr.loaded / xhr.total * 100;
    console.log( Math.round(percentComplete, 2) + '% downloaded' );
  }
};

var onError = function ( xhr ) { };

THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'assets/models/ganondorf/' );
mtlLoader.load( 'model.mtl', function( materials ) {

  materials.preload();

  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials( materials );
  objLoader.setPath( 'assets/models/ganondorf/' );
  objLoader.load( 'model.obj', function ( object ) {

    //object.scale.set(0.4, 0.4, 0.4);
    object.scale.set(0.5, 0.5, 0.5);
    //object.position.y = - 95;
    //object.position.set(0, 0, -5);
    object.position.set(0, -4.5, -5); //ganondorf on ground

    //object.material.emissive = new THREE.Color( 0.2, 0.2, 0.2 );

    scene.add( object );

  }, onProgress, onError );

});

window.addEventListener('resize', onResize, true);
window.addEventListener('vrdisplaypresentchange', onResize, true);

// Request animation frame loop function
var lastRender = 0;
function animate(timestamp) {
  var delta = Math.min(timestamp - lastRender, 500);
  lastRender = timestamp;

  // Apply rotation to cube mesh
  cube.rotation.y += delta * 0.0006;

  controls.update();
  // Render the scene through the manager.

  // Update FirstPersonControls after VRControls.
  // FirstPersonControls requires a timestamp.
  vrControls.update();
  fpVrControls.update(timestamp);

  manager.render(scene, camera, timestamp);
  effect.render(scene, camera);

  vrDisplay.requestAnimationFrame(animate);
}

function onResize(e) {
  effect.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}

var vrDisplay;

// Get the HMD, and if we're dealing with something that specifies stageParameters, rearrange the scene.
function setupStage() {
  navigator.getVRDisplays().then(function(displays) {
    if (displays.length > 0) {
      vrDisplay = displays[0];
      if (vrDisplay.stageParameters) {
        setStageDimensions(vrDisplay.stageParameters);
      }
      vrDisplay.requestAnimationFrame(animate);
    }
  });
}

function setStageDimensions(stage) {
  /* not sure what this does... */
  // Make the skybox fit the stage.
  var material = skybox.material;
  scene.remove(skybox);

  // Size the skybox according to the size of the actual stage.
  var geometry = new THREE.BoxGeometry(stage.sizeX, boxSize, stage.sizeZ);
  skybox = new THREE.Mesh(geometry, material);

  // Place it on the floor.
  skybox.position.y = boxSize/2;
  scene.add(skybox);

  // Place the cube in the middle of the scene, at user height.
  cube.position.set(0, controls.userHeight, 0);
}<commit_msg>adjust song volume<commit_after>/*
 *** CUSTOM JS ***
*/

// Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
// Only enable it if you actually need to.
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);

// Append the canvas element created by the renderer to document body element.
document.body.appendChild(renderer.domElement);

// Create a three.js scene.
var scene = new THREE.Scene();

// Create a three.js camera.
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

var controls = new THREE.VRControls(camera);
controls.standing = true; //raise user above ground

/*** VR Controls ***/
// https://github.com/brianpeiris/three-firstperson-vr-controls
// https://brian.peiris.io/three-firstperson-vr-controls/demo/
// Create VRControls in addition to FirstPersonVRControls.
var vrControls = new THREE.VRControls(camera);
//vrControls.standing = true;
var fpVrControls = new THREE.FirstPersonVRControls(camera, scene);
// Optionally enable vertical movement.
fpVrControls.verticalMovement = true;
fpVrControls.movementSpeed = 5; //normal
fpVrControls.movementSpeed = 10;

// Apply VR stereo rendering to renderer.
var effect = new THREE.VREffect(renderer);
effect.setSize(window.innerWidth, window.innerHeight);

// Add a repeating grid as a skybox.
var boxSize = 40;
//var boxSize = 20;
var loader = new THREE.TextureLoader();
loader.load('img/box.png', onTextureLoaded);
//loader.load('assets/textures/crate.gif', onTextureLoaded);
//loader.load('assets/mc-textures/leaves_big_oak_opaque.png', onTextureLoaded);
var dirt_texture = new THREE.TextureLoader().load( "assets/textures/dirt.png" );

/* see: https://threejs.org/docs/api/textures/Texture.html */
function onTextureLoaded(texture) {
  //texture.wrapS = THREE.RepeatWrapping;
  //texture.wrapT = THREE.RepeatWrapping;
  //texture.repeat.set(boxSize, boxSize);
  //texture.repeat.set( 5, 5 ); //how many times the texture is repeated across the surface, in each direction U and V

  var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
  var material = new THREE.MeshBasicMaterial({
    map: dirt_texture,
    //map: texture,
    color: 0x01BE00,
    //side: THREE.BackSide //inside
    //side: THREE.FrontSide //outsiWde (nothing / default)
    side: THREE.DoubleSide //both
  });

  // Align the skybox to the floor (which is at y=0).
  skybox = new THREE.Mesh(geometry, material);
  //skybox.position.y = boxSize/2;
  skybox.position.y = 2.5; //grid box way above
  //scene.add(skybox);

  // For high end VR devices like Vive and Oculus, take into account the stage parameters provided.
  setupStage();
}

///////////
// FLOOR //
///////////
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
//var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/dirt.png' );
//floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
//floor.position.y = -0.5;
floor.position.y = -4.8; //lower = floor lowers
floor.rotation.x = Math.PI / 2; // 1.57
scene.add(floor);

///////////
// WALL //
///////////
var wall_y_pos = -2.3;
//var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/wall.png' );
wallTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var wallMaterial = new THREE.MeshBasicMaterial( { map: wallTexture, side: THREE.DoubleSide } );
var wallGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
//var wallGeometry = new THREE.PlaneGeometry(600, 40, 1, 1); // extended
var wall1 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall2 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall3 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall4 = new THREE.Mesh(wallGeometry, wallMaterial);
//floor.position.y = -0.5;
/* Front Wall */
wall1.position.x = 0;
wall1.position.y = wall_y_pos;
wall1.position.z = -15; //further away
var wall_rotation = 0.01;
console.log(wall_rotation);
//wall1.rotation.x = wall_rotation;
scene.add(wall1);
/* Back Wall */
wall2.position.x = 0;
wall2.position.y = wall_y_pos;
wall2.position.z = 15; //further away
//wall2.rotation.x = wall_rotation;
scene.add(wall2);
/* Left Side Wall */
wall3.position.x = -15;
wall3.position.y = wall_y_pos;
wall3.position.z = 0; //further away
//wall3.rotation.x = wall_rotation;
//wall3.rotation.y = 2;
wall3.rotation.y = Math.PI / 2;
scene.add(wall3);
/* Right Side Wall */
wall4.position.x = 15;
wall4.position.y = wall_y_pos;
wall4.position.z = 0; //further away
wall4.rotation.y = Math.PI / 2;
scene.add(wall4);

// Create a VR manager helper to enter and exit VR mode.
var params = {
  hideButton: false, // Default: false.
  isUndistorted: false // Default: false.
};
var manager = new WebVRManager(renderer, effect, params);

/////////////
// OBJECTS //
/////////////
// Create 3D objects.
var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
var sign = new THREE.Mesh(geometry, material);
//cube.position.set(0, controls.userHeight, -1);
cube.position.set(0, 3.5, -1); //move cube higher
scene.add(cube);
//sign.position.set(-2.25, 0.25, -2.5); //left-right, top-down, forward-back
sign.position.set(-4.75, 0.25, -4.75); //left-right, top-down, forward-back
scene.add(sign);

///////////
// SOUND //
///////////
var listener = new THREE.AudioListener();
camera.add( listener );

// sound spheres
//var sphere = new THREE.SphereGeometry( 5, 8, 4 );
var sphere = new THREE.SphereGeometry( 2.5, 4, 2 );
material_sphere1 = new THREE.MeshPhongMaterial( { color: 0xffaa00, shading: THREE.FlatShading, shininess: 0 } );

var audioLoader = new THREE.AudioLoader();

var mesh1 = new THREE.Mesh( sphere, material_sphere1 );
mesh1.position.set(0, 2.5, -20);
//mesh1.position.set(0, 2.5, -20);
//mesh1.position.set(-4.75, 0.25, -4.75);
scene.add( mesh1 );

var sound1 = new THREE.PositionalAudio( listener );
//audioLoader.load( 'assets/sounds/358232_j_s_song.ogg', function( buffer ) {
audioLoader.load( 'assets/sounds/lost-woods.mp3', function( buffer ) {
  sound1.setBuffer( buffer );
  //sound1.setRefDistance( 20 ); //higher = louder
  sound1.setRefDistance( 3 );
  sound1.setVolume(0.5);
  sound1.setLoop(true);
  sound1.play();
});
mesh1.add( sound1 );

///////////////////
// LIGHT / MODEL //
///////////////////
var ambient = new THREE.AmbientLight( 0x444444 );
//var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );

var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );

var onProgress = function ( xhr ) {
  if ( xhr.lengthComputable ) {
    var percentComplete = xhr.loaded / xhr.total * 100;
    console.log( Math.round(percentComplete, 2) + '% downloaded' );
  }
};

var onError = function ( xhr ) { };

THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'assets/models/ganondorf/' );
mtlLoader.load( 'model.mtl', function( materials ) {

  materials.preload();

  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials( materials );
  objLoader.setPath( 'assets/models/ganondorf/' );
  objLoader.load( 'model.obj', function ( object ) {

    //object.scale.set(0.4, 0.4, 0.4);
    object.scale.set(0.5, 0.5, 0.5);
    //object.position.y = - 95;
    //object.position.set(0, 0, -5);
    object.position.set(0, -4.5, -5); //ganondorf on ground

    //object.material.emissive = new THREE.Color( 0.2, 0.2, 0.2 );

    scene.add( object );

  }, onProgress, onError );

});

window.addEventListener('resize', onResize, true);
window.addEventListener('vrdisplaypresentchange', onResize, true);

// Request animation frame loop function
var lastRender = 0;
function animate(timestamp) {
  var delta = Math.min(timestamp - lastRender, 500);
  lastRender = timestamp;

  // Apply rotation to cube mesh
  cube.rotation.y += delta * 0.0006;

  controls.update();
  // Render the scene through the manager.

  // Update FirstPersonControls after VRControls.
  // FirstPersonControls requires a timestamp.
  vrControls.update();
  fpVrControls.update(timestamp);

  manager.render(scene, camera, timestamp);
  effect.render(scene, camera);

  vrDisplay.requestAnimationFrame(animate);
}

function onResize(e) {
  effect.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}

var vrDisplay;

// Get the HMD, and if we're dealing with something that specifies stageParameters, rearrange the scene.
function setupStage() {
  navigator.getVRDisplays().then(function(displays) {
    if (displays.length > 0) {
      vrDisplay = displays[0];
      if (vrDisplay.stageParameters) {
        setStageDimensions(vrDisplay.stageParameters);
      }
      vrDisplay.requestAnimationFrame(animate);
    }
  });
}

function setStageDimensions(stage) {
  /* not sure what this does... */
  // Make the skybox fit the stage.
  var material = skybox.material;
  scene.remove(skybox);

  // Size the skybox according to the size of the actual stage.
  var geometry = new THREE.BoxGeometry(stage.sizeX, boxSize, stage.sizeZ);
  skybox = new THREE.Mesh(geometry, material);

  // Place it on the floor.
  skybox.position.y = boxSize/2;
  scene.add(skybox);

  // Place the cube in the middle of the scene, at user height.
  cube.position.set(0, controls.userHeight, 0);
}<|endoftext|>