<commit_before>(function() {
	var Utilities = {
		random: function(start, end) {
			var range = end - start;
			var randomNumber = Math.random() * range + start;
			return randomNumber;
		},

		minMax: function(value, min, max) {
			if (typeof min !== "undefined") {
				value = value < min ? min : value;
			}
			if (typeof max !== "undefined") {
				value = value > max ? max : value;
			}
			return value;
		},

		roundTo: function(num, decimalPlaces) {
			return Math.round(num * 10 * decimalPlaces) / (10 * decimalPlaces)
		},

		copyObject: function(originalObject) {
			return JSON.parse(JSON.stringify(originalObject));
		},

		toHash: function(str) {
			var hash = 0;
			if (str.length == 0) {
				return hash;
			}
			for (i = 0; i < str.length; i++) {
				char = str.charCodeAt(i);
				hash = ((hash<<5)-hash)+char;
				hash = hash & hash; // Convert to 32bit integer
			}
			return hash;
		}
	};

	var CONSTS = {
		TREE_COUNT: 9
	};

	var ATTRIBUTES = {
		length: {
			initialValue: 65,
			varyBy: 10,
			min: 25,
			max: 100
		},
		divergence: {
			initialValue: 35,
			varyBy: 30,
			min: 5,
			max: 70
		},
		reduction: {
			initialValue: 0.625,
			varyBy: 0.3,
			min: 0.5,
			max: 0.75
		},
		lineWidth: {
			initialValue: 6,
			varyBy: 0
		},
		branchings: {
			initialValue: 0,
			varyBy: 2,
			min: 0,
			max: 8,
			round: true
		}
	};

	var TreeModel = function(parent) {
		var self = this;
		var attributeNamesArray = [];

		parent = parent || {attributes:{}};
		this.attributes = {};

		// Takes an optional parent - to allow for re-initialization.
		this.initialize = function(parentTree) {
			parent = parentTree || parent;
			for (var attributeName in ATTRIBUTES) {
				attributeNamesArray.push(attributeName);
				self.attributes[attributeName] = parent.attributes[attributeName] || ATTRIBUTES[attributeName].initialValue;
				console.log("initialize", self.attributes);
			}
			self.randomize();
		};

		this.randomize = function() {
			// Selecting a random attribute
			var attributeToRandomize = attributeNamesArray[Math.floor(Math.random()*attributeNamesArray.length)];
			var attribute = ATTRIBUTES[attributeToRandomize];
			var varyBy = attribute.varyBy;

			// Adding/subtracting a random amount from that attribute
			var newValue = self.attributes[attributeToRandomize] + Utilities.random(-1*varyBy, varyBy);

			// Ensuring that the value is within the bounds, and properly rounded.
			newValue = Utilities.minMax(newValue, attribute.min, attribute.max);
			if (attribute.round) {
				newValue = Math.round(newValue);
			} else {
				// Otherwise, just round to max 3 decimal places.
				newValue = Utilities.roundTo(newValue, 2)
			}

			self.attributes[attributeToRandomize] = newValue;
		};

		this.getAttributes = function() {
			return Utilities.copyObject(self.attributes);
		};

		this.setAttributes = function(attributes) {
			console.log("setAttributes", attributes);
			if (Array.isArray(attributes)) {
				for (var i = 0; i < attributes.length; i++) {
					self.attributes[attributeNamesArray[i]] = parseFloat(attributes[i]);
				}
			} else {
				for (var attributeName in attributes) {
					self.attributes[attributeName] = parseFloat(attributes[attributeName]);
				}
			}
		}

		this.initialize();
	};

	/* Adapted from http://thecodeplayer.com/walkthrough/create-binary-trees-using-javascript-and-html5-canvas?s=rl */
	var TreeView = function(canvas) {
		var ctx = canvas.getContext("2d");
		//Lets resize the canvas to occupy the full page
		var W = canvas.offsetWidth;
		var H = canvas.offsetHeight;
		canvas.width = W;
		canvas.height = H;

		//Some variables
		var length, divergence, reduction, lineWidth, branchings, start_points = [];

		this.draw = function(attributes) {
			//filling the canvas white
			ctx.clearRect (0, 0, W, H);

			//Lets draw the trunk of the tree
			//length of the trunk - 100-150
			length = attributes.length;
			//angle at which branches will diverge - 10-60
			divergence = attributes.divergence;
			//Every branch will be 0.75times of the previous one - 0.5-0.75
			reduction = attributes.reduction;
			//width of the branch/trunk
			lineWidth = attributes.lineWidth;
			//number of branchings
			branchings = attributes.branchings;
			branchings ? branchings < 0 : 0;

			//This is the end point of the trunk, from where branches will diverge
			var trunk = {x: W/2, y: length + 5, angle: 90};
			//It becomes the start point for branches
			start_points = []; //empty the start points on every init();
			start_points.push(trunk);

			//Y coordinates go positive downwards, hence they are inverted by deducting it
			//from the canvas height = H
			ctx.beginPath();
			ctx.moveTo(trunk.x, H - 5);
			ctx.lineTo(trunk.x, H - trunk.y);
			ctx.strokeStyle = "brown";
			ctx.lineWidth = lineWidth;
			ctx.stroke();

			branches();
		}

		//Lets draw the branches now
		function branches(callNum) {
			callNum = callNum || 0;

			//reducing lineWidth and length
			length = length * reduction;
			lineWidth = lineWidth * reduction;
			ctx.lineWidth = lineWidth;

			var new_start_points = [];
			ctx.beginPath();
			for(var i = 0; i < start_points.length; i++) {
				var sp = start_points[i];
				//2 branches will come out of every start point. Hence there will be
				//2 end points. There is a difference in the divergence.
				var ep1 = get_endpoint(sp.x, sp.y, sp.angle + divergence, length);
				var ep2 = get_endpoint(sp.x, sp.y, sp.angle - divergence, length);

				//drawing the branches now
				ctx.moveTo(sp.x, H - sp.y);
				ctx.lineTo(ep1.x, H - ep1.y);
				ctx.moveTo(sp.x, H - sp.y);
				ctx.lineTo(ep2.x, H - ep2.y);

				//Time to make this function recursive to draw more branches
				ep1.angle = sp.angle + divergence;
				ep2.angle = sp.angle - divergence;

				new_start_points.push(ep1);
				new_start_points.push(ep2);
			}
			//Lets add some more color
			if (length < 10) {
				ctx.strokeStyle = "green";
			} else {
				ctx.strokeStyle = "brown";
			}
			ctx.stroke();
			start_points = new_start_points;
			//recursive call - only if length is more than 2.
			//Else it will fall in an long loop
			if (callNum < branchings) {
				setTimeout(function(){
					branches(callNum+1);
				}, 50);
			}
		}

		function get_endpoint(x, y, a, length) {
			//This function will calculate the end points based on simple vectors
			//http://physics.about.com/od/mathematics/a/VectorMath.htm
			//You can read about basic vectors from this link
			var epx = x + length * Math.cos(a * Math.PI/180);
			var epy = y + length * Math.sin(a * Math.PI/180);
			return {x: epx, y: epy};
		}

		this.setRoot = function() {
			canvas.classList.add("root");
		}

		this.unsetRoot = function() {
			canvas.classList.remove("root");
		}

		this.onClick = function(callback) {
			canvas.addEventListener("click", function() {
				callback();
			});
		}
	}

	var TreeController = (function() {
		var root;
		var trees = new Array(CONSTS.TREE_COUNT);
		var treeCanvases = document.querySelectorAll(".tree");
		var attributeHashes = [];
		var ignoreHash;

		function getAttributesHash(attributes) {
			var hash = "";
			for (var attributeName in attributes) {
				hash += attributes[attributeName] + "_";
			}
			return hash.substring(0, hash.length - 1);
		}

		function setupTree(index, parent) {
			if (!trees[index]) {
				tree = trees[index] =  {};
				tree.model = new TreeModel(parent);
				tree.view = new TreeView(treeCanvases[index]);
				tree.view.onClick(function() {
					spawnChildren(index);
				})
			} else {
				tree = trees[index];
				tree.model.initialize(parent);
			}
			tree.view.draw(tree.model.getAttributes());
			attributeHashes[index] = getAttributesHash(tree.model.getAttributes());
			return tree;
		}

		function spawnChildren(index, skipHash) {
			root.view.unsetRoot()
			root = trees[index];
			root.view.setRoot();
			for (var i = 0; i < trees.length; i++) {
				if (i === index) {
					continue;
				}
				setupTree(i, root.model);
			}
			if (!skipHash) {
				ignoreHash = true;
				hasher.setHash(attributeHashes.join(","));
				ignoreHash = false;
			}
		}

		// function to read the hash value and use it as the tree attributes.
		function readHash(hash) {
			if (ignoreHash) {
				return;
			}
			var attributeSets = hash.split(",");
			trees.forEach(function(tree, index) {
				tree.model.setAttributes(attributeSets[index].split("_"))
				tree.view.draw(tree.model.getAttributes())
			});
		}

		function init() {
			root = setupTree(0);
			spawnChildren(0, true);

			hasher.initialized.add(readHash); //add initialized listener (to grab initial value in case it is already set)
			hasher.changed.add(readHash);
			hasher.init(); //initialize hasher (start listening for history changes)
		}

		return {
			init: init
		}
	})();

	TreeController.init();
})();<commit_msg>Added hashing support<commit_after>(function() {
	var Utilities = {
		random: function(start, end) {
			var range = end - start;
			var randomNumber = Math.random() * range + start;
			return randomNumber;
		},

		minMax: function(value, min, max) {
			if (typeof min !== "undefined") {
				value = value < min ? min : value;
			}
			if (typeof max !== "undefined") {
				value = value > max ? max : value;
			}
			return value;
		},

		roundTo: function(num, decimalPlaces) {
			return Math.round(num * 10 * decimalPlaces) / (10 * decimalPlaces)
		},

		copyObject: function(originalObject) {
			return JSON.parse(JSON.stringify(originalObject));
		},

		toHash: function(str) {
			var hash = 0;
			if (str.length == 0) {
				return hash;
			}
			for (i = 0; i < str.length; i++) {
				char = str.charCodeAt(i);
				hash = ((hash<<5)-hash)+char;
				hash = hash & hash; // Convert to 32bit integer
			}
			return hash;
		}
	};

	var CONSTS = {
		TREE_COUNT: 9
	};

	var ATTRIBUTES = {
		length: {
			initialValue: 65,
			varyBy: 10,
			min: 25,
			max: 100
		},
		divergence: {
			initialValue: 35,
			varyBy: 30,
			min: 5,
			max: 70
		},
		reduction: {
			initialValue: 0.625,
			varyBy: 0.3,
			min: 0.5,
			max: 0.75
		},
		lineWidth: {
			initialValue: 6,
			varyBy: 0
		},
		branchings: {
			initialValue: 0,
			varyBy: 2,
			min: 0,
			max: 8,
			round: true
		}
	};

	var TreeModel = function(parent) {
		var self = this;
		var attributeNamesArray = [];

		parent = parent || {attributes:{}};
		this.attributes = {};

		// Takes an optional parent - to allow for re-initialization.
		this.initialize = function(parentTree) {
			parent = parentTree || parent;
			for (var attributeName in ATTRIBUTES) {
				attributeNamesArray.push(attributeName);
				self.attributes[attributeName] = parent.attributes[attributeName] || ATTRIBUTES[attributeName].initialValue;
				console.log("initialize", self.attributes);
			}
			self.randomize();
		};

		this.randomize = function() {
			// Selecting a random attribute
			var attributeToRandomize = attributeNamesArray[Math.floor(Math.random()*attributeNamesArray.length)];
			var attribute = ATTRIBUTES[attributeToRandomize];
			var varyBy = attribute.varyBy;

			// Adding/subtracting a random amount from that attribute
			var newValue = self.attributes[attributeToRandomize] + Utilities.random(-1*varyBy, varyBy);

			// Ensuring that the value is within the bounds, and properly rounded.
			newValue = Utilities.minMax(newValue, attribute.min, attribute.max);
			if (attribute.round) {
				newValue = Math.round(newValue);
			} else {
				// Otherwise, just round to max 3 decimal places.
				newValue = Utilities.roundTo(newValue, 2)
			}

			self.attributes[attributeToRandomize] = newValue;
		};

		this.getAttributes = function() {
			return Utilities.copyObject(self.attributes);
		};

		this.setAttributes = function(attributes) {
			console.log("setAttributes", attributes);
			if (Array.isArray(attributes)) {
				for (var i = 0; i < attributes.length; i++) {
					self.attributes[attributeNamesArray[i]] = parseFloat(attributes[i]);
				}
			} else {
				for (var attributeName in attributes) {
					self.attributes[attributeName] = parseFloat(attributes[attributeName]);
				}
			}
		}

		this.initialize();
	};

	/* Adapted from http://thecodeplayer.com/walkthrough/create-binary-trees-using-javascript-and-html5-canvas?s=rl */
	var TreeView = function(canvas) {
		var ctx = canvas.getContext("2d");
		//Lets resize the canvas to occupy the full page
		var W = canvas.offsetWidth;
		var H = canvas.offsetHeight;
		canvas.width = W;
		canvas.height = H;

		//Some variables
		var length, divergence, reduction, lineWidth, branchings, start_points = [];

		this.draw = function(attributes) {
			//filling the canvas white
			ctx.clearRect (0, 0, W, H);

			//Lets draw the trunk of the tree
			//length of the trunk - 100-150
			length = attributes.length;
			//angle at which branches will diverge - 10-60
			divergence = attributes.divergence;
			//Every branch will be 0.75times of the previous one - 0.5-0.75
			reduction = attributes.reduction;
			//width of the branch/trunk
			lineWidth = attributes.lineWidth;
			//number of branchings
			branchings = attributes.branchings;
			branchings ? branchings < 0 : 0;

			//This is the end point of the trunk, from where branches will diverge
			var trunk = {x: W/2, y: length + 5, angle: 90};
			//It becomes the start point for branches
			start_points = []; //empty the start points on every init();
			start_points.push(trunk);

			//Y coordinates go positive downwards, hence they are inverted by deducting it
			//from the canvas height = H
			ctx.beginPath();
			ctx.moveTo(trunk.x, H - 5);
			ctx.lineTo(trunk.x, H - trunk.y);
			ctx.strokeStyle = "brown";
			ctx.lineWidth = lineWidth;
			ctx.stroke();

			branches();
		}

		//Lets draw the branches now
		function branches(callNum) {
			callNum = callNum || 0;

			//reducing lineWidth and length
			length = length * reduction;
			lineWidth = lineWidth * reduction;
			ctx.lineWidth = lineWidth;

			var new_start_points = [];
			ctx.beginPath();
			for(var i = 0; i < start_points.length; i++) {
				var sp = start_points[i];
				//2 branches will come out of every start point. Hence there will be
				//2 end points. There is a difference in the divergence.
				var ep1 = get_endpoint(sp.x, sp.y, sp.angle + divergence, length);
				var ep2 = get_endpoint(sp.x, sp.y, sp.angle - divergence, length);

				//drawing the branches now
				ctx.moveTo(sp.x, H - sp.y);
				ctx.lineTo(ep1.x, H - ep1.y);
				ctx.moveTo(sp.x, H - sp.y);
				ctx.lineTo(ep2.x, H - ep2.y);

				//Time to make this function recursive to draw more branches
				ep1.angle = sp.angle + divergence;
				ep2.angle = sp.angle - divergence;

				new_start_points.push(ep1);
				new_start_points.push(ep2);
			}
			//Lets add some more color
			if (length < 10) {
				ctx.strokeStyle = "green";
			} else {
				ctx.strokeStyle = "brown";
			}
			ctx.stroke();
			start_points = new_start_points;
			//recursive call - only if length is more than 2.
			//Else it will fall in an long loop
			if (callNum < branchings) {
				setTimeout(function(){
					branches(callNum+1);
				}, 50);
			}
		}

		function get_endpoint(x, y, a, length) {
			//This function will calculate the end points based on simple vectors
			//http://physics.about.com/od/mathematics/a/VectorMath.htm
			//You can read about basic vectors from this link
			var epx = x + length * Math.cos(a * Math.PI/180);
			var epy = y + length * Math.sin(a * Math.PI/180);
			return {x: epx, y: epy};
		}

		this.setRoot = function() {
			canvas.classList.add("root");
		}

		this.unsetRoot = function() {
			canvas.classList.remove("root");
		}

		this.onClick = function(callback) {
			canvas.addEventListener("click", function() {
				callback();
			});
		}
	}

	var TreeController = (function() {
		var root;
		var trees = new Array(CONSTS.TREE_COUNT);
		var treeCanvases = document.querySelectorAll(".tree");
		var attributeHashes = [];
		var ignoreHash;

		function getAttributesHash(attributes) {
			var hash = "";
			for (var attributeName in attributes) {
				hash += attributes[attributeName] + "_";
			}
			return hash.substring(0, hash.length - 1);
		}

		function setupTree(index, parent) {
			if (!trees[index]) {
				tree = trees[index] =  {};
				tree.model = new TreeModel(parent);
				tree.view = new TreeView(treeCanvases[index]);
				tree.view.onClick(function() {
					spawnChildren(index);
				})
			} else {
				tree = trees[index];
				tree.model.initialize(parent);
			}
			tree.view.draw(tree.model.getAttributes());
			attributeHashes[index] = getAttributesHash(tree.model.getAttributes());
			return tree;
		}

		function spawnChildren(index, skipHash) {
			root.view.unsetRoot()
			root = trees[index];
			root.view.setRoot();
			for (var i = 0; i < trees.length; i++) {
				if (i === index) {
					continue;
				}
				setupTree(i, root.model);
			}
			if (!skipHash) {
				// Set a flag, so the hash watched doesn't fire.
				ignoreHash = true;
				hasher.setHash(attributeHashes.join(","));
				ignoreHash = false;
			}
		}

		// function to read the hash value and use it as the tree attributes.
		function readHash(hash) {
			if (ignoreHash) {
				return;
			}
			var attributeSets = hash.split(",");
			trees.forEach(function(tree, index) {
				tree.model.setAttributes(attributeSets[index].split("_"))
				tree.view.draw(tree.model.getAttributes())
			});
		}

		function init() {
			root = setupTree(0);
			spawnChildren(0, true);

			hasher.initialized.add(readHash); //add initialized listener (to grab initial value in case it is already set)
			hasher.changed.add(readHash);
			hasher.init(); //initialize hasher (start listening for history changes)
		}

		return {
			init: init
		}
	})();

	TreeController.init();
})();<|endoftext|>


