<commit_before>
// The textbook is stored in brackets.currentTextbook

function createNewTextbook() {
	var newTextbook 		= {};
	newTextbook.title 		= "Title";
	newTextbook.author 		= "Author";
	newTextbook.elements 	= [];
	return newTextbook;
}

function textbookIsWellDefined(textbook) {
	if (typeof(textbook.title) != "string") {
		return false;
	}
	else if (typeof(textbook.author) != "string") {
		return false;
	}
	else if (!(textbook.elements.isArray)) {
		return false;
	}
	else {
		// For each of the elements, see if they are well defined
		// If one of them is not, then the whole textbook is not, so return false
		var numberOfElements = textbook.elements.length;
		for (var el = 0; el < numberOfElements; el++) {
			if (!(elementIsWellDefined(textbook.elements[el]))) return false;
		}
		return true;
	}
}

function elementIsWellDefined(element) {
	// Check that element has a type that is a string
	if (typeof(element.type) != "string") {
		return false;
	}
	// Check that element has comments
	else if (!(element.comments.isArray)) {
		return false;
	}

	else {
		// Check that comments are well defined
		var numberOfComments = element.comments.length;
		for (var comm = 0; comm < numberOfComments; comm++) {
			if (!(commentIsWellDefined(element.comments[comm]))) return false;
		}
		// Check that rest is well defined for the different types of elements
		switch(element.type) {
			case 'pdfRectangle':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startX) != "number" ||
						 typeof(element.startY) != "number" ||
						 typeof(element.endX) != "number" ||
						 typeof(element.endY) != "number" ||
						 typeof(element.page) != "number") {
					return false;
				}
				// Check that end is after start
				else if (element.startX >= element.endX ||
						 element.startY >= element.endY) {
					return false;
				}
				else {
					return true;
				}
			case 'pdfHorizontal':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startY) != "number" ||
						 typeof(element.endY) != "number") {
					return false;
				}
				// Check that end is after start
				else if (element.startY >= element.endY) {
					return false;
				}
				else {
					return true;
				}
			case 'youtube':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startTime) != "number") {
					return false;
				}
				// Check that startTime is after 0
				else if (element.startTime >= 0) {
					return false;
				}
				else {
					return true;
				}
			case 'text' :
				// Check that element has a text field
				if (typeof(element.text) != "string") {
					return false;
				}
				else {
					return true;
				}
			case 'wikipedia':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				else {
					return true;
				}
			case 'image':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				else {
					return true;
				}
			default:
				return false;
				break;
		}
	}
}

function commentIsWellDefined(comment) {
	// Check that comment has an author that is a string
	if (typeof(comment.author) != "string") {
		return false;
	}
	// Check that comment has a comment that is a string
	else if (typeof(comment.comment) != "string") {
		return false;
	}
	else {
		return true;
	}
}

function modifyTitle(newTitle) {
	if (newTitle.length) {
		brackets.currentTextbook.title = newTitle;
	}
}

function modifyAuthor(newAuthor) {
	if (newAuthor.length) {
		brackets.currentTextbook.author = newAuthor;
	}
}