<commit_before>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = ''
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

	Logo.url = 'http://' + window.location.hostname +
		'/?backColor=' + Logo.backColor +
		'&fontColor=' + Logo.fontColor +
		'&fontStroke=' + Logo.fontStroke +
		'&backStyle=' + Logo.backStyle +
		'&stripeColor=' + Logo.stripeColor +
		'&letters=' + Logo.letters.join('|') +
		'&offsetX=' + Logo.offsetX +
		'&fontFamily=' + encodeURIComponent(Logo.fontFamily);

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: '#' + Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: '#' + Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: '#' + Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: '#' + Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: '#' + Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: '#' + Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: '#' + Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
			// Gradient fill
			var grd = context.createLinearGradient(0, 0, Logo.kinetic.stage.getWidth()/2, Logo.kinetic.stage.getHeight());
			grd.addColorStop(0, '#bbb');
			grd.addColorStop(1, '#f8f8f0');
			context.fillStyle = grd;
			context.fill()

		},
		opacity: .10
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log('dataUrl:'+dataUrl);
				$('#logo').replaceWith(pngLogo);
			}
		}
	});

})();<commit_msg>+Horizontal and Vertical striping<commit_after>function queryObj() {
	var result = {}, queryString = location.search.slice(1),
		re = /([^&=]+)=([^&]*)/g, m;

	while (m = re.exec(queryString)) {
		result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
	}
	return result;
}

(function () {

	Logo = {
	};

	Logo.randomColor = function() {
		var color = ''
		for(var i = 0; i < 3; i++) {
			var r = Math.floor(Math.random() * 15);
			color += r < 9 ? r : String.fromCharCode(65 + r - 9);
		}
		return color;
	};

	Logo.queryObj = new queryObj();

	Logo.backStyles = new Array('blank', 'striped', 'diag', 'exed', 'habs', 'roundel', 'dots');
	Logo.fontFamilies = new Array("Calibri", "Times New Roman", "Comic Sans MS", "Palatino Linotype", "Arial", "Helvetica", "Tahoma");

	Logo.letters = new Array();
		if(Logo.queryObj.letters) {
			Logo.letters = Logo.queryObj.letters.split("|");
		} else {
			var letterLength = 1 + Math.floor(Math.random() * 2);
			for(var i = 0; i < letterLength; i++) {
				Logo.letters.push([String.fromCharCode(65 + Math.floor(Math.random() * 26))]);
			}
		}
		Logo.backColor = Logo.queryObj.backColor ? Logo.queryObj.backColor : Logo.randomColor();
		Logo.fontColor = Logo.queryObj.fontColor ? Logo.queryObj.fontColor : Logo.randomColor();
		Logo.fontStroke = Logo.queryObj.fontStroke ? Logo.queryObj.fontStroke : Logo.backColor;
		Logo.backStyle = Logo.queryObj.backStyle ? Logo.queryObj.backStyle : Logo.backStyles[Math.floor(Math.random() * Logo.backStyles.length)];
		Logo.stripeColor = Logo.queryObj.stripeColor ? Logo.queryObj.stripeColor : Logo.randomColor();
		Logo.offsetX = Logo.queryObj.offsetX? Logo.queryObj.offsetX : (Logo.letters.length > 1? (Math.random() * 50) : 0);
		Logo.fontFamily = Logo.queryObj.fontFamily ? Logo.queryObj.fontFamily : Logo.fontFamilies[Math.floor(Math.random() * Logo.fontFamilies.length)];

	Logo.url = 'http://' + window.location.hostname +
		'/?backColor=' + Logo.backColor +
		'&fontColor=' + Logo.fontColor +
		'&fontStroke=' + Logo.fontStroke +
		'&backStyle=' + Logo.backStyle +
		'&stripeColor=' + Logo.stripeColor +
		'&letters=' + Logo.letters.join('|') +
		'&offsetX=' + Logo.offsetX +
		'&fontFamily=' + encodeURIComponent(Logo.fontFamily);

	Logo.kinetic = {}; // All kinetic object references go in here

	Logo.kinetic.stage = new Kinetic.Stage( {
		container: 'logo',
		width: Logo.queryObj.width? Logo.queryObj.width : 275, //Math.min(window.innerWidth, window.innerHeight),
		height: Logo.queryObj.height? Logo.queryObj.height : 275 //Math.min(window.innerWidth, window.innerHeight)
	});

	Logo.kinetic.layer = new Kinetic.Layer();

	Logo.kinetic.wrapper = new Kinetic.Rect( {
		x:0,
		y:0,
		width: Logo.kinetic.stage.getWidth(),
		height: Logo.kinetic.stage.getHeight(),
		fill: '#' + Logo.backColor
	});

	Logo.kinetic.layer.add(Logo.kinetic.wrapper);

	Logo.kinetic.stripes = new Array();

	if(Logo.backStyle == 'striped') {
		for(var i = 0; i < 2; i++) {
			var x = (i % 2 == 0)? Logo.kinetic.stage.getWidth() * .2 : Logo.kinetic.stage.getWidth() - (Logo.kinetic.stage.getWidth() * .2);
			var stripe = new Kinetic.Line({
				points: [ x, 0, x, Logo.kinetic.stage.getHeight() ],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .1
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'diag' || Logo.backStyle == 'exed') {
		var count = Logo.backStyle == 'diag' ? 1 : 2;
		for(var i = 0; i < count; i++) {
			var stripe = new Kinetic.Line({
				points: (i % 2 == 0) ? [0, 0, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()] : [0, Logo.kinetic.stage.getHeight(), Logo.kinetic.stage.getWidth(), 0],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() * .2
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'habs') {
		var stripe = new Kinetic.Line({
			points: [0, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight() * .5],
			stroke: '#' + Logo.stripeColor,
			strokeWidth: Logo.kinetic.stage.getWidth() * .25
		});
		Logo.kinetic.stripes.push(stripe);
		Logo.kinetic.layer.add(stripe);
	}
	if(Logo.backStyle == "horizontal") {
		for(var i = 0; i <= 3; i++) {
			var stripe = new Kinetic.Line({
				points: [0, i * (Logo.kinetic.stage.getWidth() / 3), Logo.kinetic.stage.getHeight(), i * (Logo.kinetic.stage.getWidth() / 3)],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() / 6
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == "vertical") {
		for(var i = 0; i <= 4; i++) {
			var stripe = new Kinetic.Line({
				points: [i * (Logo.kinetic.stage.getWidth() / 4), 0, i * (Logo.kinetic.stage.getWidth() / 4),Logo.kinetic.stage.getHeight()],
				stroke: '#' + Logo.stripeColor,
				strokeWidth: Logo.kinetic.stage.getWidth() / 8
			});
			Logo.kinetic.stripes.push(stripe);
			Logo.kinetic.layer.add(stripe);
		}
	}
	if(Logo.backStyle == 'roundel') {
		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			fill: '#' + Logo.stripeColor,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .2
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);

		var circle = new Kinetic.Circle({
			x: Logo.kinetic.stage.getWidth() * .5,
			y: Logo.kinetic.stage.getHeight() * .5,
			strokeWidth: Logo.kinetic.stage.getWidth() * .15,
			radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .4,
			stroke: '#' + Logo.stripeColor
		});
		Logo.kinetic.stripes.push(circle);
		Logo.kinetic.layer.add(circle);
	}
	if(Logo.backStyle == 'dots') {
		for(var i = 0; i < 4; i++) {
			for(var j = 0; j < 4; j++) {
				var circle = new Kinetic.Circle({
					x: (Logo.kinetic.stage.getWidth() / 3*( i )) + ((j%2) * Logo.kinetic.stage.getWidth()/6),
					y: Logo.kinetic.stage.getHeight() / 3 * (j ),
					radius: Math.min(Logo.kinetic.stage.getWidth(), Logo.kinetic.stage.getHeight()) * .1,
					fill: '#' + Logo.stripeColor
				});
				Logo.kinetic.stripes.push(circle);
				Logo.kinetic.layer.add(circle);
			}
		}
	}
	Logo.kinetic.letters = new Array();
	for(var i = Logo.letters.length-1; i >= 0; i--) {
		var y = i * Logo.kinetic.stage.getHeight() * .1;
		var x = 0;
		if(Logo.letters.length > 1) {
			x = (i == 0? -1 : 1) * Logo.offsetX * Logo.kinetic.stage.getWidth() / 200;
		}
		if(Logo.letters.length == 2) {
			y  -= Logo.kinetic.stage.getHeight() * (i == 0? .1 : -.02);
		}
		var letter = new Kinetic.Text({
			x: x,
			y: y,
			width: Logo.kinetic.stage.getWidth(),
			fill: '#' + Logo.fontColor,
			fontFamily: Logo.fontFamily,
			fontSize: Logo.kinetic.stage.getHeight() - 25,
			text: Logo.letters[i],
			align: 'center',
			fontStyle: 'bold',
			strokeWidth: 2,
			stroke: '#' + Logo.fontStroke
		});
		Logo.kinetic.letters.push(letter);
		Logo.kinetic.layer.add(letter);
	}

     Logo.kinetic.gloss = new Kinetic.Shape({
		drawFunc: function(canvas) {
			var borderSize = Logo.kinetic.stage.getWidth() * .03;
			var context = canvas.getContext();
			context.beginPath();
			context.moveTo(borderSize, borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize , borderSize);
			context.lineTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .3);
			context.quadraticCurveTo(Logo.kinetic.stage.getWidth() - borderSize, Logo.kinetic.stage.getHeight() * .5, Logo.kinetic.stage.getWidth() * .5, Logo.kinetic.stage.getHeight() * .5);
			context.quadraticCurveTo(borderSize, Logo.kinetic.stage.getWidth() * .5, borderSize, Logo.kinetic.stage.getWidth() * .6);
			context.closePath();
			canvas.fillStroke(this);
			// Gradient fill
			var grd = context.createLinearGradient(0, 0, Logo.kinetic.stage.getWidth()/2, Logo.kinetic.stage.getHeight());
			grd.addColorStop(0, '#bbb');
			grd.addColorStop(1, '#f8f8f0');
			context.fillStyle = grd;
			context.fill()
		},
		opacity: .10
	});

	Logo.kinetic.layer.add(Logo.kinetic.gloss);

	Logo.kinetic.stage.add(Logo.kinetic.layer);

	Logo.kinetic.stage.toDataURL({
		callback: function(dataUrl) {
			query = new queryObj();
			if(query.mode == 'png') {
				pngLogo = new Image();
				pngLogo.src = dataUrl;
				console.log('dataUrl:'+dataUrl);
				$('#logo').replaceWith(pngLogo);
			}
		}
	});

})();<|endoftext|>


<commit_before>$(function(){
	window.fnames = new Array();
	window.ftypes = new Array();
	fnames[0]='EMAIL';
	ftypes[0]='email';
	var $mcj = jQuery.noConflict(true);
	if(window.location.hash == '#thanks'){
		$('#thanks-dialog').modal();
	}
});

var fbShare = function(url){
	window.open('https://www.facebook.com/dialog/share?app_id=1450714908506163' +
				'&href=' + encodeURIComponent(url),
				'fbwindow',
	            'height=623, width=556, top=' + (window.innerHeight/2 - 623/2) + ', left=' + (window.innerWidth/2 - 556/2) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
};

var twShare = function(url, text){
	window.open('https://twitter.com/intent/tweet' +
				'?url=' + encodeURIComponent(url) +
				'&text=' + encodeURIComponent(text) +
				'&related=musikee_com',
				'twwindow',
	            'height=253, width=723, top=' + (window.innerHeight/2 - 253/2) + ', left=' + (window.innerWidth/2 - 723/2) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
};<commit_msg>debug<commit_after>$(function(){
	window.fnames = new Array();
	window.ftypes = new Array();
	fnames[0]='EMAIL';
	ftypes[0]='email';
	var $mcj = jQuery.noConflict(true);
	if(window.location.hash == '#thanks'){
		console.log('hash', window.location.hash);
		console.log($('#thanks-dialog'));
		$('#thanks-dialog').modal();
	}
});

var fbShare = function(url){
	window.open('https://www.facebook.com/dialog/share?app_id=1450714908506163' +
				'&href=' + encodeURIComponent(url),
				'fbwindow',
	            'height=623, width=556, top=' + (window.innerHeight/2 - 623/2) + ', left=' + (window.innerWidth/2 - 556/2) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
};

var twShare = function(url, text){
	window.open('https://twitter.com/intent/tweet' +
				'?url=' + encodeURIComponent(url) +
				'&text=' + encodeURIComponent(text) +
				'&related=musikee_com',
				'twwindow',
	            'height=253, width=723, top=' + (window.innerHeight/2 - 253/2) + ', left=' + (window.innerWidth/2 - 723/2) + ', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
};<|endoftext|>


<commit_before>jQuery(function() {
	var $sidebar = $('#sidebar'),
		$nav = $('.nav'),
		$main = $('.main');

	var found = true;

	var $el;

	$("section > div.highlighter-rouge:first-of-type").each(function(i) {

		var $this = $(this).before("

"),
		$languages = $this.prev(),
		$notFirst = $this.nextUntil(":not(div.highlighter-rouge)"),
		$all = $this.add($notFirst);

		$all.add($languages).wrapAll("

");

		listLanguages($all, $languages);

		$this.css('display', 'block');
		$notFirst.css('display', 'none');

		$languages.find('a').first().addClass('active');

		$languages.find('a').click(function() {
			$all.css('display', 'none');
			$all.eq($(this).parent().index()).css('display', 'block');

			$languages.find('a').removeClass('active');
			$(this).addClass('active');
			return false;
		});

		if ($languages.children().length === 0) {
			$languages.remove();
		}
	});

	function listLanguages($el, $insert) {
		$el.each(function(i) {
			var title = $(this).attr('title');
			if (title) {
				$insert.append("
" + title + "
");
			}
		});
	}

	var href = $('.sidebar a').first().attr("href");

	if (href !== undefined && href.charAt(0) === "#") {
		setActiveSidebarLink();

		$(window).on("scroll", function(evt) {
			setActiveSidebarLink();
		});
	}

	function setActiveSidebarLink() {
			$('.sidebar a').removeClass('active');
				var $closest = getClosestHeader();
				$closest.addClass('active');
				document.title = $closest.text();

	}
});

function getClosestHeader() {
	var $links = $('.sidebar a'),
	top = window.scrollY,
	$last = $links.first();

	if (top < 300) {
		return $last;
	}

	if (top + window.innerHeight >= $(".main").height()) {
		return $links.last();
	}

	for (var i = 0; i < $links.length; i++) {
		var $link = $links.eq(i),
		href = $link.attr("href");

		if (href !== undefined && href.charAt(0) === "#" && href.length > 1) {
			var $anchor = $(href);

			if ($anchor.length > 0) {
				var offset = $anchor.offset();

				if (top < offset.top - 300) {
					return $last;
				}

				$last = $link;
			}
		}
	}
	return $last;
}
<commit_msg>updating title to include 'memair'<commit_after>jQuery(function() {
	var $sidebar = $('#sidebar'),
		$nav = $('.nav'),
		$main = $('.main');

	var found = true;

	var $el;

	$("section > div.highlighter-rouge:first-of-type").each(function(i) {

		var $this = $(this).before("

"),
		$languages = $this.prev(),
		$notFirst = $this.nextUntil(":not(div.highlighter-rouge)"),
		$all = $this.add($notFirst);

		$all.add($languages).wrapAll("

");

		listLanguages($all, $languages);

		$this.css('display', 'block');
		$notFirst.css('display', 'none');

		$languages.find('a').first().addClass('active');

		$languages.find('a').click(function() {
			$all.css('display', 'none');
			$all.eq($(this).parent().index()).css('display', 'block');

			$languages.find('a').removeClass('active');
			$(this).addClass('active');
			return false;
		});

		if ($languages.children().length === 0) {
			$languages.remove();
		}
	});

	function listLanguages($el, $insert) {
		$el.each(function(i) {
			var title = $(this).attr('title');
			if (title) {
				$insert.append("
" + title + "
");
			}
		});
	}

	var href = $('.sidebar a').first().attr("href");

	if (href !== undefined && href.charAt(0) === "#") {
		setActiveSidebarLink();

		$(window).on("scroll", function(evt) {
			setActiveSidebarLink();
		});
	}

	function setActiveSidebarLink() {
			$('.sidebar a').removeClass('active');
				var $closest = getClosestHeader();
				$closest.addClass('active');
				document.title = $closest.text() + ' | Memair';

	}
});

function getClosestHeader() {
	var $links = $('.sidebar a'),
	top = window.scrollY,
	$last = $links.first();

	if (top < 300) {
		return $last;
	}

	if (top + window.innerHeight >= $(".main").height()) {
		return $links.last();
	}

	for (var i = 0; i < $links.length; i++) {
		var $link = $links.eq(i),
		href = $link.attr("href");

		if (href !== undefined && href.charAt(0) === "#" && href.length > 1) {
			var $anchor = $(href);

			if ($anchor.length > 0) {
				var offset = $anchor.offset();

				if (top < offset.top - 300) {
					return $last;
				}

				$last = $link;
			}
		}
	}
	return $last;
}
<|endoftext|>


<commit_before>---
layout: null
sitemap:
  exclude: 'yes'
---

$(document).ready(function () {
  $('a.research-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

  if (window.location.hash && window.location.hash == '#research') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

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

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

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

})
<commit_msg>Update main.js<commit_after>---
layout: null
sitemap:
  exclude: 'yes'
---

$(document).ready(function () {
  $('a.research-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

  if (window.location.hash && window.location.hash == 'research') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }

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

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

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

})
<|endoftext|>


<commit_before>var mp = .3,
		mr = .5,
		ms = .01;

var mesh;
var loader = new THREE.STLLoader();
var material;

var Menu = function() {
	this.STL_file = './models/Wwrench.stl',
	this.position = mp;
	this.rotation = mr;
	this.scale = ms;
};

if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var container, stats;
var camera, cameraTarget, scene, renderer;

var mouseX = 0, mouseY = 0;
var faceX = 0, faceY = 0;
var objX = 0, objY = 0;

var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var context2 = canvas.getContext('2d');

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init() {

	container = document.createElement( 'div' );
	document.body.appendChild( container );

	camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
	camera.position.set( 3, 0.15, 3 );

	cameraTarget = new THREE.Vector3( 0, -0.25, 0 );

	scene = new THREE.Scene();
	scene.fog = new THREE.Fog( 0x72645b, 2, 15 );

  var PI2 = Math.PI * 2;
  var program = function (context) {
    context.beginPath();
    context.arc(0, 0, 0.5, 0, PI2, true);
    context.fill();
	}

	var program2 = function (context) {
    context.beginPath();
    context.arc(0, 0, 0.5, 0, PI2, true);
    context.fill();
	}

	// Ground

	var plane = new THREE.Mesh(
		new THREE.PlaneBufferGeometry( 40, 40 ),
		new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
	);
	plane.rotation.x = -Math.PI/2;
	plane.position.y = -0.5;
	scene.add( plane );

	plane.receiveShadow = true;

	// load STL
	material = new THREE.MeshPhongMaterial( { color: 0xAAAAAA, specular: 0x111111, shininess: 200 } );

	loader.load( './models/Wwrench.stl', function ( geometry ) {

		var meshMaterial = material;
		if (geometry.hasColors) {
			meshMaterial = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
		}

		mesh = new THREE.Mesh( geometry, meshMaterial );
		mesh.position.set( mp, mp, 0 );
		mesh.rotation.set(  Math.PI * mr, 2 * Math.PI * mr, Math.PI * mr );
		mesh.scale.set( ms, ms, ms );

		mesh.castShadow = true;
		mesh.receiveShadow = true;

		scene.add( mesh );

	} );

	// Ambient Light

	scene.add( new THREE.AmbientLight( 0x777777 ) );

	addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
	addShadowedLight( 0.5, 1, -1, 0xffaa00, 1 );

	// The Renderer

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	renderer.gammaInput = true;
	renderer.gammaOutput = true;

	renderer.shadowMapEnabled = true;
	renderer.shadowMapCullFace = THREE.CullFaceBack;

	container.appendChild( renderer.domElement );

	// Stats on top left

	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '0px';
	container.appendChild( stats.domElement );

	window.addEventListener( 'resize', onWindowResize, false );

}

function addShadowedLight( x, y, z, color, intensity ) {

	var directionalLight = new THREE.DirectionalLight( color, intensity );
	directionalLight.position.set( x, y, z );
	scene.add( directionalLight );

	directionalLight.castShadow = true;

	var d = 1;
	directionalLight.shadowCameraLeft = -d;
	directionalLight.shadowCameraRight = d;
	directionalLight.shadowCameraTop = d;
	directionalLight.shadowCameraBottom = -d;

	directionalLight.shadowCameraNear = 1;
	directionalLight.shadowCameraFar = 4;

	directionalLight.shadowMapWidth = 1024;
	directionalLight.shadowMapHeight = 1024;

	directionalLight.shadowBias = -0.005;
	directionalLight.shadowDarkness = 0.15;

}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize( window.innerWidth, window.innerHeight );

}

window.onload = function() {

	// CAD Menu
	var panel = new Menu();
	var gui = new dat.GUI();

	var file = gui.add(panel, 'STL_file');

	var positionF = gui.add(panel, 'position', 0, 1); // Min and max
	var rotationF = gui.add(panel, 'rotation', 0, 2); // Min and max
	var scaleF = gui.add(panel, 'scale', 0, 1); // Min and max

	positionF.onChange(function(value){
		mesh.position.set( value, value, 0 );
		mp = value;
	});

	rotationF.onChange(function(value){
		mesh.rotation.set(  Math.PI * value, Math.PI *2* value, Math.PI * value );
		mr = value;
	});

	scaleF.onChange(function(value){
		mesh.scale.set( value, value, value );
		ms = value;
	});

	file.onFinishChange(function(value){

		console.log('new STL: ' + value);
		scene.remove(mesh);
		console.log('old STL mesh removed');

		loader.load( value, function ( geometry ) {

			var meshMaterial = material;
			if (geometry.hasColors) {
				meshMaterial = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
			}
			mesh = new THREE.Mesh( geometry, meshMaterial );
			mesh.position.set( mp, mp, 0 );
			mesh.rotation.set(  Math.PI * mr, 2 * Math.PI * mr, Math.PI * mr );
			mesh.scale.set( ms, ms, ms );
			mesh.castShadow = true;
			mesh.receiveShadow = true;
			scene.add( mesh );
		} );

		console.log('new STL loaded');

	});

	/* END CAD MENU STUFF*/

  var trackerC = new tracking.ColorTracker();
  trackerC.setMinDimension(5);
  trackerC.setMinGroupSize(10);
  tracking.track('#video', trackerC, { camera: true });
  trackerC.on('track', onColorMove);
};

function onColorMove(event) {
  if (event.data.length === 0) {
    return;
  }
  var maxRect;
  var maxRectArea = 0;
  event.data.forEach(function(rect) {
    if (rect.width * rect.height > maxRectArea){
      maxRectArea = rect.width * rect.height;
      maxRect = rect;
    }
  });
  if (maxRectArea > 0) {
    var rectCenterX = maxRect.x + (maxRect.width/2);
    var rectCenterY = maxRect.y + (maxRect.height/2);
    objX = (rectCenterX - 160) * (window.innerWidth/320) * 10;
    objY = (rectCenterY - 120) * (window.innerHeight/240) * 10;
    context2.clearRect(0, 0, canvas.width, canvas.height);
    context2.strokeStyle = maxRect.color;
    context2.strokeRect(maxRect.x, maxRect.y, maxRect.width, maxRect.height);

    context2.font = '11px Helvetica';
    context2.fillStyle = "#fff";
    context2.fillText('x: ' + maxRect.x + 'px', maxRect.x + maxRect.width + 5, maxRect.y + 11);
    context2.fillText('y: ' + maxRect.y + 'px', maxRect.x + maxRect.width + 5, maxRect.y + 22);
  }
}

function animate() {

	requestAnimationFrame( animate );
	render();
	stats.update();

}

function render() {
	var timer = Date.now() * 0.0005;

	var m2 = scene.children[6];

	camera.position.x = (objX - camera.position.x) * 0.001;
  camera.position.y = (- objY - camera.position.y) * 0.001;

	camera.lookAt(scene.position);
  renderer.render(scene, camera);

}

<commit_msg>adds commenting to clarify js code<commit_after>var mp = .3,
		mr = .5,
		ms = .01;

var mesh;
var loader = new THREE.STLLoader();
var material;

var Menu = function() {
	this.STL_file = './models/Wwrench.stl',
	this.position = mp;
	this.rotation = mr;
	this.scale = ms;
};

if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var container, stats;
var camera, cameraTarget, scene, renderer;

var mouseX = 0, mouseY = 0;
var faceX = 0, faceY = 0;
var objX = 0, objY = 0;

var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var context2 = canvas.getContext('2d');

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

init();
animate();

function init() {

	container = document.createElement( 'div' );
	document.body.appendChild( container );

	camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
	camera.position.set( 3, 0.15, 3 );

	cameraTarget = new THREE.Vector3( 0, -0.25, 0 );

	scene = new THREE.Scene();
	scene.fog = new THREE.Fog( 0x72645b, 2, 15 );

  var PI2 = Math.PI * 2;
  var program = function (context) {
    context.beginPath();
    context.arc(0, 0, 0.5, 0, PI2, true);
    context.fill();
	}

	var program2 = function (context) {
    context.beginPath();
    context.arc(0, 0, 0.5, 0, PI2, true);
    context.fill();
	}

	// Ground (grabbed from three js lib)

	var plane = new THREE.Mesh(
		new THREE.PlaneBufferGeometry( 40, 40 ),
		new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
	);
	plane.rotation.x = -Math.PI/2;
	plane.position.y = -0.5;
	scene.add( plane );

	plane.receiveShadow = true;

	// load STL
	material = new THREE.MeshPhongMaterial( { color: 0xAAAAAA, specular: 0x111111, shininess: 200 } );

	loader.load( './models/Wwrench.stl', function ( geometry ) {

		var meshMaterial = material;
		if (geometry.hasColors) {
			meshMaterial = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
		}

		mesh = new THREE.Mesh( geometry, meshMaterial );
		mesh.position.set( mp, mp, 0 );
		mesh.rotation.set(  Math.PI * mr, 2 * Math.PI * mr, Math.PI * mr );
		mesh.scale.set( ms, ms, ms );

		mesh.castShadow = true;
		mesh.receiveShadow = true;

		scene.add( mesh );

	} );

	// Ambient Light

	scene.add( new THREE.AmbientLight( 0x777777 ) );

	addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
	addShadowedLight( 0.5, 1, -1, 0xffaa00, 1 );

	// The Renderer

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	renderer.gammaInput = true;
	renderer.gammaOutput = true;

	renderer.shadowMapEnabled = true;
	renderer.shadowMapCullFace = THREE.CullFaceBack;

	container.appendChild( renderer.domElement );

	// Stats on top left

	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '0px';
	container.appendChild( stats.domElement );

	window.addEventListener( 'resize', onWindowResize, false );

}

function addShadowedLight( x, y, z, color, intensity ) {

	var directionalLight = new THREE.DirectionalLight( color, intensity );
	directionalLight.position.set( x, y, z );
	scene.add( directionalLight );

	directionalLight.castShadow = true;

	var d = 1;
	directionalLight.shadowCameraLeft = -d;
	directionalLight.shadowCameraRight = d;
	directionalLight.shadowCameraTop = d;
	directionalLight.shadowCameraBottom = -d;

	directionalLight.shadowCameraNear = 1;
	directionalLight.shadowCameraFar = 4;

	directionalLight.shadowMapWidth = 1024;
	directionalLight.shadowMapHeight = 1024;

	directionalLight.shadowBias = -0.005;
	directionalLight.shadowDarkness = 0.15;

}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize( window.innerWidth, window.innerHeight );

}

window.onload = function() {

	// CAD Menu
	var panel = new Menu();
	var gui = new dat.GUI();

	var file = gui.add(panel, 'STL_file');

	var positionF = gui.add(panel, 'position', 0, 1); // Min and max
	var rotationF = gui.add(panel, 'rotation', 0, 2); // Min and max
	var scaleF = gui.add(panel, 'scale', 0, 1); // Min and max

	positionF.onChange(function(value){
		mesh.position.set( value, value, 0 );
		mp = value;
	});

	rotationF.onChange(function(value){
		mesh.rotation.set(  Math.PI * value, Math.PI *2* value, Math.PI * value );
		mr = value;
	});

	scaleF.onChange(function(value){
		mesh.scale.set( value, value, value );
		ms = value;
	});

	file.onFinishChange(function(value){

		console.log('new STL: ' + value);
		scene.remove(mesh);
		console.log('old STL mesh removed');

		loader.load( value, function ( geometry ) {

			var meshMaterial = material;
			if (geometry.hasColors) {
				meshMaterial = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
			}
			mesh = new THREE.Mesh( geometry, meshMaterial );
			mesh.position.set( mp, mp, 0 );
			mesh.rotation.set(  Math.PI * mr, 2 * Math.PI * mr, Math.PI * mr );
			mesh.scale.set( ms, ms, ms );
			mesh.castShadow = true;
			mesh.receiveShadow = true;
			scene.add( mesh );
		} );

		console.log('new STL loaded');

	});

	/* END CAD MENU STUFF*/

	// Adds color tracker object
  var trackerC = new tracking.ColorTracker();
  trackerC.setMinDimension(5);
  trackerC.setMinGroupSize(10);
  tracking.track('#video', trackerC, { camera: true });
  trackerC.on('track', onColorMove);
};

//Sets color tracking frame size
function onColorMove(event) {
  if (event.data.length === 0) {
    return;
  }
  var maxRect;
  var maxRectArea = 0;
  event.data.forEach(function(rect) {
    if (rect.width * rect.height > maxRectArea){
      maxRectArea = rect.width * rect.height;
      maxRect = rect;
    }
  });
  if (maxRectArea > 0) {
    var rectCenterX = maxRect.x + (maxRect.width/2);
    var rectCenterY = maxRect.y + (maxRect.height/2);
    objX = (rectCenterX - 160) * (window.innerWidth/320) * 10;
    objY = (rectCenterY - 120) * (window.innerHeight/240) * 10;
    context2.clearRect(0, 0, canvas.width, canvas.height);
    context2.strokeStyle = maxRect.color;
    context2.strokeRect(maxRect.x, maxRect.y, maxRect.width, maxRect.height);
    //shows pixels of color tracking frame
    context2.font = '11px Helvetica';
    context2.fillStyle = "#fff";
    context2.fillText('x: ' + maxRect.x + 'px', maxRect.x + maxRect.width + 5, maxRect.y + 11);
    context2.fillText('y: ' + maxRect.y + 'px', maxRect.x + maxRect.width + 5, maxRect.y + 22);
  }
}

function animate() {

	requestAnimationFrame( animate );
	render();
	stats.update();

}

function render() {

	camera.position.x = (objX - camera.position.x) * 0.001;
  camera.position.y = (- objY - camera.position.y) * 0.001;

	camera.lookAt(scene.position);
  renderer.render(scene, camera);

}

<|endoftext|>


<commit_before>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 300;
    var w = 800;
    var padding = 30;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.selectAll("path.line")
       .data(json)
       .enter().append("path")
         .classed("line", true)
         .attr("stroke", function(d, index) {
           return colors(index);
         })
         .attr("d", function(dataset) {
           return line(dataset.datapoints);
         });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(json[0].datapoints, x0, 1),
            d0 = json[0].datapoints[i - 1],
            d1 = json[0].datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });
  }

  getGraphSources().forEach(function(source) {
    d3.json(source, function(err, json) {
      if(err && !json) {
        renderError(err, source);
      } else {
        renderGraph("body", json);
      }
    });
  });
})();
<commit_msg>Minor dimension tweak for dev<commit_after>(function(undefined) {
  function getGraphSources() {
    var graphSources = [];
    d3.selectAll(".graph").each(function() {
      graphSources.push(d3.select(this).attr("data-src"));
    });
    return graphSources;
  }

  function renderError(err, source) {
    console.error("Error retrieving " + source + ": " + err);
  }

  /* Graphite structures points as [value, timestamp] */
  function xVal(point) { return new Date(1000 * point[1]) }
  function yVal(point) { return point[0] }

  var bisectDate = d3.bisector(function(d) { return xVal(d); }).left;

  function renderGraph(el, json) {
    var colors = d3.scale.category10();

    var h = 600;
    var w = 700;
    var padding = 80;

    var xScale = d3.time.scale()
      .range([padding, w - padding])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, xVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, xVal) })
      ]);

    var yScale = d3.scale.linear()
      .range([h - padding, 0])
      .domain([
        d3.min(json, function(d) { return d3.min(d.datapoints, yVal) }),
        d3.max(json, function(d) { return d3.max(d.datapoints, yVal) }),
      ]);

    var xAxis = d3.svg.axis()
      .scale(xScale)
      .orient("bottom");

    var yAxis = d3.svg.axis()
      .scale(yScale)
      .orient("left");

    var line = d3.svg.line()
      .interpolate("basis")
      .x(function(d) { return xScale(xVal(d)); })
      .y(function(d) { return yScale(yVal(d)); })
      .interpolate("monotone")
      .defined(function(d) { return !isNaN(yVal(d)); });

    var svg = d3.select(el)
                .append("svg")
                .attr("height", h)
                .attr("width", w);

    var legend = d3.select(el)
                   .append("ul")
                   .classed("legend", true)
                   .select("li")
                   .data(json)
                   .enter()
                     .append("li")
                     .text(function(d) { return d.target; })
                     .style("color", function(d, index) { return colors(index); });

    svg.selectAll("path.line")
       .data(json)
       .enter().append("path")
         .classed("line", true)
         .attr("stroke", function(d, index) {
           return colors(index);
         })
         .attr("d", function(dataset) {
           return line(dataset.datapoints);
         });

    svg.append("g")
      .classed("x-axis", true)
      .attr("transform", "translate(0, " + (h - padding) + ")")
      .call(xAxis);

    svg.append("g")
      .classed("y-axis", true)
      .attr("transform", "translate(" + padding + ", 0)")
      .call(yAxis);

    var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

    focus.append("line")
      .attr("x1", 0)
      .attr("x2", 0)
      .attr("y1", 0)
      .attr("y2", h - padding);

    svg.append("rect")
      .attr("class", "overlay")
      .attr("x", padding)
      .attr("y", 0)
      .attr("width", w - 2 * padding)
      .attr("height", h - padding)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout",  function() { focus.style("display", "none"); })
      .on("mousemove", function() {
        /* TODO validate the assumption that the first series in the json will
         * have x values for the whole shebang */
        var x0 = xScale.invert(d3.mouse(this)[0]),
            i = bisectDate(json[0].datapoints, x0, 1),
            d0 = json[0].datapoints[i - 1],
            d1 = json[0].datapoints[i];
        if(d0 && d1) {
          var d = x0 - xVal(d0) > xVal(d1) - x0 ? d1 : d0;
        } else if(d0) {
          var d = d0;
        } else if(d1) {
          var d = d1;
        } else {
          console.log("Failed to get datapoint for highlight");
        }
        focus.attr("transform", "translate(" + xScale(xVal(d)) + ",0)");
      });
  }

  getGraphSources().forEach(function(source) {
    d3.json(source, function(err, json) {
      if(err && !json) {
        renderError(err, source);
      } else {
        renderGraph("body", json);
      }
    });
  });
})();
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');

const plugins = require('./plugins');
const paths = require('./paths');

const {
  ROOT,
  MODULES,
  FRONTEND,
  UI,
  STATIC
} = paths;

module.exports = {
  context: ROOT,
  entry: `./${path.relative(ROOT, path.join(FRONTEND, 'index.js'))}`,
  resolve: {
    modules: MODULES,
    alias: fs.readdirSync(FRONTEND)
      .map((name) => path.join(FRONTEND, name))
      .filter((fullpath) => fs.statSync(fullpath).isDirectory())
      .reduce((aliases, fullpath) => Object.assign(aliases, {
        [`@${path.basename(fullpath)}`]: fullpath
      }), {
        '@root': FRONTEND,
        '@ui': UI
      })
  },
  resolveLoader: {
    modules: MODULES
  },
  output: {
    path: STATIC,
    publicPath: '/static/',
    filename: '[name].js'
  },
  plugins: [
    plugins['no-errors'],
    plugins['define'],
    plugins['shell']
  ],
  module: {
    loaders: [{
      test: /js?$/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loaders: [
        'babel-loader'
      ]
    }, {
      test: /\.json?$/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loaders: [
        'json-loader'
      ]
    }, {
      test: /\.png/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loader: [
        'url-loader'
      ]
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      exclude: /node_modules/,
      loader: 'file-loader',
      include: [
        FRONTEND,
        UI
      ]
    },
    {
      test: /\.css$/,
      exclude: /node_modules/,
      loaders: [ 'style-loader', 'css-loader' ],
      include: [
        FRONTEND,
        UI
      ]
    }]
  }
};
<commit_msg>Fix broken production deployments<commit_after>const path = require('path');
const fs = require('fs');

const plugins = require('./plugins');
const paths = require('./paths');

const {
  ROOT,
  MODULES,
  FRONTEND,
  UI,
  STATIC
} = paths;

module.exports = {
  context: ROOT,
  entry: `./${path.relative(ROOT, path.join(FRONTEND, 'index.js'))}`,
  resolve: {
    modules: MODULES,
    alias: fs.readdirSync(FRONTEND)
      .map((name) => path.join(FRONTEND, name))
      .filter((fullpath) => fs.statSync(fullpath).isDirectory())
      .reduce((aliases, fullpath) => Object.assign(aliases, {
        [`@${path.basename(fullpath)}`]: fullpath
      }), {
        '@root': FRONTEND,
        '@ui': UI
      })
  },
  resolveLoader: {
    modules: MODULES
  },
  output: {
    path: STATIC,
    publicPath: '/static/',
    filename: '[name].js'
  },
  plugins: [
    plugins['no-errors'],
    plugins['define'],
    plugins['shell']
  ],
  module: {
    loaders: [{
      test: /js?$/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loaders: [
        'babel-loader'
      ]
    }, {
      test: /\.json?$/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loaders: [
        'json-loader'
      ]
    }, {
      test: /\.png/,
      exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
      loader: [
        'url-loader'
      ]
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file-loader',
      // XXX: By commenting this out, production "BUILD=production make compile"
      //      will break.
      //
      // exclude: /node_modules/,
      include: [
        FRONTEND,
        UI
      ],
    },
    {
      test: /\.css$/,
      exclude: /node_modules/,
      loaders: [ 'style-loader', 'css-loader' ],
      include: [
        FRONTEND,
        UI
      ]
    }]
  }
};
<|endoftext|>


<commit_before>/**
 * @class Denkmal_Component_MessageAdd
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_MessageAdd = Denkmal_Component_Abstract.extend({

  /** @type String */
  _class: 'Denkmal_Component_MessageAdd',

  events: {
    'click .showForm': function() {
      this.toggleActive(true);
    },
    'click .hideForm': function() {
      this.toggleActive(false);
    }
  },

  childrenEvents: {
    'Denkmal_FormField_Tags toggleText': function(state) {
      this.toggleText(state);
    }
  },

  /**
   * @param {Boolean} state
   */
  toggleActive: function(state) {
    this.$el.toggleClass('state-active', state);
  },

  /**
   * @param {Boolean} state
   */
  toggleText: function(state) {
    this.$('.form').toggleClass('state-text', state);
  }
});
<commit_msg>Fix message form resetting<commit_after>/**
 * @class Denkmal_Component_MessageAdd
 * @extends Denkmal_Component_Abstract
 */
var Denkmal_Component_MessageAdd = Denkmal_Component_Abstract.extend({

  /** @type String */
  _class: 'Denkmal_Component_MessageAdd',

  events: {
    'click .showForm': function() {
      this.toggleActive(true);
    },
    'click .hideForm': function() {
      this.toggleActive(false);
    }
  },

  childrenEvents: {
    'Denkmal_FormField_Tags toggleText': function(view, state) {
      this.toggleText(state);
    }
  },

  /**
   * @param {Boolean} state
   */
  toggleActive: function(state) {
    this.$el.toggleClass('state-active', state);
    if (!state) {
      this.findChild('Denkmal_Form_Message').reset();
    }
  },

  /**
   * @param {Boolean} state
   */
  toggleText: function(state) {
    this.$('.form').toggleClass('state-text', state);
  }
});
<|endoftext|>


<commit_before>var Tethys = (function (my) {

    document.querySelector('#tree').addEventListener('click', function (event) {
        if (event.target.className.indexOf('file') !== -1) {
            var fileId = event.target.dataset.fileid;
            if (fileId === 'new') {
                var parentId = event.target.dataset.parent;
                Modal.onsubmit["createFile"] = function (button, input) {
                    var newName = input[0];
                    if (newName.length <= 0) newName = "New " + button;
                    if (button === 'file') {
                        FileSystem.mkfile(parentId, newName);
                        Modal.close();
                    } else if (button === 'folder'){
                        FileSystem.mkdir(parentId, newName);
                        Modal.close();
                    } else if (button === "github"){
                        Modal.onsubmit["github"] = function(button, input){
                            FileSystem.fetchRepo(parentId, input[0], input[1]);
                            Modal.close();
                        }
                        Modal.open("github");
                    }else{
                        Modal.close();
                    }
                }
                Modal.open('createFile');
                document.querySelector("#fileUpload").addEventListener('change', function(event){
                    var files = event.target.files;
                    for (var i=0; i<files.length; i++){
                        FileSystem.loadFile(files[i], parentId);
                    }
                    Modal.close();
                });
            } else if (fileId === 'delete'){
                var parentId = event.target.dataset.parent;
                var fileName = event.target.dataset.name;
                Modal.onsubmit["confirmFolderDelete"] = function (button, input) {
                    if (button === 'yes') {
                        FileSystem.del(parentId);
                    }
                    Modal.close();
                }
                Modal.open('confirmFolderDelete',{name:fileName});
            }else {
                FileSystem.open(fileId);
            }

        }
    });

    document.querySelector('#delete').addEventListener('click', function (event) {
        Modal.onsubmit["confirmDelete"] = function (button, input) {
            if (button === 'yes') {
                FileSystem.delCurrent();
            }
            Modal.close();
        }
        Modal.open('confirmDelete', FileSystem.workingFile);
    });

    var toolbarCollapsed=false;
    document.querySelector('#collapsetoolbar').addEventListener('click', function (event) {
        toolbarCollapsed=!toolbarCollapsed;
        if (toolbarCollapsed){
            document.querySelector('.toolbar').style.height='30px';
            document.querySelector('.workspace').style.bottom='30px';
            document.querySelector('.sidebar').style.bottom='30px';
            document.querySelector('.roomlist .panel-topbar').style.display = 'none';
            document.querySelector('.onlinelist .panel-topbar').style.display = 'none';
            document.querySelector('.onlinelist').style.border = '0';
        }else{
            document.querySelector('.toolbar').style.height='';
            document.querySelector('.workspace').style.bottom='';
            document.querySelector('.sidebar').style.bottom='';
            document.querySelector('.roomlist .panel-topbar').style.display = '';
            document.querySelector('.onlinelist .panel-topbar').style.display = '';
            document.querySelector('.onlinelist').style.border = '';
        }
    });

    var sidebarCollapsed=false;
    document.querySelector('#collapsesidebar').addEventListener('click', function (event) {
        sidebarCollapsed=!sidebarCollapsed;
        if (sidebarCollapsed){
            document.querySelector('.sidebar').style.width='30px';
            document.querySelector('.workspace').style.left='30px';
            document.querySelector('#tree').style.display='none';
            document.querySelector('.sidebar .panel-topbar').style.display='none';
        }else{
            document.querySelector('.sidebar').style.width='';
            document.querySelector('.workspace').style.left='';
            document.querySelector('#tree').style.display='';
            document.querySelector('.sidebar .panel-topbar').style.display='';
        }
    });

    document.querySelector('#savezip').addEventListener('click', function (event) {
        FileSystem.saveAsZip();
    });

    document.querySelector('#settings').addEventListener('click', function (event) {
        Modal.onsubmit['themes'] = function(button, input){
            FileSystem.setTheme(button);
        }
        Modal.open("themes");
    });

    document.querySelector('#roomlist').addEventListener('click', function (event) {
        if (event.target.className.indexOf('square') !== -1) {
            var imgEl = event.target.getElementsByTagName('img')[0];
            var userID = imgEl.dataset.userid;
            var name = imgEl.dataset.name;
            if (userID === "me" || !SocketAPI.isMyRoom) return;
            Modal.onsubmit["confirmKick"] = function () {
                SocketAPI.kick(userID);
                Modal.close();
            };
            Modal.open('confirmKick', {
                name: name
            });
        }
    });

    document.querySelector('#onlinelist').addEventListener('click', function (event) {
        if (event.target.className.indexOf('square') !== -1) {
            var imgEl = event.target.getElementsByTagName('img')[0];
            var userID = imgEl.dataset.userid;
            var name = imgEl.dataset.name;
            if (userID === "me") return;
            Modal.onsubmit["requestInvite"] = function () {
                SocketAPI.requestRoom(userID);
                Modal.close();
            };
            Modal.open('requestInvite', {
                name: name
            });
        }
    });

    var me;
    var username;
    var hash;
    Modal.onsubmit['intro'] = function (button, input) {
        if (!input[0] || input[0].length <= 1) {
            input[0]="Guest";
        }
        username = input[0];
        var pic = Math.floor(Math.random() * 95);
        hash = Math.random();
        SocketAPI.joinOnline(username, pic, hash);

        me = {
            id: "me",
            name: "You",
            pic: pic,
            hash : hash
        }
        makeUser(me, "room", true);

        Modal.open('welcome');
    }

    var roomlistElement = document.querySelector("#roomlist > .panel");
    var onlinelistElement = document.querySelector("#onlinelist > .panel");

    var roomElements = {};
    var onlineElements = {};
    var userTemplate = `<img class="user-img" data-name="{{name}}" data-userid="{{id}}" src="img/miniman/avatar-{{pic}}.png"><label>{{name}}</label>`;

    my.roomEmpty = function(){
        return roomElements <= 1;
    }

    var cursors = {};

    function makeCursor(user){
        var img = document.createElement('img');
        img.src="img/pointer.png";
        img.className = "cursor";
        img.displayed=false;
        img.style.display='none';
        cursors[user.id]=document.body.appendChild(img);
    }

    function moveCursor(userId, coords){
        cursors[userId].style.left = coords.x+"px";
        cursors[userId].style.top = coords.y+"px";
    }

    var cursorMoveMutex = false;
    var lastCursor = {x: 0, y:0};
    window.addEventListener('mousemove', function(e){
        if (my.roomEmpty()) return;
        lastCursor={x: e.clientX, y: e.clientY};

        if (cursorMoveMutex) return;  //Ratelimit
        cursorMoveMutex = true;
        setTimeout(function(){
            SocketAPI.moveCursor(lastCursor);
            cursorMoveMutex = false;
        },100);

    });

    window.addEventListener('mouseout', function(e){
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            setTimeout(function(){
                SocketAPI.moveCursor({x:-50, y:-50});
            },500);
        }
    },false);

    SocketAPI.onMoveCursor = function(userId, fileId, coords) {
        if (fileId === FileSystem.workingFile.fileId){
            if (!cursors[userId].displayed){
                cursors[userId].displayed=true;
                cursors[userId].style.display = '';
            }
            moveCursor(userId, coords);
        }else{
            if (cursors[userId].displayed){
                cursors[userId].displayed=false;
                cursors[userId].style.display = 'none';
            }
        }
    }

    function makeUser(user, group, isMe){
        if (user.hash == hash && !isMe) return; //Don't make self
        var div = document.createElement('div');
        div.className = "square";
        div.innerHTML = Microstache.template(userTemplate, user);

        if (group === "online"){
            onlinelistElement.appendChild(div);
            onlineElements[user.id] = div;
        }
        if (group === 'room'){
            roomlistElement.appendChild(div);
            roomElements[user.id] = div;
        }
    }
    function removeUser(user, group){
        var re = roomElements[user.id];
        var we = onlineElements[user.id]
        if (re && re.parentNode == roomlistElement){
            roomlistElement.removeChild(roomElements[user.id]);
        }
        if (we && we.parentNode == onlinelistElement){
            onlinelistElement.removeChild(onlineElements[user.id]);
        }
    }
    function clearRoom(){
        while (roomlistElement.firstChild){
            roomlistElement.removeChild(roomlistElement.firstChild);
        }
        makeUser(me, 'room', true);
    }

    SocketAPI.onOtherJoinOnline = function (user) {
        removeUser(user);
        makeUser(user,'online');
    }
    SocketAPI.onOtherLeftOnline = function (user) {
        removeUser(user);
    }
    SocketAPI.onOtherJoinRoom = function (user) {
        removeUser(user);
        makeUser(user, 'room');
        makeCursor(user); //Make a cursor
    }
    SocketAPI.onOtherLeftRoom = function (user) {
        removeUser(user, 'room');
        cursors[user.id].parentNode.removeChild(cursors[user.id]); // Remove their cursor
    }
    SocketAPI.onWho = function(onlineList){
        for (var i=0; i<onlineList.length; i++){
            removeUser(onlineList[i]);
            makeUser(onlineList[i],'online');
        }
    }
    SocketAPI.onRequestRoom = function(user, orignalId){
        Modal.onsubmit["request-join"]=function(button){
            if (button==="accept"){
                SocketAPI.respondToRoomRequest(user.id, orignalId);
            }
            Modal.close();
        }
        Modal.open('request-join', user);
    }
    SocketAPI.onRoomRespond = function(roomOwner, who){
        Modal.onsubmit['join-response'] = function(){};
        Modal.open('join-response', {name:roomOwner.name});
        clearRoom();
        for (var i=0; i<who.length; i++){
            removeUser(who[i]);
            makeUser(who[i], 'room');
            makeCursor(who[i]);
        }
        document.querySelector("#roomlist > .panel-topbar").innerHTML = roomOwner.name+"'s Room";
    }
    SocketAPI.onKick = function(onlineList){
        clearRoom();
        for (var i=0; i<onlineList.length; i++){
            removeUser(onlineList[i]);
            makeUser(onlineList[i],'online');
        }
        document.querySelector("#roomlist > .panel-topbar").innerHTML = "Your Room";
        Modal.onsubmit['kick-alert'] = function(){};
        Modal.open('kick-alert');
    }

    FileSystem.init(true);
    FileSystem.open("welcome");
    Modal.open('intro');

    var code = Util.getParameterByName("code");
    var ext= Util.getParameterByName("ext");
    var theme = Util.getParameterByName("theme");
    FileSystem.openString(code,ext);
    if (theme){
        FileSystem.setTheme(theme);
    }

    console.log("%c Rock that console! If you're after the source: https://github.com/RationalCoding/MultiHack", "color:#263238; font-size: 15px;");

    return my;
}({}))<commit_msg>remove cursors after dropped connections<commit_after>var Tethys = (function (my) {

    document.querySelector('#tree').addEventListener('click', function (event) {
        if (event.target.className.indexOf('file') !== -1) {
            var fileId = event.target.dataset.fileid;
            if (fileId === 'new') {
                var parentId = event.target.dataset.parent;
                Modal.onsubmit["createFile"] = function (button, input) {
                    var newName = input[0];
                    if (newName.length <= 0) newName = "New " + button;
                    if (button === 'file') {
                        FileSystem.mkfile(parentId, newName);
                        Modal.close();
                    } else if (button === 'folder'){
                        FileSystem.mkdir(parentId, newName);
                        Modal.close();
                    } else if (button === "github"){
                        Modal.onsubmit["github"] = function(button, input){
                            FileSystem.fetchRepo(parentId, input[0], input[1]);
                            Modal.close();
                        }
                        Modal.open("github");
                    }else{
                        Modal.close();
                    }
                }
                Modal.open('createFile');
                document.querySelector("#fileUpload").addEventListener('change', function(event){
                    var files = event.target.files;
                    for (var i=0; i<files.length; i++){
                        FileSystem.loadFile(files[i], parentId);
                    }
                    Modal.close();
                });
            } else if (fileId === 'delete'){
                var parentId = event.target.dataset.parent;
                var fileName = event.target.dataset.name;
                Modal.onsubmit["confirmFolderDelete"] = function (button, input) {
                    if (button === 'yes') {
                        FileSystem.del(parentId);
                    }
                    Modal.close();
                }
                Modal.open('confirmFolderDelete',{name:fileName});
            }else {
                FileSystem.open(fileId);
            }

        }
    });

    document.querySelector('#delete').addEventListener('click', function (event) {
        Modal.onsubmit["confirmDelete"] = function (button, input) {
            if (button === 'yes') {
                FileSystem.delCurrent();
            }
            Modal.close();
        }
        Modal.open('confirmDelete', FileSystem.workingFile);
    });

    var toolbarCollapsed=false;
    document.querySelector('#collapsetoolbar').addEventListener('click', function (event) {
        toolbarCollapsed=!toolbarCollapsed;
        if (toolbarCollapsed){
            document.querySelector('.toolbar').style.height='30px';
            document.querySelector('.workspace').style.bottom='30px';
            document.querySelector('.sidebar').style.bottom='30px';
            document.querySelector('.roomlist .panel-topbar').style.display = 'none';
            document.querySelector('.onlinelist .panel-topbar').style.display = 'none';
            document.querySelector('.onlinelist').style.border = '0';
        }else{
            document.querySelector('.toolbar').style.height='';
            document.querySelector('.workspace').style.bottom='';
            document.querySelector('.sidebar').style.bottom='';
            document.querySelector('.roomlist .panel-topbar').style.display = '';
            document.querySelector('.onlinelist .panel-topbar').style.display = '';
            document.querySelector('.onlinelist').style.border = '';
        }
    });

    var sidebarCollapsed=false;
    document.querySelector('#collapsesidebar').addEventListener('click', function (event) {
        sidebarCollapsed=!sidebarCollapsed;
        if (sidebarCollapsed){
            document.querySelector('.sidebar').style.width='30px';
            document.querySelector('.workspace').style.left='30px';
            document.querySelector('#tree').style.display='none';
            document.querySelector('.sidebar .panel-topbar').style.display='none';
        }else{
            document.querySelector('.sidebar').style.width='';
            document.querySelector('.workspace').style.left='';
            document.querySelector('#tree').style.display='';
            document.querySelector('.sidebar .panel-topbar').style.display='';
        }
    });

    document.querySelector('#savezip').addEventListener('click', function (event) {
        FileSystem.saveAsZip();
    });

    document.querySelector('#settings').addEventListener('click', function (event) {
        Modal.onsubmit['themes'] = function(button, input){
            FileSystem.setTheme(button);
        }
        Modal.open("themes");
    });

    document.querySelector('#roomlist').addEventListener('click', function (event) {
        if (event.target.className.indexOf('square') !== -1) {
            var imgEl = event.target.getElementsByTagName('img')[0];
            var userID = imgEl.dataset.userid;
            var name = imgEl.dataset.name;
            if (userID === "me" || !SocketAPI.isMyRoom) return;
            Modal.onsubmit["confirmKick"] = function () {
                SocketAPI.kick(userID);
                Modal.close();
            };
            Modal.open('confirmKick', {
                name: name
            });
        }
    });

    document.querySelector('#onlinelist').addEventListener('click', function (event) {
        if (event.target.className.indexOf('square') !== -1) {
            var imgEl = event.target.getElementsByTagName('img')[0];
            var userID = imgEl.dataset.userid;
            var name = imgEl.dataset.name;
            if (userID === "me") return;
            Modal.onsubmit["requestInvite"] = function () {
                SocketAPI.requestRoom(userID);
                Modal.close();
            };
            Modal.open('requestInvite', {
                name: name
            });
        }
    });

    var me;
    var username;
    var hash;
    Modal.onsubmit['intro'] = function (button, input) {
        if (!input[0] || input[0].length <= 1) {
            input[0]="Guest";
        }
        username = input[0];
        var pic = Math.floor(Math.random() * 95);
        hash = Math.random();
        SocketAPI.joinOnline(username, pic, hash);

        me = {
            id: "me",
            name: "You",
            pic: pic,
            hash : hash
        }
        makeUser(me, "room", true);

        Modal.open('welcome');
    }

    var roomlistElement = document.querySelector("#roomlist > .panel");
    var onlinelistElement = document.querySelector("#onlinelist > .panel");

    var roomElements = {};
    var onlineElements = {};
    var userTemplate = `<img class="user-img" data-name="{{name}}" data-userid="{{id}}" src="img/miniman/avatar-{{pic}}.png"><label>{{name}}</label>`;

    my.roomEmpty = function(){
        return roomElements <= 1;
    }

    var cursors = {};

    function makeCursor(user){
        var img = document.createElement('img');
        img.src="img/pointer.png";
        img.className = "cursor";
        img.displayed=false;
        img.style.display='none';
        cursors[user.id]=document.body.appendChild(img);
    }

    function moveCursor(userId, coords){
        cursors[userId].style.left = coords.x+"px";
        cursors[userId].style.top = coords.y+"px";
    }

    var cursorMoveMutex = false;
    var lastCursor = {x: 0, y:0};
    window.addEventListener('mousemove', function(e){
        if (my.roomEmpty()) return;
        lastCursor={x: e.clientX, y: e.clientY};

        if (cursorMoveMutex) return;  //Ratelimit
        cursorMoveMutex = true;
        setTimeout(function(){
            SocketAPI.moveCursor(lastCursor);
            cursorMoveMutex = false;
        },100);

    });

    window.addEventListener('mouseout', function(e){
        e = e ? e : window.event;
        var from = e.relatedTarget || e.toElement;
        if (!from || from.nodeName == "HTML") {
            setTimeout(function(){
                SocketAPI.moveCursor({x:-50, y:-50});
            },500);
        }
    },false);

    SocketAPI.onMoveCursor = function(userId, fileId, coords) {
        if (fileId === FileSystem.workingFile.fileId){
            if (!cursors[userId].displayed){
                cursors[userId].displayed=true;
                cursors[userId].style.display = '';
            }
            moveCursor(userId, coords);
        }else{
            if (cursors[userId].displayed){
                cursors[userId].displayed=false;
                cursors[userId].style.display = 'none';
            }
        }
    }

    function makeUser(user, group, isMe){
        if (user.hash == hash && !isMe) return; //Don't make self
        var div = document.createElement('div');
        div.className = "square";
        div.innerHTML = Microstache.template(userTemplate, user);

        if (group === "online"){
            onlinelistElement.appendChild(div);
            onlineElements[user.id] = div;
        }
        if (group === 'room'){
            roomlistElement.appendChild(div);
            roomElements[user.id] = div;
        }
    }
    function removeUser(user, group){
        var re = roomElements[user.id];
        var we = onlineElements[user.id]
        if (re && re.parentNode == roomlistElement){
            roomlistElement.removeChild(roomElements[user.id]);
        }
        if (we && we.parentNode == onlinelistElement){
            onlinelistElement.removeChild(onlineElements[user.id]);
        }
    }
    function clearRoom(){
        while (roomlistElement.firstChild){
            roomlistElement.removeChild(roomlistElement.firstChild);
        }
        makeUser(me, 'room', true);
    }

    SocketAPI.onOtherJoinOnline = function (user) {
        removeUser(user);
        makeUser(user,'online');
    }
    SocketAPI.onOtherLeftOnline = function (user) {
        removeUser(user);
        if (cursors[user.id]){
            cursors[user.id].parentNode.removeChild(cursors[user.id]); // Remove their cursor
        }
    }
    SocketAPI.onOtherJoinRoom = function (user) {
        removeUser(user);
        makeUser(user, 'room');
        makeCursor(user); //Make a cursor
    }
    SocketAPI.onOtherLeftRoom = function (user) {
        removeUser(user, 'room');
        if (cursors[user.id]){
            cursors[user.id].parentNode.removeChild(cursors[user.id]); // Remove their cursor
        }
    }
    SocketAPI.onWho = function(onlineList){
        for (var i=0; i<onlineList.length; i++){
            removeUser(onlineList[i]);
            makeUser(onlineList[i],'online');
        }
    }
    SocketAPI.onRequestRoom = function(user, orignalId){
        Modal.onsubmit["request-join"]=function(button){
            if (button==="accept"){
                SocketAPI.respondToRoomRequest(user.id, orignalId);
            }
            Modal.close();
        }
        Modal.open('request-join', user);
    }
    SocketAPI.onRoomRespond = function(roomOwner, who){
        Modal.onsubmit['join-response'] = function(){};
        Modal.open('join-response', {name:roomOwner.name});
        clearRoom();
        for (var i=0; i<who.length; i++){
            removeUser(who[i]);
            makeUser(who[i], 'room');
            makeCursor(who[i]);
        }
        document.querySelector("#roomlist > .panel-topbar").innerHTML = roomOwner.name+"'s Room";
    }
    SocketAPI.onKick = function(onlineList){
        clearRoom();
        for (var i=0; i<onlineList.length; i++){
            removeUser(onlineList[i]);
            makeUser(onlineList[i],'online');
        }
        document.querySelector("#roomlist > .panel-topbar").innerHTML = "Your Room";
        Modal.onsubmit['kick-alert'] = function(){};
        Modal.open('kick-alert');
    }

    FileSystem.init(true);
    FileSystem.open("welcome");
    Modal.open('intro');

    var code = Util.getParameterByName("code");
    var ext= Util.getParameterByName("ext");
    var theme = Util.getParameterByName("theme");
    FileSystem.openString(code,ext);
    if (theme){
        FileSystem.setTheme(theme);
    }

    console.log("%c Rock that console! If you're after the source: https://github.com/RationalCoding/MultiHack", "color:#263238; font-size: 15px;");

    return my;
}({}))<|endoftext|>