function addPDFRectangleClip(source,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.page		= Math.floor(startX);
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addPDFRectangleClip(source,page,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.page		= page;
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addPDFHorizontalClip(source,startY,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfHorizontal";
	newElement.source 	= source;
	newElement.startY 	= startY;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addYouTubeVid(source) {
	var newElement 		 = {};
	newElement.type 	 = "youtube";
	newElement.source 	 = source;
	newElement.comments  = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}
function addYouTubeVid(source, start, end) {
	var newElement 		 = {};
	newElement.type 	 = "youtube";
	newElement.source 	 = source;
	newElement.start 	 = start;
	newElement.end 		 = end;
	newElement.comments  = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addText(text) {
	var newElement 		= {};
	newElement.type 	= "text";
	newElement.text 	= text;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addWiki(source) {
	var newElement 		= {};
	newElement.type 	= "wikipedia";
	newElement.source 	= source;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addImage(source) {
	var newElement 		= {};
	newElement.type 	= "image";
	newElement.source 	= source;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
	renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function previousPDFs() {
	var pdfLinks = [];

	if (typeof brackets.currentTextbook === "undefined") {
	  return [];
	}

	var numberOfElements = brackets.currentTextbook.elements.length;
	for (var el = 0; el < numberOfElements; el++) {
		if (brackets.currentTextbook.elements[el].type == "pdfRectangle" ||
			brackets.currentTextbook.elements[el].type == "pdfHorizontal") {
			if ($.inArray(brackets.currentTextbook.elements[el].source, pdfLinks) == -1) {
				pdfLinks.push(brackets.currentTextbook.elements[el].source);
			}
		}
	};
	return pdfLinks;
}

// If within range, delete. Else skip
function deleteElement(clipNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (clipNumber >= 0 && clipNumber<numberOfElements) {
		var newElements = [];
		for (var el = 0; el < clipNumber; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		for (var el = clipNumber+1; el < numberOfElements; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		brackets.currentTextbook.elements = newElements;
	}
}

// Move element at index oldPosition in between element at index newPosition and the element at index (newPosition+1)
function moveElement(oldPosition,newPosition) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (oldPosition >= 0 && oldPosition<numberOfElements &&
		newPosition >= 0 && newPosition<numberOfElements) {
		// If no change then return
		if (oldPosition == newPosition) {return;}
		// Copy everything that's not going to be changed
		var newElements = [];
		var firstChange = Math.min(oldPosition,newPosition);
		for (var el = 0; el < firstChange; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		// If move up the page
		if (oldPosition > newPosition) {
			newElements.push(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition; el < oldPosition; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			for (var el = oldPosition+1; el < numberOfElements; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
		// If move down the page
		else {
			for (var el = oldPosition+1; el <= newPosition; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			newElements.push(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition+1; el < numberOfElements; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
	}
}

// Comment functions below

function addComment(elementNumber,author,comment) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		brackets.currentTextbook.elements[elementNumber].comments.push({
			"author"  : author,
			"comment" : comment
		});
	}
}

function deleteComment(elementNumber,commentNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		var numberOfComments = brackets.currentTextbook.elements[elementNumber].comments.length;
		if (commentNumber >= 0 && commentNumber<numberOfComments) {
			var newComments = [];
			for (var comm = 0; comm < commentNumber; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			for (var comm = commentNumber+1; comm < numberOfElements; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			brackets.currentTextbook.elements[elementNumber].comments = newComments;
		}
	}
}

function getCommentAuthors() {
	var authors = [];
	var numberOfElements = brackets.currentTextbook.elements.length;
	var numberOfComments = 0;
	for (var el = 0; el < numberOfElements; el++) {
		numberOfComments = brackets.currentTextbook.elements[el].comments.length;
		for (var comm = 0; comm < numberOfComments; comm++) {
			if (!(contains(authors,brackets.currentTextbook.elements[el].comments[comm].author))) {
				authors.push(brackets.currentTextbook.elements[el].comments[comm].author);
			}
		}
	}
	return authors;
}

function contains(array, needle) {
	for (var i = 0; i < array.length; i++) {
		if(array[i] === needle) {
			return true;
		}
	}
}

function noCommentTextbook() {
	var virginTextbook = {
		"title": brackets.currentTextbook.title,
		"author": brackets.currentTextbook.author,
		"elements": []
	};
	brackets.currentTextbook.elements.forEach(function(element) {
		var virginElement = element;
		virginElement.comments = [];
		virginTextbook.elements.push(virginElement);
	});
	return virginTextbook;
}

function describeTextbook() {
	var textbookString = brackets.currentTextbook.name;
	textbookString += " by " + brackets.currentTextbook.author + "\n";
	var numberOfElements = brackets.currentTextbook.elements.length;
	for (var i = 0; i < length; i++) {
		textbookString += "\n" + i + ": ";
		switch(brackets.currentTextbook.elements[i].type) {
			case 'pdfRectangle':
				textbookString += "Rectangle from " + brackets.currentTextbook.elements[i].source;
			case 'pdfHorizontal':
				textbookString += "Horizontal clip from  " + brackets.currentTextbook.elements[i].source;
			case 'youtube':
				textbookString += "YouTube clip from  " + brackets.currentTextbook.elements[i].source;
			case 'text' :
				textbookString += "Some text";
			case 'wikipedia':
				textbookString += "Wikipedia clip from  " + brackets.currentTextbook.elements[i].source;
			case 'image':
				textbookString += "Image from  " + brackets.currentTextbook.elements[i].source;
			default:
				textbookString += "Undefined type";
		}
	}
}
<commit_msg>Fixes #8<commit_after>
// The textbook is stored in brackets.currentTextbook

function createNewTextbook() {
	var newTextbook 		= {};
	newTextbook.title 		= "Title";
	newTextbook.author 		= "Author";
	newTextbook.elements 	= [];
	return newTextbook;
}

function textbookIsWellDefined(textbook) {
	if (typeof(textbook.title) != "string") {
		return false;
	}
	else if (typeof(textbook.author) != "string") {
		return false;
	}
	else if (!(textbook.elements.isArray)) {
		return false;
	}
	else {
		// For each of the elements, see if they are well defined
		// If one of them is not, then the whole textbook is not, so return false
		var numberOfElements = textbook.elements.length;
		for (var el = 0; el < numberOfElements; el++) {
			if (!(elementIsWellDefined(textbook.elements[el]))) return false;
		}
		return true;
	}
}

function elementIsWellDefined(element) {
	// Check that element has a type that is a string
	if (typeof(element.type) != "string") {
		return false;
	}
	// Check that element has comments
	else if (!(element.comments.isArray)) {
		return false;
	}

	else {
		// Check that comments are well defined
		var numberOfComments = element.comments.length;
		for (var comm = 0; comm < numberOfComments; comm++) {
			if (!(commentIsWellDefined(element.comments[comm]))) return false;
		}
		// Check that rest is well defined for the different types of elements
		switch(element.type) {
			case 'pdfRectangle':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startX) != "number" ||
						 typeof(element.startY) != "number" ||
						 typeof(element.endX) != "number" ||
						 typeof(element.endY) != "number" ||
						 typeof(element.page) != "number") {
					return false;
				}
				// Check that end is after start
				else if (element.startX >= element.endX ||
						 element.startY >= element.endY) {
					return false;
				}
				else {
					return true;
				}
			case 'pdfHorizontal':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startY) != "number" ||
						 typeof(element.endY) != "number") {
					return false;
				}
				// Check that end is after start
				else if (element.startY >= element.endY) {
					return false;
				}
				else {
					return true;
				}
			case 'youtube':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				// Check that element has all coordinates
				else if (typeof(element.startTime) != "number") {
					return false;
				}
				// Check that startTime is after 0
				else if (element.startTime >= 0) {
					return false;
				}
				else {
					return true;
				}
			case 'text' :
				// Check that element has a text field
				if (typeof(element.text) != "string") {
					return false;
				}
				else {
					return true;
				}
			case 'wikipedia':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				else {
					return true;
				}
			case 'image':
				// Check that element has a source that is a string
				if (typeof(element.source) != "string") {
					return false;
				}
				else {
					return true;
				}
			default:
				return false;
				break;
		}
	}
}

function commentIsWellDefined(comment) {
	// Check that comment has an author that is a string
	if (typeof(comment.author) != "string") {
		return false;
	}
	// Check that comment has a comment that is a string
	else if (typeof(comment.comment) != "string") {
		return false;
	}
	else {
		return true;
	}
}

function modifyTitle(newTitle) {
	if (newTitle.length) {
		brackets.currentTextbook.title = newTitle;
	}
}

function modifyAuthor(newAuthor) {
	if (newAuthor.length) {
		brackets.currentTextbook.author = newAuthor;
	}
}

function addPDFRectangleClip(source,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.page		= Math.floor(startX);
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addPDFRectangleClip(source,page,startX,startY,endX,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfRectangle";
	newElement.source 	= source;
	newElement.page		= page;
	newElement.startX 	= startX;
	newElement.startY 	= startY;
	newElement.endX 	= endX;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addPDFHorizontalClip(source,startY,endY) {
	var newElement 		= {};
	newElement.type 	= "pdfHorizontal";
	newElement.source 	= source;
	newElement.startY 	= startY;
	newElement.endY 	= endY;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addYouTubeVid(source) {
	var newElement 		 = {};
	newElement.type 	 = "youtube";
	newElement.source 	 = source;
	newElement.comments  = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}
function addYouTubeVid(source, start, end) {
	var newElement 		 = {};
	newElement.type 	 = "youtube";
	newElement.source 	 = source;
	newElement.start 	 = start;
	newElement.end 		 = end;
	newElement.comments  = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addText(text) {
	var newElement 		= {};
	newElement.type 	= "text";
	newElement.text 	= text;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addWiki(source) {
	var newElement 		= {};
	newElement.type 	= "wikipedia";
	newElement.source 	= source;
	newElement.page		= source.split("/").slice(-1)[0];
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
    renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function addImage(source) {
	var newElement 		= {};
	newElement.type 	= "image";
	newElement.source 	= source;
	newElement.comments = [];
	brackets.currentTextbook.elements.push(newElement);
	renderElement(brackets.textbookContainer, newElement);
	$("#empty-textbook").css("display", "none");
}

function previousPDFs() {
	var pdfLinks = [];

	if (typeof brackets.currentTextbook === "undefined") {
	  return [];
	}

	var numberOfElements = brackets.currentTextbook.elements.length;
	for (var el = 0; el < numberOfElements; el++) {
		if (brackets.currentTextbook.elements[el].type == "pdfRectangle" ||
			brackets.currentTextbook.elements[el].type == "pdfHorizontal") {
			if ($.inArray(brackets.currentTextbook.elements[el].source, pdfLinks) == -1) {
				pdfLinks.push(brackets.currentTextbook.elements[el].source);
			}
		}
	};
	return pdfLinks;
}

// If within range, delete. Else skip
function deleteElement(clipNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (clipNumber >= 0 && clipNumber<numberOfElements) {
		var newElements = [];
		for (var el = 0; el < clipNumber; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		for (var el = clipNumber+1; el < numberOfElements; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		brackets.currentTextbook.elements = newElements;
	}
}

// Move element at index oldPosition in between element at index newPosition and the element at index (newPosition+1)
function moveElement(oldPosition,newPosition) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (oldPosition >= 0 && oldPosition<numberOfElements &&
		newPosition >= 0 && newPosition<numberOfElements) {
		// If no change then return
		if (oldPosition == newPosition) {return;}
		// Copy everything that's not going to be changed
		var newElements = [];
		var firstChange = Math.min(oldPosition,newPosition);
		for (var el = 0; el < firstChange; el++) {
			newElements.push(brackets.currentTextbook.elements[el]);
		}
		// If move up the page
		if (oldPosition > newPosition) {
			newElements.push(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition; el < oldPosition; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			for (var el = oldPosition+1; el < numberOfElements; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
		// If move down the page
		else {
			for (var el = oldPosition+1; el <= newPosition; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			newElements.push(brackets.currentTextbook.elements[oldPosition]);
			for (var el = newPosition+1; el < numberOfElements; el++) {
				newElements.push(brackets.currentTextbook.elements[el]);
			}
			brackets.currentTextbook.elements = newElements;
		}
	}
}

// Comment functions below

function addComment(elementNumber,author,comment) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		brackets.currentTextbook.elements[elementNumber].comments.push({
			"author"  : author,
			"comment" : comment
		});
	}
}

function deleteComment(elementNumber,commentNumber) {
	var numberOfElements = brackets.currentTextbook.elements.length;
	if (elementNumber >= 0 && elementNumber<numberOfElements) {
		var numberOfComments = brackets.currentTextbook.elements[elementNumber].comments.length;
		if (commentNumber >= 0 && commentNumber<numberOfComments) {
			var newComments = [];
			for (var comm = 0; comm < commentNumber; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			for (var comm = commentNumber+1; comm < numberOfElements; el++) {
				newElements.add(brackets.currentTextbook.elements[elementNumber].comments[comm]);
			}
			brackets.currentTextbook.elements[elementNumber].comments = newComments;
		}
	}
}

function getCommentAuthors() {
	var authors = [];
	var numberOfElements = brackets.currentTextbook.elements.length;
	var numberOfComments = 0;
	for (var el = 0; el < numberOfElements; el++) {
		numberOfComments = brackets.currentTextbook.elements[el].comments.length;
		for (var comm = 0; comm < numberOfComments; comm++) {
			if (!(contains(authors,brackets.currentTextbook.elements[el].comments[comm].author))) {
				authors.push(brackets.currentTextbook.elements[el].comments[comm].author);
			}
		}
	}
	return authors;
}

function contains(array, needle) {
	for (var i = 0; i < array.length; i++) {
		if(array[i] === needle) {
			return true;
		}
	}
}

function noCommentTextbook() {
	var virginTextbook = {
		"title": brackets.currentTextbook.title,
		"author": brackets.currentTextbook.author,
		"elements": []
	};
	brackets.currentTextbook.elements.forEach(function(element) {
		var virginElement = element;
		virginElement.comments = [];
		virginTextbook.elements.push(virginElement);
	});
	return virginTextbook;
}

function describeTextbook() {
	var textbookString = brackets.currentTextbook.name;
	textbookString += " by " + brackets.currentTextbook.author + "\n";
	var numberOfElements = brackets.currentTextbook.elements.length;
	for (var i = 0; i < length; i++) {
		textbookString += "\n" + i + ": ";
		switch(brackets.currentTextbook.elements[i].type) {
			case 'pdfRectangle':
				textbookString += "Rectangle from " + brackets.currentTextbook.elements[i].source;
			case 'pdfHorizontal':
				textbookString += "Horizontal clip from  " + brackets.currentTextbook.elements[i].source;
			case 'youtube':
				textbookString += "YouTube clip from  " + brackets.currentTextbook.elements[i].source;
			case 'text' :
				textbookString += "Some text";
			case 'wikipedia':
				textbookString += "Wikipedia clip from  " + brackets.currentTextbook.elements[i].source;
			case 'image':
				textbookString += "Image from  " + brackets.currentTextbook.elements[i].source;
			default:
				textbookString += "Undefined type";
		}
	}
}
<|endoftext|>


<commit_before>const UserList = (function(){
  function UserList(sys){
    this.sys = sys;
    this.dom = sys.gui.initUserList();
    this.users = {};
  }

  UserList.prototype.show = function(){
    this.dom.style.display = "block";
  };

  UserList.prototype.hide = function(){
    this.dom.style.display = "none";
  };

  UserList.prototype.remove = function(nick){
    if(typeof this.users[nick] === "undefined"){
      return false;
    }
    this.users[nick].remove(nick);
    delete this.users[nick];
    return true;
  };

  UserList.prototype.append = function(nick, avatar){
    const container = document.createElement("div");
    container.className = "user-item";

    if(avatar){
      const a = document.createElement("span");
      a.style.backgroundImage = "url('"+avatar+"')";
      a.className = "user-list-avatar";
      container.appendChild(a);
    }

    const name = document.createElement("span");
    name.className = "nick";
    name.innerHTML = nick;
    container.appendChild(name);
    const self = this;
    name.onclick = function(){
      const my = self.users[myNick];
      var m = [];
      if(nick == myNick){
        m.push([
          function(){
            var newNick = prompt(language["writeNick"]);
            if(newNick){
              send("Bot", "/nick "+newNick);
            }
          },
          language["changeNick"]
        ]);
      }else if(my.isOp){
        m.push([
          function(){
            alert(typeof sys.currentPage());
            send(sys.currentPage().name, "/kick "+nick);
          },
          language["kick"]
        ]);
        m.push([
          function(){
            send(sys.currentPage().name, "/ban "+nick);
          },
          language["ban"]
        ]);
      }

      for(var i=0;i<m.length;i++){
         const item = document.createElement("div");
         item.onclick = m[i][0];
         item.innerHTML = m[i][1];
         menu.appendChild(item);
      }
      if(menu.offsetParent == null){
        menu.style.display = "block";
      }else{
        menu.style.display = "none";
        menu.innerHTML = "";
      }
    };

    const menu = document.createElement("div");
    menu.className = "menu";
    menu.style.display = "none";
    container.appendChild(menu);

    this.dom.appendChild(container);
    this.users[nick] = new User(container, nick);
  };

  UserList.prototype.updateNick = function(old, news){
     if(typeof this.users[old] === "undefined"){
       return false;
     }

     this.users[old].updateNick(news);
     this.users[news] = this.users[old];
     delete this.users[old];
  };

  UserList.prototype.get = function(nick){
    if(typeof this.users[nick] === "undefined")
      return null;
    return this.users[nick];
  };

  return UserList;
})();
<commit_msg>Update userlist.js<commit_after>const UserList = (function(){
  function UserList(sys){
    this.sys = sys;
    this.dom = sys.gui.initUserList();
    this.users = {};
  }

  UserList.prototype.show = function(){
    this.dom.style.display = "block";
  };

  UserList.prototype.hide = function(){
    this.dom.style.display = "none";
  };

  UserList.prototype.remove = function(nick){
    if(typeof this.users[nick] === "undefined"){
      return false;
    }
    this.users[nick].remove(nick);
    delete this.users[nick];
    return true;
  };

  UserList.prototype.append = function(nick, avatar){
    const container = document.createElement("div");
    container.className = "user-item";

    if(avatar){
      const a = document.createElement("span");
      a.style.backgroundImage = "url('"+avatar+"')";
      a.className = "user-list-avatar";
      container.appendChild(a);
    }

    const name = document.createElement("span");
    name.className = "nick";
    name.innerHTML = nick;
    container.appendChild(name);
    const self = this;
    name.onclick = function(){
      const my = self.users[myNick];
      var m = [];
      if(nick == myNick){
        m.push([
          function(){
            var newNick = prompt(language["writeNick"]);
            if(newNick){
              send("Bot", "/nick "+newNick);
            }
          },
          language["changeNick"]
        ]);
      }else if(my.isOp){
        m.push([
          function(){
            alert(typeof sys.currentPage());
            send(sys.currentPage().name, "/kick "+nick);
          },
          language["kick"]
        ]);
        m.push([
          function(){
            send(sys.currentPage().name, "/ban "+nick);
          },
          language["ban"]
        ]);
      }

      for(var i=0;i<m.length;i++){
         const item = document.createElement("div");
         item.onclick = m[i][0];
         item.innerHTML = m[i][1];
         menu.appendChild(item);
      }
      if(menu.offsetParent == null){
        menu.style.display = "block";
      }else{
        menu.style.display = "none";
        menu.innerHTML = "";
      }
    };

    const menu = document.createElement("div");
    menu.className = "menu";
    menu.style.display = "none";
    container.appendChild(menu);

    this.dom.appendChild(container);
    this.users[nick] = new User(
      this.sys,
      this.sys.appendUser(this.dom, avatar, nick),
      nick
    );
  };

  UserList.prototype.updateNick = function(old, news){
     if(typeof this.users[old] === "undefined"){
       return false;
     }

     this.users[old].updateNick(news);
     this.users[news] = this.users[old];
     delete this.users[old];
  };

  UserList.prototype.get = function(nick){
    if(typeof this.users[nick] === "undefined")
      return null;
    return this.users[nick];
  };

  return UserList;
})();
<|endoftext|>


<commit_before>var filterList = ['logo', 'red pencil', 'wikibooks', 'feature', 'star', 'symbol', 'vote', 'icon', 'question_book', 'disamb', 'edit']

var width = 1000;
var height = 500;

var rootCircleRadius = 30;
var rootCircleCenterXPos = 30;

var childCircleRadius = 20;

var verticalMargin = 30;

var horizontalOffset = 100;
var verticalBarXPos = rootCircleCenterXPos + rootCircleRadius + horizontalOffset;

var textOffset = 30;
var barWidth = 100;

// Distance between two children
var heightBetweenChildren = 100;

function capitalise(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function getName(data) {
    return data.vernacularName || data.canonicalName || data.scientificName || "Error: could not find name";
}

function getScientificName(data) {
    var name = data.scientificName;

    // Used when name has date and scientist attached
    if (typeof data.authorship !== "undefined") {
        if (data.authorship === "") {
            return name;
        }

        var index = name.indexOf(data.authorship);
        if (index !== -1) {
            // remove the space before the name too
            return name.substring(0, index - 1);
        }
    }

    return name;
}

function showInformation(data, tree) {
    adjustInfoContainerWidth();

    // Remove existing data, if it exists
    d3.select('#speciesData').remove();

    var infoSelection = d3.select('#infoContainer');
    var divSelection = infoSelection.append('div').attr('id', 'speciesData').attr('class', 'verticalLine');

    showWikipediaInformation(data, tree);

}

function putLoader(divSelection) {
    divSelection.append('div').attr('class', 'ui active inline loader').attr('id', 'loader');
}

function removeLoader(divSelection) {
    divSelection.select('#loader').remove();
}

function adjustInfoContainerWidth() {
    var speciesContainer = d3.select('#speciesContainer');
    var infoSelection = d3.select('#infoContainer');

    // Resize both to occupy half of the page
    speciesContainer.style('width', '400px');
    infoSelection.style('width', 'calc(100% - 500px)');
}

function setInformationPaneWidthToZero() {
    var speciesContainer = d3.select('#speciesContainer');
    var infoSelection = d3.select('#infoContainer');
    d3.select('#speciesData').remove();

    // Resize both to occupy half of the page
    speciesContainer.style('width', 'calc(100%)');
    infoSelection.style('width', '0px');
}

function removeWikiCruft(text) {
    var lowercaseText = text.toLowerCase();

    var index = lowercaseText.indexOf('see also');
    if (index !== -1) {
        return text.substring(0, index);
    }

    var index = lowercaseText.indexOf('references');
    if (index !== -1) {
        return text.substring(0, index);
    }

    var index = lowercaseText.indexOf('bibliography');
    if (index !== -1) {
        return text.substring(0, index);
    }

    return text;
}

function showWikipediaInformation(data, tree) {
    var divSelection = d3.select('#speciesData');
    putLoader(divSelection);

    var wiki = new Wikipedia();
    var speciesName = getScientificName(data);
    var commonName = data.vernacularName;
    wiki.article(commonName, speciesName, function (data) {
        removeLoader(divSelection);
        console.log(data);
        if (typeof data === "undefined") {
            divSelection.append('h1').text('No available information');
            return;
        }

        var title = data.title;
        var content = data.extract;
        var content = removeWikiCruft(content);

        var titleText = title + " (" + tree.getTaxon() + ')';
        divSelection.append('h1').attr('class', 'header').text(titleText);
        divSelection.append('div').attr('id', 'content').html(content);

        wiki.image(commonName, speciesName, function (imagesData) {
            var url = chooseImage(imagesData);
            if (typeof url !== "undefined") {
                divSelection.insert('img', '#content').attr('src', url).attr('alt', 'image').attr('class', 'ui huge image');
            }
        });
    });
}

function containsAny(title, stringList) {
    var titleLowerCase = title.toLowerCase();
    for (var i = 0; i < stringList.length; i++) {
        var s = stringList[i].toLowerCase();
        if (titleLowerCase.indexOf(s) !== -1) {
            return true;
        }
    }
    return false;
}

function chooseImage(imagesData) {
    for (var i = 0; i < imagesData.length; i++) {
        var image = imagesData[i];
        var title = image.title;
        var mime = image.imageinfo[0].mime;
        var url = image.imageinfo[0].url;
        var size = image.imageinfo[0].size;

        // For speacial wikipedia icons, video and audio
        if (containsAny(title, filterList) || containsAny(url, filterList) || mime.indexOf('application') !== -1) {
            continue;
        }

        if (size >= 5000000) {
            continue;
        }

        return url;
    }
}

function expandSuperTree(data, svgContainer, tree) {
    if (tree.isAtKingdomLevel()) {
        console.info("Reached kingdom level. Can't go up.");
        return;
    }

    setInformationPaneWidthToZero();

    tree.setRootToParent();
    tree.fetchBasicChildrenInformation(function (children) {
        addChildren(svgContainer, tree, children);
    });
}

function showChildren(data, svgContainer, tree) {
    if (tree.isSpeciesLevel()) {
        console.info("Reached species level. Can't go down.");
        return;
    }

    setInformationPaneWidthToZero();

    tree.setRootToChild(data.id);
    tree.fetchBasicChildrenInformation(function (children) {
        addChildren(svgContainer, tree, children);
    });
}

function clearSvg(svgContainer) {
    svgContainer.selectAll('g').remove();
    svgContainer.selectAll('circle').remove();
    svgContainer.selectAll('image').remove();
    svgContainer.selectAll('line').remove();
}

function resizeSvg(svgContainer, children) {
    resizeSvgHeight(svgContainer, children);
}

function resizeSvgHeight(svgContainer, children) {
    // Distance between two children
    var contentHeight = Math.max(2 * rootCircleRadius, (children.length - 1) * heightBetweenChildren);

    var marginHeight = 2 * verticalMargin;

    height = contentHeight + marginHeight;
    svgContainer.attr('height', height);
}

function addRootCircle(svgContainer, tree) {
    var height = svgContainer.attr('height');

    svgSelection.append('circle')
        .attr("cx", rootCircleCenterXPos)
        .attr("cy", verticalMargin + rootCircleRadius)
        .attr("r", rootCircleRadius)
        .style("fill", "green")
        .on("click", function (data) {
            expandSuperTree(data, svgContainer, tree);
        });
}

function addHorizontalLineFromCircle(svgContainer) {
    var height = svgContainer.attr('height');

    svgSelection.append('line')
        .attr('x1', rootCircleCenterXPos + rootCircleRadius)
        .attr('y1', verticalMargin + rootCircleRadius)
        .attr('x2', verticalBarXPos)
        .attr('y2', verticalMargin + rootCircleRadius)
        .attr('stroke-width', 5)
        .attr('stroke', 'black');
}

function addVerticalLine(svgContainer) {
    var height = svgContainer.attr('height');

    svgSelection.append('line')
        .attr('x1', verticalBarXPos)
        .attr('y1', verticalMargin)
        .attr('x2', verticalBarXPos)
        .attr('y2', height - verticalMargin)
        .attr('stroke-width', 5)
        .attr('stroke', 'black');
}

function addHorizontalBars(childrenSelection, numChildren) {
    for (var i = 0; i < numChildren; i++) {
        var height = i * heightBetweenChildren;
        var yPos = height + verticalMargin;

        childrenSelection.append('line')
            .attr('x1', verticalBarXPos)
            .attr('y1', yPos)
            .attr('x2', verticalBarXPos + barWidth)
            .attr('y2', yPos)
            .attr('stroke-width', 5)
            .attr('stroke', 'black');
    }
}

function addCircles(childrenSelection, childrenData, tree) {
    var circles = childrenSelection.selectAll('image')
        .data(childrenData)
        .enter()
        .append('image');

    var num = 0;
    var remainingSpace = height - 2 * verticalMargin;

    var circleAttributes = circles
        .attr('x', verticalBarXPos + barWidth - 10)
        .attr('y', function (data, index) {
            var height = index * heightBetweenChildren;
            var yPos = height + verticalMargin - 15;
            return yPos;
        })
        .attr('height', 30)
        .attr('width', 30)
        .attr('xlink:href', 'image/info.png')
        .on("click", function (data) {
            showInformation(data, tree);
        });
}

function addText(svgContainer, tree, childrenSelection, childrenData) {
    var text = childrenSelection.selectAll("text")
        .data(childrenData)
        .enter()
        .append("text");

    var textAttributes = text
        .attr('x', verticalBarXPos + barWidth + textOffset)
        .attr('y', function (data, index) {
            var height = index * heightBetweenChildren;
            var textAdjustment = 6;
            var yPos = height + verticalMargin + textAdjustment;
            return yPos;
        })
        .text(function (data) {
            var text = capitalise(getName(data));
            if (data.numDescendants !== 0 && data.numDescendants !== undefined) {
                var text = text + ' (' + data.numDescendants + ' descendants)'
            }
            return text;
        })
        .attr('font-family', 'sans-serif')
        .attr('font-size', '20px')
        .attr('fill', 'rgb(83, 83, 83)')
        .on('click', function (data) {
            showChildren(data, svgContainer, tree);
        });
}

function sortByNumberDescendants(childrenData) {
    return childrenData.sort(function (a, b) {
        var keyA = a.numDescendants || 0,
            keyB = b.numDescendants || 0;
        // Compare the 2 dates
        if (keyA > keyB) return -1;
        if (keyA < keyB) return 1;
        return 0;
    });
}

function addChildrenToSvg(svgContainer, tree, childrenData) {
    var childrenSelection = svgContainer.append('g').attr('id', 'childrenGroup');
    var numChildren = childrenData.length;
    childrenData = sortByNumberDescendants(childrenData);

    addHorizontalBars(childrenSelection, numChildren);
    addCircles(childrenSelection, childrenData, tree);
    addText(svgContainer, tree, childrenSelection, childrenData);
}

function addChildren(svgContainer, tree, children) {
    clearSvg(svgContainer)
    resizeSvg(svgContainer, children);
    addRootCircle(svgContainer, tree);
    addHorizontalLineFromCircle(svgContainer);
    addVerticalLine(svgContainer);
    addChildrenToSvg(svgContainer, tree, children);
}

var selection = d3.select("#speciesContainer");

var svgSelection = selection.append("svg")
    .attr('width', width)
    .attr('height', height);

var tree = new Tree();
tree.fetchBasicChildrenInformation(function (children) {
    addChildren(svgSelection, tree, children);
});
<commit_msg>Bugfix: when there was no image available, undefined was passed into the chooseImage function, resulting in error. Now, an empty array is passed.<commit_after>var filterList = ['logo', 'red pencil', 'wikibooks', 'feature', 'star', 'symbol', 'vote', 'icon', 'question_book', 'disamb', 'edit']

var width = 1000;
var height = 500;

var rootCircleRadius = 30;
var rootCircleCenterXPos = 30;

var childCircleRadius = 20;

var verticalMargin = 30;

var horizontalOffset = 100;
var verticalBarXPos = rootCircleCenterXPos + rootCircleRadius + horizontalOffset;

var textOffset = 30;
var barWidth = 100;

// Distance between two children
var heightBetweenChildren = 100;

function capitalise(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function getName(data) {
    return data.vernacularName || data.canonicalName || data.scientificName || "Error: could not find name";
}

function getScientificName(data) {
    var name = data.scientificName;

    // Used when name has date and scientist attached
    if (typeof data.authorship !== "undefined") {
        if (data.authorship === "") {
            return name;
        }

        var index = name.indexOf(data.authorship);
        if (index !== -1) {
            // remove the space before the name too
            return name.substring(0, index - 1);
        }
    }

    return name;
}

function showInformation(data, tree) {
    adjustInfoContainerWidth();

    // Remove existing data, if it exists
    d3.select('#speciesData').remove();

    var infoSelection = d3.select('#infoContainer');
    var divSelection = infoSelection.append('div').attr('id', 'speciesData').attr('class', 'verticalLine');

    showWikipediaInformation(data, tree);

}

function putLoader(divSelection) {
    divSelection.append('div').attr('class', 'ui active inline loader').attr('id', 'loader');
}

function removeLoader(divSelection) {
    divSelection.select('#loader').remove();
}

function adjustInfoContainerWidth() {
    var speciesContainer = d3.select('#speciesContainer');
    var infoSelection = d3.select('#infoContainer');

    // Resize both to occupy half of the page
    speciesContainer.style('width', '400px');
    infoSelection.style('width', 'calc(100% - 500px)');
}

function setInformationPaneWidthToZero() {
    var speciesContainer = d3.select('#speciesContainer');
    var infoSelection = d3.select('#infoContainer');
    d3.select('#speciesData').remove();

    // Resize both to occupy half of the page
    speciesContainer.style('width', 'calc(100%)');
    infoSelection.style('width', '0px');
}

function removeWikiCruft(text) {
    var lowercaseText = text.toLowerCase();

    var index = lowercaseText.indexOf('see also');
    if (index !== -1) {
        return text.substring(0, index);
    }

    var index = lowercaseText.indexOf('references');
    if (index !== -1) {
        return text.substring(0, index);
    }

    var index = lowercaseText.indexOf('bibliography');
    if (index !== -1) {
        return text.substring(0, index);
    }

    return text;
}

function showWikipediaInformation(data, tree) {
    var divSelection = d3.select('#speciesData');
    putLoader(divSelection);

    var wiki = new Wikipedia();
    var speciesName = getScientificName(data);
    var commonName = data.vernacularName;
    wiki.article(commonName, speciesName, function (data) {
        removeLoader(divSelection);
        console.log(data);
        if (typeof data === "undefined") {
            divSelection.append('h1').text('No available information');
            return;
        }

        var title = data.title;
        var content = data.extract;
        var content = removeWikiCruft(content);

        var titleText = title + " (" + tree.getTaxon() + ')';
        divSelection.append('h1').attr('class', 'header').text(titleText);
        divSelection.append('div').attr('id', 'content').html(content);

        wiki.image(commonName, speciesName, function (imagesData) {
            var url = chooseImage(imagesData || []);
            if (typeof url !== "undefined") {
                divSelection.insert('img', '#content').attr('src', url).attr('alt', 'image').attr('class', 'ui huge image');
            }
        });
    });
}

function containsAny(title, stringList) {
    var titleLowerCase = title.toLowerCase();
    for (var i = 0; i < stringList.length; i++) {
        var s = stringList[i].toLowerCase();
        if (titleLowerCase.indexOf(s) !== -1) {
            return true;
        }
    }
    return false;
}

function chooseImage(imagesData) {
    for (var i = 0; i < imagesData.length; i++) {
        var image = imagesData[i];
        var title = image.title;
        var mime = image.imageinfo[0].mime;
        var url = image.imageinfo[0].url;
        var size = image.imageinfo[0].size;

        // For speacial wikipedia icons, video and audio
        if (containsAny(title, filterList) || containsAny(url, filterList) || mime.indexOf('application') !== -1) {
            continue;
        }

        if (size >= 5000000) {
            continue;
        }

        return url;
    }
}

function expandSuperTree(data, svgContainer, tree) {
    if (tree.isAtKingdomLevel()) {
        console.info("Reached kingdom level. Can't go up.");
        return;
    }

    setInformationPaneWidthToZero();

    tree.setRootToParent();
    tree.fetchBasicChildrenInformation(function (children) {
        addChildren(svgContainer, tree, children);
    });
}

function showChildren(data, svgContainer, tree) {
    if (tree.isSpeciesLevel()) {
        console.info("Reached species level. Can't go down.");
        return;
    }

    setInformationPaneWidthToZero();

    tree.setRootToChild(data.id);
    tree.fetchBasicChildrenInformation(function (children) {
        addChildren(svgContainer, tree, children);
    });
}

function clearSvg(svgContainer) {
    svgContainer.selectAll('g').remove();
    svgContainer.selectAll('circle').remove();
    svgContainer.selectAll('image').remove();
    svgContainer.selectAll('line').remove();
}

function resizeSvg(svgContainer, children) {
    resizeSvgHeight(svgContainer, children);
}

function resizeSvgHeight(svgContainer, children) {
    // Distance between two children
    var contentHeight = Math.max(2 * rootCircleRadius, (children.length - 1) * heightBetweenChildren);

    var marginHeight = 2 * verticalMargin;

    height = contentHeight + marginHeight;
    svgContainer.attr('height', height);
}

function addRootCircle(svgContainer, tree) {
    var height = svgContainer.attr('height');

    svgSelection.append('circle')
        .attr("cx", rootCircleCenterXPos)
        .attr("cy", verticalMargin + rootCircleRadius)
        .attr("r", rootCircleRadius)
        .style("fill", "green")
        .on("click", function (data) {
            expandSuperTree(data, svgContainer, tree);
        });
}

function addHorizontalLineFromCircle(svgContainer) {
    var height = svgContainer.attr('height');

    svgSelection.append('line')
        .attr('x1', rootCircleCenterXPos + rootCircleRadius)
        .attr('y1', verticalMargin + rootCircleRadius)
        .attr('x2', verticalBarXPos)
        .attr('y2', verticalMargin + rootCircleRadius)
        .attr('stroke-width', 5)
        .attr('stroke', 'black');
}

function addVerticalLine(svgContainer) {
    var height = svgContainer.attr('height');

    svgSelection.append('line')
        .attr('x1', verticalBarXPos)
        .attr('y1', verticalMargin)
        .attr('x2', verticalBarXPos)
        .attr('y2', height - verticalMargin)
        .attr('stroke-width', 5)
        .attr('stroke', 'black');
}

function addHorizontalBars(childrenSelection, numChildren) {
    for (var i = 0; i < numChildren; i++) {
        var height = i * heightBetweenChildren;
        var yPos = height + verticalMargin;

        childrenSelection.append('line')
            .attr('x1', verticalBarXPos)
            .attr('y1', yPos)
            .attr('x2', verticalBarXPos + barWidth)
            .attr('y2', yPos)
            .attr('stroke-width', 5)
            .attr('stroke', 'black');
    }
}

function addCircles(childrenSelection, childrenData, tree) {
    var circles = childrenSelection.selectAll('image')
        .data(childrenData)
        .enter()
        .append('image');

    var num = 0;
    var remainingSpace = height - 2 * verticalMargin;

    var circleAttributes = circles
        .attr('x', verticalBarXPos + barWidth - 10)
        .attr('y', function (data, index) {
            var height = index * heightBetweenChildren;
            var yPos = height + verticalMargin - 15;
            return yPos;
        })
        .attr('height', 30)
        .attr('width', 30)
        .attr('xlink:href', 'image/info.png')
        .on("click", function (data) {
            showInformation(data, tree);
        });
}

function addText(svgContainer, tree, childrenSelection, childrenData) {
    var text = childrenSelection.selectAll("text")
        .data(childrenData)
        .enter()
        .append("text");

    var textAttributes = text
        .attr('x', verticalBarXPos + barWidth + textOffset)
        .attr('y', function (data, index) {
            var height = index * heightBetweenChildren;
            var textAdjustment = 6;
            var yPos = height + verticalMargin + textAdjustment;
            return yPos;
        })
        .text(function (data) {
            var text = capitalise(getName(data));
            if (data.numDescendants !== 0 && data.numDescendants !== undefined) {
                var text = text + ' (' + data.numDescendants + ' descendants)'
            }
            return text;
        })
        .attr('font-family', 'sans-serif')
        .attr('font-size', '20px')
        .attr('fill', 'rgb(83, 83, 83)')
        .on('click', function (data) {
            showChildren(data, svgContainer, tree);
        });
}

function sortByNumberDescendants(childrenData) {
    return childrenData.sort(function (a, b) {
        var keyA = a.numDescendants || 0,
            keyB = b.numDescendants || 0;
        // Compare the 2 dates
        if (keyA > keyB) return -1;
        if (keyA < keyB) return 1;
        return 0;
    });
}

function addChildrenToSvg(svgContainer, tree, childrenData) {
    var childrenSelection = svgContainer.append('g').attr('id', 'childrenGroup');
    var numChildren = childrenData.length;
    childrenData = sortByNumberDescendants(childrenData);

    addHorizontalBars(childrenSelection, numChildren);
    addCircles(childrenSelection, childrenData, tree);
    addText(svgContainer, tree, childrenSelection, childrenData);
}

function addChildren(svgContainer, tree, children) {
    clearSvg(svgContainer)
    resizeSvg(svgContainer, children);
    addRootCircle(svgContainer, tree);
    addHorizontalLineFromCircle(svgContainer);
    addVerticalLine(svgContainer);
    addChildrenToSvg(svgContainer, tree, children);
}

var selection = d3.select("#speciesContainer");

var svgSelection = selection.append("svg")
    .attr('width', width)
    .attr('height', height);

var tree = new Tree();
tree.fetchBasicChildrenInformation(function (children) {
    addChildren(svgSelection, tree, children);
});
<|endoftext|>


<commit_before>/* jshint maxdepth: 5, maxparams: 6 */

(function(W, U) {
	'use strict';

	var reg = {
			args: /(\\?['"][^'"]+\\?['"]|[^,]+)/g,
			ext: /(.[^\(]+)(?:\((.*)\))?/,
			pair: /{{#(\S+?)(?:\|(.+?))?}}([\s\S]+?){{\/\1}}/g,
			partial: /{{\s*>(.+?)}}/g,
			single: /{{(.+?)}}/g,
			str: /^\\?("|')/,
			tags: /{{\s*(?:([#\/])([^#{\|\n\s]+)\s*(\|[^{\n]+)?|else)\s*}}/g
		},
		helpers = {
			is: function(val) {
				return this.val === val;
			},
			not: function(val) {
				return this.val !== val;
			},
			isEmpty: function() {
				return this.empty;
			},
			notEmpty: function() {
				return ! this.empty;
			}
		},
		views = {},
		esc,

		/**
		 * Determine if value matches empty criteria
		 *
		 * @private
		 * @param {*} val
		 * @returns {boolean}
		 */
		_isEmpty = function(val) {
			return val === '' || val === false || val == null ||
				(typeof val == 'object' && ! Object.keys(val).length);
		},

		/**
		 * Make recursive partial replacements
		 *
		 * @private
		 * @param {string} temp
		 * @returns {string}
		 */
		_embed = function(temp) {
			temp = temp.replace(reg.partial, function(m, tag) {
				return views[tag.trim()] || '';
			});

			if (reg.partial.test(temp)) {
				temp = _embed(temp);
			}

			return temp;
		},

		/**
		 * Get specific object value
		 *
		 * @private
		 * @param {object} data
		 * @param {object} prev
		 * @param {string} key
		 * @param {string} fb
		 * @param {object} init
		 * @returns {*}
		 */
		_get = function(data, prev, key, fb, init) {
			key = key.trim();

			// Alter context
			if (key.substr(0, 6) == '$root.') {
				key = key.substr(6);
				data = init;
			} else if (key.substr(0, 3) == '../') {
				key = key.substr(3);
				data = prev;
			}

			var segs = key == '.' ? ['.'] : key.split('.'),
				orig = data,
				len = segs.length - 1,
				i = 0;

			// Loop through object segments
			for (; i <= len; i++) {
				key = segs[i];

				if (data && data.hasOwnProperty(key)) {
					data = data[key];

					// Return value on last segment
					if (i === len) {
						return data;
					}
				} else {
					break;
				}
			}

			if (key == '.') {
				return data;
			}

			// Process fallback value
			if (fb && fb !== '') {
				fb = fb.trim();
				var match = fb.match(reg.str);

				if (match) {
					return fb.replace(reg.str, '')
						.replace(new RegExp(match[0] + '$'), '');
				}

				return _get(orig, prev, fb, '', init);
			}

			return fb;
		},

		/**
		 * Parse helper arguments
		 *
		 * @private
		 * @param {string} str
		 * @param {object} data
		 * @param {object} prev
		 * @param {object} init
		 * @returns {*}
		 */
		_parseArgs = function(str, data, prev, init) {
			var args = str !== U ? str.match(reg.args) || [] : [];

			return args.map(function(arg) {
				arg = arg.trim();
				var match = arg.match(reg.str);

				if (match) {
					return arg.replace(reg.str, '')
						.replace(new RegExp(match[0] + '$'), '');
				}

				return arg == 'true' ? true :
					arg == 'false' ? false :
					arg == 'null' ? null :
					parseInt(arg).toString() == arg ? parseInt(arg) :
					_get(data, prev, arg, '', init);
			});
		},

		/**
		 * Parse template string
		 *
		 * @private
		 * @param {string} temp
		 * @param {object} data
		 * @param {object} prev
		 * @param {object} init
		 * @param {int} index
		 * @returns {string}
		 */
		_parse = function(temp, data, prev, init, index) {
			return temp.replace(reg.pair, function(m, t, helper, inner) {
				// Return escaped template tag pairs
				if (t == '!') {
					esc = true;
					return inner.replace(/{{/g, '{~');
				}

				var tag = t.replace(/%\d+/, ''),
					cond = inner.split('{{:' + t + '}}');
				inner = cond[0];

				var val = _get(data, prev, tag, U, init),
					empty = _isEmpty(val),
					help = [],
					each;

				// Parse helpers
				if (helper || empty) {
					var meth = helper ? helper.split('|') : [],
						sec = cond.length > 1 ? cond[1] : '',
						agg = [];

					// Check for root helpers
					if (empty) {
						var arg = meth[0] && meth[0][0] == '(';
						meth.unshift(tag + (arg ? meth[0] : '()'));

						if (arg) {
							meth.splice(1, 1);
						}
					}

					// Capture available aggregates and helpers
					meth.forEach(function(el) {
						var arr = el.match(reg.ext),
							name = arr[1].trim();

						// Check for each helper
						if (name == 'each') {
							each = true;
						} else if (helpers[name]) {
							el = [helpers[name], arr[2]];
							each ? help.push(el) : agg.push(el);
						}
					});

					// Process aggregates
					if (agg.length) {
						if (! agg.every(function(f) {
								var rv = f[0].apply({
									val: val,
									data: data,
									root: init,
									tag: tag,
									empty: empty,
									index: index
								}, _parseArgs(f[1], data, prev, init));

								if (rv === false) {
									return rv;
								}

								if (rv !== true) {
									val = rv;
									empty = _isEmpty(val);
								}

								return true;
							})) {
							return _parse(sec, data, prev, init, index);
						}
					} else if (empty) {
						return _parse(sec, data, prev, init, index);
					}
				}

				var isObject = typeof val == 'object';

				if (! each) {
					if (! isObject) {
						val = W.$extend({}, data, {
							'.': val,
							'#': 0,
							'##': 1
						});
					}

					return _parse(inner, val, data, init, index);
				}

				if (! empty) {
					// Loop through objects and arrays
					if (isObject) {
						var isPlainObject = W.$isObject(val),
							resp = '',
							i = 0;

						for (var key in val) {
							if (val.hasOwnProperty(key)) {
								// Merge default properties
								var el = val[key];
								empty = _isEmpty(el);

								// Process helpers
								if (! help.length ||
									help.every(function(f) {
										var rv = f[0].apply({
											val: el,
											data: data,
											root: init,
											tag: tag,
											empty: empty,
											index: i
										}, _parseArgs(f[1], val));

										if (rv === false) {
											return rv;
										}

										if (rv !== true) {
											el = rv;
										}

										return true;
									})
								) {
									var item = W.$extend({}, W.$isObject(el) ?
											el :
											(isPlainObject ? val : {}),
										{
											$key: key,
											'.': el,
											'#': i,
											'##': i + 1
										});
									i++;

									resp += _parse(inner, item, data, init, i);
								}
							}
						}

						return resp;
					}

					return inner;
				}
			}).replace(reg.single, function(m, set) {
				var split = set.split('||'),
					fb = split[1],
					segs = split[0].split('|'),
					tag = segs[0].trim(),
					val = _get(data, prev, tag, fb, init),
					helps = segs.length > 1 ? segs.slice(1) : segs;

				// Process helpers
				helps.forEach(function(el, i) {
					var arr = el.match(reg.ext);
					helps[i] = el.trim();

					if (arr) {
						var helper = helpers[arr[1].trim()];

						if (helper && (segs.length > 1 ||
							! data.hasOwnProperty(tag))) {
							val = helper.apply({
								val: val,
								data: data,
								root: init,
								tag: tag,
								index: index,
								fallback: fb
							}, _parseArgs(arr[2], data));
						}
					}
				});

				// Encode output by default
				if (val === U || typeof val == 'object') {
					val = '';
				} else if (typeof val == 'string') {
					// Recursively process injected tags
					if (val.indexOf('{{') > -1) {
						val = _render(val, data);
					}

					// Encode HTML characters
					if (helps.indexOf('raw') < 0) {
						val = val.replace(/&/g, '&')
							.replace(/&/g, '&')
							.replace(/</g, '<')
							.replace(/>/g, '>')
							.replace(/"/g, '"');
					}
				}

				return val;
			});
		},

		/**
		 * Render template string
		 *
		 * @private
		 * @param {string} temp
		 * @param {object} data
		 * @returns {string}
		 */
		_render = function(temp, data) {
			var tags = [],
				depth = [];

			// Make partial replacements
			temp = _embed(temp);

			// Match tag pairs
			temp = temp.replace(reg.tags, function(m, pre, tag, helper) {
				var resp = '{{';

				if (tag == '!') {
					esc = pre == '#';
					resp += pre + tag;
				} else if (esc) {
					return m;
				} else if (pre) {
					var segs = tag.split('('),
						root = segs[0],
						exists = tags.hasOwnProperty(tag);
					resp += pre + root + '%';

					if (pre == '#') {
						depth.push(root);

						if (exists) {
							tags[root].i++;
							tags[root].o.push(tags[root].i);
						} else {
							tags[root] = {
								i: 1,
								o: [1]
							};
						}

						if (segs.length > 1) {
							helper = '(' + segs.slice(1).join('(');
						}

						resp += tags[root].i + (helper || '');
					} else if (exists) {
						resp += tags[root].o.pop();
						tags[root].i--;
						depth.pop();
					}
				} else if (depth.length) {
					tag = depth.slice(-1)[0];
					resp += ':' + tag + '%' + tags[tag].i;
				}

				return resp + '}}';
			});

			// Parse template tags
			return _parse(temp, data, {}, data, 0);
		};

	W.app = {
		/**
		 * Application instance storage
		 */
		fn: {},

		/**
		 * Create an application
		 *
		 * @param {string} name
		 * @param {object} options
		 * @param {object} options.model
		 * @param {($|HTMLElement|string)} [options.target]
		 * @param {($|HTMLElement|string)} options.view
		 *
		 */
		make: function(name, options) {
			var sel = options.view,
				targ = options.target,
				model = options.model || {},
				views = W.$(targ || sel).map(function(el) {
					return [el, targ ? sel : el.outerHTML];
				}),
				fn = function(data) {
					views.forEach(function(view) {
						W.$setRef(
							W.view.diff(view[0], W.$parseHTML(
								W.view.render(view[1], data)
							), targ)
						);
					});
				},
				app = W.app;

			fn(model);

			// Create a new application controller
			app.fn[name] = W._make(name, {}, {}, false, model);
			app[name] = new app.fn[name]();

			W.$extend(app[name], {
				/**
				 * Destroy current application
				 */
				$destroy: function() {
					if (options._destruct) {
						options._destruct();
					}

					delete app[name];
				},

				/**
				 * Pause view updating
				 */
				$pause: function() {
					app[name].$unobserve('*', fn);
				},

				/**
				 * Resume view updating
				 *
				 * @param {boolean} [update=false]
				 */
				$resume: function(update) {
					app[name].$observe('*', fn);

					if (update) {
						fn(app[name].$get());
					}
				}
			});

			// Initialize app observation
			app[name].$resume();

			return app[name];
		}
	};

	W.view = {
		/**
		 * Parse data into template string
		 *
		 * @param {string} template
		 * @param {object} [data]
		 * @returns {string}
		 */
		render: function(template, data) {
			esc = false;
			template = _render(views[template] || template, W.$extend(data));

			return esc ?
				template.replace(/{~/g, '{{') :
				template;
		},

		/**
		 * Add conditional template handler or tag data modifier
		 *
		 * @param {object|string} name
		 * @param {function} [fn]
		 */
		addHelper: function(name, fn) {
			W._extend(helpers, name, fn);
		},

		/**
		 * Add views to store for on-demand reference
		 *
		 * @param {object|string} name
		 * @param {string} [value]
		 */
		addView: function(name, value) {
			W._extend(views, name, value);
		}
	};
})(Wee, undefined);<commit_msg>Update the app view after the controller is made<commit_after>/* jshint maxdepth: 5, maxparams: 6 */

(function(W, U) {
	'use strict';

	var reg = {
			args: /(\\?['"][^'"]+\\?['"]|[^,]+)/g,
			ext: /(.[^\(]+)(?:\((.*)\))?/,
			pair: /{{#(\S+?)(?:\|(.+?))?}}([\s\S]+?){{\/\1}}/g,
			partial: /{{\s*>(.+?)}}/g,
			single: /{{(.+?)}}/g,
			str: /^\\?("|')/,
			tags: /{{\s*(?:([#\/])([^#{\|\n\s]+)\s*(\|[^{\n]+)?|else)\s*}}/g
		},
		helpers = {
			is: function(val) {
				return this.val === val;
			},
			not: function(val) {
				return this.val !== val;
			},
			isEmpty: function() {
				return this.empty;
			},
			notEmpty: function() {
				return ! this.empty;
			}
		},
		views = {},
		esc,

		/**
		 * Determine if value matches empty criteria
		 *
		 * @private
		 * @param {*} val
		 * @returns {boolean}
		 */
		_isEmpty = function(val) {
			return val === '' || val === false || val == null ||
				(typeof val == 'object' && ! Object.keys(val).length);
		},

		/**
		 * Make recursive partial replacements
		 *
		 * @private
		 * @param {string} temp
		 * @returns {string}
		 */
		_embed = function(temp) {
			temp = temp.replace(reg.partial, function(m, tag) {
				return views[tag.trim()] || '';
			});

			if (reg.partial.test(temp)) {
				temp = _embed(temp);
			}

			return temp;
		},

		/**
		 * Get specific object value
		 *
		 * @private
		 * @param {object} data
		 * @param {object} prev
		 * @param {string} key
		 * @param {string} fb
		 * @param {object} init
		 * @returns {*}
		 */
		_get = function(data, prev, key, fb, init) {
			key = key.trim();

			// Alter context
			if (key.substr(0, 6) == '$root.') {
				key = key.substr(6);
				data = init;
			} else if (key.substr(0, 3) == '../') {
				key = key.substr(3);
				data = prev;
			}

			var segs = key == '.' ? ['.'] : key.split('.'),
				orig = data,
				len = segs.length - 1,
				i = 0;

			// Loop through object segments
			for (; i <= len; i++) {
				key = segs[i];

				if (data && data.hasOwnProperty(key)) {
					data = data[key];

					// Return value on last segment
					if (i === len) {
						return data;
					}
				} else {
					break;
				}
			}

			if (key == '.') {
				return data;
			}

			// Process fallback value
			if (fb && fb !== '') {
				fb = fb.trim();
				var match = fb.match(reg.str);

				if (match) {
					return fb.replace(reg.str, '')
						.replace(new RegExp(match[0] + '$'), '');
				}

				return _get(orig, prev, fb, '', init);
			}

			return fb;
		},

		/**
		 * Parse helper arguments
		 *
		 * @private
		 * @param {string} str
		 * @param {object} data
		 * @param {object} prev
		 * @param {object} init
		 * @returns {*}
		 */
		_parseArgs = function(str, data, prev, init) {
			var args = str !== U ? str.match(reg.args) || [] : [];

			return args.map(function(arg) {
				arg = arg.trim();
				var match = arg.match(reg.str);

				if (match) {
					return arg.replace(reg.str, '')
						.replace(new RegExp(match[0] + '$'), '');
				}

				return arg == 'true' ? true :
					arg == 'false' ? false :
					arg == 'null' ? null :
					parseInt(arg).toString() == arg ? parseInt(arg) :
					_get(data, prev, arg, '', init);
			});
		},

		/**
		 * Parse template string
		 *
		 * @private
		 * @param {string} temp
		 * @param {object} data
		 * @param {object} prev
		 * @param {object} init
		 * @param {int} index
		 * @returns {string}
		 */
		_parse = function(temp, data, prev, init, index) {
			return temp.replace(reg.pair, function(m, t, helper, inner) {
				// Return escaped template tag pairs
				if (t == '!') {
					esc = true;
					return inner.replace(/{{/g, '{~');
				}

				var tag = t.replace(/%\d+/, ''),
					cond = inner.split('{{:' + t + '}}');
				inner = cond[0];

				var val = _get(data, prev, tag, U, init),
					empty = _isEmpty(val),
					help = [],
					each;

				// Parse helpers
				if (helper || empty) {
					var meth = helper ? helper.split('|') : [],
						sec = cond.length > 1 ? cond[1] : '',
						agg = [];

					// Check for root helpers
					if (empty) {
						var arg = meth[0] && meth[0][0] == '(';
						meth.unshift(tag + (arg ? meth[0] : '()'));

						if (arg) {
							meth.splice(1, 1);
						}
					}

					// Capture available aggregates and helpers
					meth.forEach(function(el) {
						var arr = el.match(reg.ext),
							name = arr[1].trim();

						// Check for each helper
						if (name == 'each') {
							each = true;
						} else if (helpers[name]) {
							el = [helpers[name], arr[2]];
							each ? help.push(el) : agg.push(el);
						}
					});

					// Process aggregates
					if (agg.length) {
						if (! agg.every(function(f) {
								var rv = f[0].apply({
									val: val,
									data: data,
									root: init,
									tag: tag,
									empty: empty,
									index: index
								}, _parseArgs(f[1], data, prev, init));

								if (rv === false) {
									return rv;
								}

								if (rv !== true) {
									val = rv;
									empty = _isEmpty(val);
								}

								return true;
							})) {
							return _parse(sec, data, prev, init, index);
						}
					} else if (empty) {
						return _parse(sec, data, prev, init, index);
					}
				}

				var isObject = typeof val == 'object';

				if (! each) {
					if (! isObject) {
						val = W.$extend({}, data, {
							'.': val,
							'#': 0,
							'##': 1
						});
					}

					return _parse(inner, val, data, init, index);
				}

				if (! empty) {
					// Loop through objects and arrays
					if (isObject) {
						var isPlainObject = W.$isObject(val),
							resp = '',
							i = 0;

						for (var key in val) {
							if (val.hasOwnProperty(key)) {
								// Merge default properties
								var el = val[key];
								empty = _isEmpty(el);

								// Process helpers
								if (! help.length ||
									help.every(function(f) {
										var rv = f[0].apply({
											val: el,
											data: data,
											root: init,
											tag: tag,
											empty: empty,
											index: i
										}, _parseArgs(f[1], val));

										if (rv === false) {
											return rv;
										}

										if (rv !== true) {
											el = rv;
										}

										return true;
									})
								) {
									var item = W.$extend({}, W.$isObject(el) ?
											el :
											(isPlainObject ? val : {}),
										{
											$key: key,
											'.': el,
											'#': i,
											'##': i + 1
										});
									i++;

									resp += _parse(inner, item, data, init, i);
								}
							}
						}

						return resp;
					}

					return inner;
				}
			}).replace(reg.single, function(m, set) {
				var split = set.split('||'),
					fb = split[1],
					segs = split[0].split('|'),
					tag = segs[0].trim(),
					val = _get(data, prev, tag, fb, init),
					helps = segs.length > 1 ? segs.slice(1) : segs;

				// Process helpers
				helps.forEach(function(el, i) {
					var arr = el.match(reg.ext);
					helps[i] = el.trim();

					if (arr) {
						var helper = helpers[arr[1].trim()];

						if (helper && (segs.length > 1 ||
							! data.hasOwnProperty(tag))) {
							val = helper.apply({
								val: val,
								data: data,
								root: init,
								tag: tag,
								index: index,
								fallback: fb
							}, _parseArgs(arr[2], data));
						}
					}
				});

				// Encode output by default
				if (val === U || typeof val == 'object') {
					val = '';
				} else if (typeof val == 'string') {
					// Recursively process injected tags
					if (val.indexOf('{{') > -1) {
						val = _render(val, data);
					}

					// Encode HTML characters
					if (helps.indexOf('raw') < 0) {
						val = val.replace(/&/g, '&')
							.replace(/&/g, '&')
							.replace(/</g, '<')
							.replace(/>/g, '>')
							.replace(/"/g, '"');
					}
				}

				return val;
			});
		},

		/**
		 * Render template string
		 *
		 * @private
		 * @param {string} temp
		 * @param {object} data
		 * @returns {string}
		 */
		_render = function(temp, data) {
			var tags = [],
				depth = [];

			// Make partial replacements
			temp = _embed(temp);

			// Match tag pairs
			temp = temp.replace(reg.tags, function(m, pre, tag, helper) {
				var resp = '{{';

				if (tag == '!') {
					esc = pre == '#';
					resp += pre + tag;
				} else if (esc) {
					return m;
				} else if (pre) {
					var segs = tag.split('('),
						root = segs[0],
						exists = tags.hasOwnProperty(tag);
					resp += pre + root + '%';

					if (pre == '#') {
						depth.push(root);

						if (exists) {
							tags[root].i++;
							tags[root].o.push(tags[root].i);
						} else {
							tags[root] = {
								i: 1,
								o: [1]
							};
						}

						if (segs.length > 1) {
							helper = '(' + segs.slice(1).join('(');
						}

						resp += tags[root].i + (helper || '');
					} else if (exists) {
						resp += tags[root].o.pop();
						tags[root].i--;
						depth.pop();
					}
				} else if (depth.length) {
					tag = depth.slice(-1)[0];
					resp += ':' + tag + '%' + tags[tag].i;
				}

				return resp + '}}';
			});

			// Parse template tags
			return _parse(temp, data, {}, data, 0);
		};

	W.app = {
		/**
		 * Application instance storage
		 */
		fn: {},

		/**
		 * Create an application
		 *
		 * @param {string} name
		 * @param {object} options
		 * @param {object} options.model
		 * @param {($|HTMLElement|string)} [options.target]
		 * @param {($|HTMLElement|string)} options.view
		 *
		 */
		make: function(name, options) {
			var sel = options.view,
				targ = options.target,
				model = options.model || {},
				views = W.$(targ || sel).map(function(el) {
					return [el, targ ? sel : el.outerHTML];
				}),
				fn = function(data) {
					views.forEach(function(view) {
						W.$setRef(
							W.view.diff(view[0], W.$parseHTML(
								W.view.render(view[1], data)
							), targ)
						);
					});
				},
				app = W.app;

			// Create a new application controller
			app.fn[name] = W._make(name, {}, {}, false, model);
			app[name] = new app.fn[name]();

			fn(model);

			W.$extend(app[name], {
				/**
				 * Destroy current application
				 */
				$destroy: function() {
					if (options._destruct) {
						options._destruct();
					}

					delete app[name];
				},

				/**
				 * Pause view updating
				 */
				$pause: function() {
					app[name].$unobserve('*', fn);
				},

				/**
				 * Resume view updating
				 *
				 * @param {boolean} [update=false]
				 */
				$resume: function(update) {
					app[name].$observe('*', fn);

					if (update) {
						fn(app[name].$get());
					}
				}
			});

			// Initialize app observation
			app[name].$resume();

			return app[name];
		}
	};

	W.view = {
		/**
		 * Parse data into template string
		 *
		 * @param {string} template
		 * @param {object} [data]
		 * @returns {string}
		 */
		render: function(template, data) {
			esc = false;
			template = _render(views[template] || template, W.$extend(data));

			return esc ?
				template.replace(/{~/g, '{{') :
				template;
		},

		/**
		 * Add conditional template handler or tag data modifier
		 *
		 * @param {object|string} name
		 * @param {function} [fn]
		 */
		addHelper: function(name, fn) {
			W._extend(helpers, name, fn);
		},

		/**
		 * Add views to store for on-demand reference
		 *
		 * @param {object|string} name
		 * @param {string} [value]
		 */
		addView: function(name, value) {
			W._extend(views, name, value);
		}
	};
})(Wee, undefined);<|endoftext|>


<commit_before>$(function() {
    $('p img').click(function () {
        let imageStr = document.querySelector("#YunisTestImage").getAttribute("class");
        console.log(`${imageStr}`);
        if (`${imageStr}` == "SYYImageDiss") {
            showBigImage()
        }else {
            removeBigPic ()
        }

        $(document).bind('mousewheel', () => {return false;});

    });
    function  showBigImage() {
        $("#YunisTestImage").removeClass('SYYImageDiss');
        $("#YunisTestImage").addClass('SYYImageShow');
        $("#SSYLargeImage").attr({ "src": $(this).attr("src") });
        $("html,body").addClass("none-scroll");//下层不可滑动
        $("#SSYLargeImage").css("display", "block");
    }

    function removeBigPic () {
        $("#YunisTestImage").removeClass('SYYImageShow');
        $("#YunisTestImage").addClass('SYYImageDiss');
        $("#SSYLargeImage").attr({ "src": "" });

        setTimeout(() => {
            $("#SSYLargeImage").css("display", "none");
        }, 600);
        恢复响应鼠标滚动事件
        // $(document).unbind('mousewheel');
        $("html,body").removeClass("none-scroll");
    }

    $('#YunisTestImage').click(function () {
        removeBigPic();
    });
    $(document).keydown(function(event){
        //判断当event.keyCode 为37时（即左方面键），执行函数to_left();
        //判断当event.keyCode 为39时（即右方面键），执行函数to_right();
        if(event.keyCode == 27){
        //do somethings;
            removeBigPic();
        }
    });

});<commit_msg>jekyll编译失败<commit_after>$(function() {
    $('p img').click(function () {
        let imageStr = document.querySelector("#YunisTestImage").getAttribute("class");
        console.log(`${imageStr}`);
        if (`${imageStr}` == "SYYImageDiss") {
            showBigImage()
        }else {
            removeBigPic ()
        }

        $(document).bind('mousewheel', () => {return false;});

    });
    function  showBigImage() {
        $("#YunisTestImage").removeClass('SYYImageDiss');
        $("#YunisTestImage").addClass('SYYImageShow');
        $("#SSYLargeImage").attr({ "src": $(this).attr("src") });
        $("#SSYLargeImage").css("display", "block");
        $("html,body").addClass("none-scroll");//下层不可滑动
    }

    function removeBigPic () {
        $("#YunisTestImage").removeClass('SYYImageShow');
        $("#YunisTestImage").addClass('SYYImageDiss');

        setTimeout(() => {
            $("#SSYLargeImage").attr({ "src": "" });
            $("#SSYLargeImage").css("display", "none");
        }, 600);
        //恢复响应鼠标滚动事件
        // $(document).unbind('mousewheel');
        $("html,body").removeClass("none-scroll");
    }

    $('#YunisTestImage').click(function () {
        removeBigPic();
    });
    $(document).keydown(function(event){
        //判断当event.keyCode 为37时（即左方面键），执行函数to_left();
        //判断当event.keyCode 为39时（即右方面键），执行函数to_right();
        if(event.keyCode == 27){
        //do somethings;
            removeBigPic();
        }
    });

});<|endoftext|>


<commit_before>
window.addEventListener("deviceorientation", on_device_orientation);

function on_device_orientation(e)
{
	document.getElementById("id_z").innerHTML = e.alpha;
	document.getElementById("id_x").innerHTML = e.beta;
	document.getElementById("id_y").innerHTML = e.gamma;
}<commit_msg>am adaugat sir<commit_after>
window.addEventListener("deviceorientation", on_device_orientation);

function on_device_orientation(e)
{
	document.getElementById("id_z").innerHTML = "z=" + e.alpha;
	document.getElementById("id_x").innerHTML = "x=" + e.beta;
	document.getElementById("id_y").innerHTML = "y=" + e.gamma;
}<|endoftext|>