<commit_before>(function (undefined) {
	var isMSIE = /*@cc_on!@*/false;

	function BBSDat (thread) {
		this.thread = thread;
		this.ajax = new Ajax();
		this.init();
	}

	(function (p) {
		p.init = function () {
			this.data = "";
			this.lastmodified = "Thu, 01 Jun 1970 00:00:00 GMT";
		};
		p.renderHTML = function (options) {
			var html = [];
			var lines = this.data.getResLines();
			var rescnt;

			if(options.end == null)
			{
				options.end = lines.length;
			}

			rescnt = lines.length;

			if((options.first == true) && (options.start > 1))
			{
				html.push(lines[0].createResLine(1));
			}

			for(var i = (options.start - 1) ; ((i < options.end) && (i < rescnt)) ; i++)
			{
				if(lines[i] == "")
				{
					break;
				}

				html.push(lines[i].createResLine(i+1));
			}

			return html.join("\n");
		};

		p.requestDat = function (callback) {
			var url = this.thread.createDatURL();
			var self = this;
			var headers = {};

			headers["Content-Type"] = "text/plain; charset=x-sjis";
			headers["If-Modified-Since"] = this.lastmodified;

			this.ajax.get(url, {
				callback: function (data, status) {
					if(status === 404 || status === 302)
					{
						callback.call(self.thread, false, "YXbh͍폜ꂽA݂܂B");
					}
					else if(status !== 200 && status !== 304)
					{
						callback.call(self.thread, false, "ʐMG[܂B");
					}
					else if(status === 200)
					{
						self.data = data;
						var lastmodified;

						if(!(lastmodified = self.ajax.getResponseHeader("Last-Modified")))
						{
							callback.call(self.thread, false, "dat̍ŏIXV擾ł܂łB");
						}
						else
						{
							self.lastmodified = lastmodified;
							callback.call(self.thread, true, "");
						}
					}
					else
					{
						callback.call(self.thread, true, "");
					}
				},
				headers: headers
			});
		};
	})(BBSDat.prototype);

	function Rooter () {

	};

	Rooter.dispatch = function (thread, paths) {
		var	bbs = paths[1],
			key = paths[2],
			options = paths[3] || "";

		if(thread.bbs != bbs || thread.key != key) thread.datdata.init();

		thread.bbs = bbs;
		thread.key = key;

		thread.loadThread(function () {
			this.terminateLoadingView();
			this.parseOptions(decodeURIComponent(options));
			this.render();
		}, function () {
			if(this.requestcomp == false)
			{
				window.alert("ʐMł...");
				return false;
			}
			return true;
		});
	};

	Rooter.readPath = function (src) {
		if(/^\/(:bbs)\/index.html$/.test(src)) return src;
		else if(/^#!ID\/(\d+)(-\d+)?$/.test(src)) return src.substr(2);
		else if(/^#!\/.*$/.test(src)) return src.substr(2);
		return src;
	};

	(function (p) {

	})(Rooter.prototype);

	function BBSThread (paths) {
		this.requestcomp = true;
		this.shiftkey = false;

		var match = window.location.pathname.match(/^.*(\/test\/read.html)/g);

		this.urlbase = match[0].replace("test/read.html", "");

		var self = this;

		var onKeyDown = function (e) {
			var key = self.keyCode(e);

			if(key === 16) self.shiftkey = true;
			if(key === 13 && self.shiftkey)
			{
				e.preventDefault();
				self.postRes();
			}
		};

		if(window.opera)
		{
			$("#message").on("keypress", function (e) {
				return onKeyDown(e);
			});
		}
		else
		{
			$("#message").on("keydown", function (e) {
				return onKeyDown(e);
			});
		}

		$("#message").on("keyup", function (e) {
			var key = self.keyCode(e);
			if(key === 16) self.shiftkey = false;
		});

		$("#resparams").submit(function (e) {
			e.preventDefault();
			self.postRes();
			return false;
		});

		$("#name").val(Cookie.get("FROM"));
		$("#e-mail").val(Cookie.get("mail"));

		this.datdata = new BBSDat(this);
		this.ajax = new Ajax();

		this.startLoadingView();
		Rooter.dispatch(this, paths.split("/"));

		$("a").click(function (e) {
			var m,
				path = Rooter.readPath($(this).attr("href"));

			if(path === "/:reload")
			{
				e.preventDefault();
				self.reload();
			}
			else if((m = path.match(/^ID\/(\d+)(-\d+)?$/)))
			{
				e.preventDefault();
				if(!m[2]) window.location.hash = "a" + m[1];
			}
			else if((m = path.match(/^\/(:bbs)\/index.html$/)))
			{
				e.preventDefault();
				window.location.href = self.urlbase + self.bbs + "/index.html";
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/(:pastfrom)-(:pastto)?$/)))
			{
				e.preventDefault();
				if(!self.options) return;
				var bbs = self.bbs,
					key = self.key,
					options = self.pastfrom + "-" + self.pastto;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/(:nextfrom)-(:nextto)?$/)))
			{
				e.preventDefault();
				if(!self.options) return;
				var bbs = self.bbs,
					key = self.key,
					options = self.nextfrom + "-" + self.nextto;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/([^\/]+)?$/)))
			{
				e.preventDefault();
				var bbs = self.bbs,
					key = self.key,
					options = m[3] || "";
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/([^\/]+)\/([^\/]+)\/([^\/]+)?$/)))
			{
				var bbs = m[1],
					key = m[2],
					options = m[3] || "" ;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
		});
	}

	(function (p) {
		p.keyCode = function (e) {
			if(document.all) return e.originalEvent.keyCode;
			else if(document.getElementById) return (e.originalEvent.keyCode) ? e.originalEvent.keyCode : e.originalEvent.charCode;
			else if(document.layers) return e.originalEvent.which;
			else return 0;
		};
		p.createDatURL = function () {
			return (this.urlbase + this.bbs + "/dat/" + this.key + ".dat?" + (new Date()).getTime());
		};
		p.createPostURL = function () {
			return (this.urlbase + "test/bbs.cgi?guid=On");
		};
		p.loadThread = function (callback, beforeLoad) {
			if(beforeLoad && !beforeLoad.call(this)) return;

			this.requestcomp = false;

			this.datdata.requestDat(function (result, message) {
				this.requestcomp = true;
				if(!result) {
					alert(message);
				}
				else
				{
					callback.call(this);
				}
			});
		};
		p.postRes = function () {
			var self = this;
			var params = $("#resparams");

			this.startSendingView();

			this.ajax.post(this.createPostURL(), {
				callback: function (data, status) {
					self.terminateSendingView();

					var params = $("#resparams");
					if( (status == 200) && (//.test(data)) )
					{
						msgwindow = window.open();
						msgwindow.document.write(data);
					}
					params.find("#message").val("");

					self.options.end = null;
					self.loadThread(function () {
						this.render();
					});
				},
				params: {
					bbs: self.bbs,
					key: self.key,
					FROM: params.find("input[name='FROM']").val(),
					mail: params.find("input[name='mail']").val(),
					MESSAGE: params.find("#message").val(),
					submit: "",
					utn: "utn",
					time: params.find("input[name='time']").val(),
					suka: params.find("input[name='suka']").val()
				},
				headers: {
					"Referer": this.urlbase + "/" + this.bbs + "/",
					"Content-Type": "application/x-www-form-urlencoded"
				},
				encoder: EscapeSJIS
			});
		};
		p.reload = function () {
			this.startLoadingView();
			this.loadThread(function () {
				this.terminateLoadingView();
				this.render();
			});
		};
		p.startLoadingView = function () {
			var count = 3;

			this.timerid = window.setInterval(function () {
				count++;
				var str = "ǂݍݒ";
				for(var i=0; i < count; i++)
				{
					str += ".";
				}

				if(count > 20)
				{
					count = 0;
				}

				$("#resbodys").html("" + str + "");
			}, 100);
		};
		p.terminateLoadingView = function () {
			window.clearInterval(this.timerid);
		};
		p.startSendingView = function () {
			var count = 3;

			this.timerid = window.setInterval( function () {
				count++;
				var str = "ݒ";
				for(var i=0; i < count; i++)
				{
					str += ".";
				}

				if(count > 20)
				{
					count = 0;
				}

				$("#resbodys").html("" + str + "");
			}, 100);
		};
		p.terminateSendingView = function () {
			window.clearInterval(this.timerid);
		};
		p.render = function() {
			$("#resbodys").html(this.datdata.renderHTML(this.options));
			var lines = this.datdata.data.getResLines();
			var subject = lines[0].split("<>")[4];

			if(subject == undefined)
			{
				subject = 'X^Cs';
			}

			$("title").html(subject);
			$("#subject").html(subject);
			var date = new Date();
			var speed = (lines.length - 1) / (Math.floor(date.getTime() / 60000) - Math.floor(this.key / 60)) * 60 * 24;
			$("#speed").html("Speed:" + speed + "");
			$("#size").html(this.datdata.data.length - 1);
		};
		p.parseOptions = function(options) {
			var reslines = this.datdata.data.getResLines();

			this.options = {};

			if(/^\|(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = reslines.length - match[0];

				if(this.options.start < 1)
				{
					this.options.start = 1;
				}

				this.options.end = reslines.length;
			}
			else if(/^(\d+)-(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = Number(match[1]);
			}
			else if(/^-(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = 1;
				this.options.end   = Number(match[0]);
			}
			else if(/^(\d+)-n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = reslines.length;
			}
			else if(/^(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = Number(match[0]);
			}
			else if(/^$/.test(options))
			{
				this.options.first = false;
				this.options.start = 1;
				this.options.end   = reslines.length;
			}
			else
			{
				window.alert("IvVw肪słB");
			}

			this.pastfrom = this.options.start - 100;
			if(this.pastfrom < 1)
			{
				this.pastfrom = 1;
			}

			this.pastto = this.options.start - 1;
			if(this.pastto < 1)
			{
				this.pastto = 1;
			}

			this.nextfrom = this.options.end + 1;
			this.nextto   = this.options.end + 100;

		};
	})(BBSThread.prototype);

	window.BBSDat = BBSDat;
	window.BBSThread = BBSThread;
})();
<commit_msg>IE6でaタグのhref属性をgetAttributeしたときに絶対URLを返す問題に対応<commit_after>(function (undefined) {
	var isMSIE = /*@cc_on!@*/false;

	function BBSDat (thread) {
		this.thread = thread;
		this.ajax = new Ajax();
		this.init();
	}

	(function (p) {
		p.init = function () {
			this.data = "";
			this.lastmodified = "Thu, 01 Jun 1970 00:00:00 GMT";
		};
		p.renderHTML = function (options) {
			var html = [];
			var lines = this.data.getResLines();
			var rescnt;

			if(options.end == null)
			{
				options.end = lines.length;
			}

			rescnt = lines.length;

			if((options.first == true) && (options.start > 1))
			{
				html.push(lines[0].createResLine(1));
			}

			for(var i = (options.start - 1) ; ((i < options.end) && (i < rescnt)) ; i++)
			{
				if(lines[i] == "")
				{
					break;
				}

				html.push(lines[i].createResLine(i+1));
			}

			return html.join("\n");
		};

		p.requestDat = function (callback) {
			var url = this.thread.createDatURL();
			var self = this;
			var headers = {};

			headers["Content-Type"] = "text/plain; charset=x-sjis";
			headers["If-Modified-Since"] = this.lastmodified;

			this.ajax.get(url, {
				callback: function (data, status) {
					if(status === 404 || status === 302)
					{
						callback.call(self.thread, false, "YXbh͍폜ꂽA݂܂B");
					}
					else if(status !== 200 && status !== 304)
					{
						callback.call(self.thread, false, "ʐMG[܂B");
					}
					else if(status === 200)
					{
						self.data = data;
						var lastmodified;

						if(!(lastmodified = self.ajax.getResponseHeader("Last-Modified")))
						{
							callback.call(self.thread, false, "dat̍ŏIXV擾ł܂łB");
						}
						else
						{
							self.lastmodified = lastmodified;
							callback.call(self.thread, true, "");
						}
					}
					else
					{
						callback.call(self.thread, true, "");
					}
				},
				headers: headers
			});
		};
	})(BBSDat.prototype);

	function Rooter () {

	};

	Rooter.dispatch = function (thread, paths) {
		var	bbs = paths[1],
			key = paths[2],
			options = paths[3] || "";

		if(thread.bbs != bbs || thread.key != key) thread.datdata.init();

		thread.bbs = bbs;
		thread.key = key;

		thread.loadThread(function () {
			this.terminateLoadingView();
			this.parseOptions(decodeURIComponent(options));
			this.render();
		}, function () {
			if(this.requestcomp == false)
			{
				window.alert("ʐMł...");
				return false;
			}
			return true;
		});
	};

	Rooter.readPath = function (src) {
		if(/^\/(:bbs)\/index.html$/.test(src)) return src;
		else if(/^#!ID\/(\d+)(-\d+)?$/.test(src)) return src.substr(2);
		else if(/^#!\/.*$/.test(src)) return src.substr(2);
		return src;
	};

	(function (p) {

	})(Rooter.prototype);

	function BBSThread (paths) {
		this.requestcomp = true;
		this.shiftkey = false;

		var match = window.location.pathname.match(/^.*(\/test\/read.html)/g);

		this.urlbase = match[0].replace("test/read.html", "");

		var self = this;

		var onKeyDown = function (e) {
			var key = self.keyCode(e);

			if(key === 16) self.shiftkey = true;
			if(key === 13 && self.shiftkey)
			{
				e.preventDefault();
				self.postRes();
			}
		};

		if(window.opera)
		{
			$("#message").on("keypress", function (e) {
				return onKeyDown(e);
			});
		}
		else
		{
			$("#message").on("keydown", function (e) {
				return onKeyDown(e);
			});
		}

		$("#message").on("keyup", function (e) {
			var key = self.keyCode(e);
			if(key === 16) self.shiftkey = false;
		});

		$("#resparams").submit(function (e) {
			e.preventDefault();
			self.postRes();
			return false;
		});

		$("#name").val(Cookie.get("FROM"));
		$("#e-mail").val(Cookie.get("mail"));

		this.datdata = new BBSDat(this);
		this.ajax = new Ajax();

		this.startLoadingView();
		Rooter.dispatch(this, paths.split("/"));

		$("a").click(function (e) {
			var m,
				path = Rooter.readPath($(this).get(0).getAttribute("href", 2));

			if(path === "/:reload")
			{
				e.preventDefault();
				self.reload();
			}
			else if((m = path.match(/^ID\/(\d+)(-\d+)?$/)))
			{
				e.preventDefault();
				if(!m[2]) window.location.hash = "a" + m[1];
			}
			else if((m = path.match(/^\/(:bbs)\/index.html$/)))
			{
				e.preventDefault();
				window.location.href = self.urlbase + self.bbs + "/index.html";
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/(:pastfrom)-(:pastto)?$/)))
			{
				e.preventDefault();
				if(!self.options) return;
				var bbs = self.bbs,
					key = self.key,
					options = self.pastfrom + "-" + self.pastto;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/(:nextfrom)-(:nextto)?$/)))
			{
				e.preventDefault();
				if(!self.options) return;
				var bbs = self.bbs,
					key = self.key,
					options = self.nextfrom + "-" + self.nextto;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/(:bbs)\/(:key)\/([^\/]+)?$/)))
			{
				e.preventDefault();
				var bbs = self.bbs,
					key = self.key,
					options = m[3] || "";
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
			else if((m = path.match(/^\/([^\/]+)\/([^\/]+)\/([^\/]+)?$/)))
			{
				var bbs = m[1],
					key = m[2],
					options = m[3] || "" ;
				window.location.hash = "#!/" + bbs + "/" + key + "/" + options;
				Rooter.dispatch(self, ["", bbs, key, options]);
			}
		});
	}

	(function (p) {
		p.keyCode = function (e) {
			if(document.all) return e.originalEvent.keyCode;
			else if(document.getElementById) return (e.originalEvent.keyCode) ? e.originalEvent.keyCode : e.originalEvent.charCode;
			else if(document.layers) return e.originalEvent.which;
			else return 0;
		};
		p.createDatURL = function () {
			return (this.urlbase + this.bbs + "/dat/" + this.key + ".dat?" + (new Date()).getTime());
		};
		p.createPostURL = function () {
			return (this.urlbase + "test/bbs.cgi?guid=On");
		};
		p.loadThread = function (callback, beforeLoad) {
			if(beforeLoad && !beforeLoad.call(this)) return;

			this.requestcomp = false;

			this.datdata.requestDat(function (result, message) {
				this.requestcomp = true;
				if(!result) {
					alert(message);
				}
				else
				{
					callback.call(this);
				}
			});
		};
		p.postRes = function () {
			var self = this;
			var params = $("#resparams");

			this.startSendingView();

			this.ajax.post(this.createPostURL(), {
				callback: function (data, status) {
					self.terminateSendingView();

					var params = $("#resparams");
					if( (status == 200) && (//.test(data)) )
					{
						msgwindow = window.open();
						msgwindow.document.write(data);
					}
					params.find("#message").val("");

					self.options.end = null;
					self.loadThread(function () {
						this.render();
					});
				},
				params: {
					bbs: self.bbs,
					key: self.key,
					FROM: params.find("input[name='FROM']").val(),
					mail: params.find("input[name='mail']").val(),
					MESSAGE: params.find("#message").val(),
					submit: "",
					utn: "utn",
					time: params.find("input[name='time']").val(),
					suka: params.find("input[name='suka']").val()
				},
				headers: {
					"Referer": this.urlbase + "/" + this.bbs + "/",
					"Content-Type": "application/x-www-form-urlencoded"
				},
				encoder: EscapeSJIS
			});
		};
		p.reload = function () {
			this.startLoadingView();
			this.loadThread(function () {
				this.terminateLoadingView();
				this.render();
			});
		};
		p.startLoadingView = function () {
			var count = 3;

			this.timerid = window.setInterval(function () {
				count++;
				var str = "ǂݍݒ";
				for(var i=0; i < count; i++)
				{
					str += ".";
				}

				if(count > 20)
				{
					count = 0;
				}

				$("#resbodys").html("" + str + "");
			}, 100);
		};
		p.terminateLoadingView = function () {
			window.clearInterval(this.timerid);
		};
		p.startSendingView = function () {
			var count = 3;

			this.timerid = window.setInterval( function () {
				count++;
				var str = "ݒ";
				for(var i=0; i < count; i++)
				{
					str += ".";
				}

				if(count > 20)
				{
					count = 0;
				}

				$("#resbodys").html("" + str + "");
			}, 100);
		};
		p.terminateSendingView = function () {
			window.clearInterval(this.timerid);
		};
		p.render = function() {
			$("#resbodys").html(this.datdata.renderHTML(this.options));
			var lines = this.datdata.data.getResLines();
			var subject = lines[0].split("<>")[4];

			if(subject == undefined)
			{
				subject = 'X^Cs';
			}

			$("title").html(subject);
			$("#subject").html(subject);
			var date = new Date();
			var speed = (lines.length - 1) / (Math.floor(date.getTime() / 60000) - Math.floor(this.key / 60)) * 60 * 24;
			$("#speed").html("Speed:" + speed + "");
			$("#size").html(this.datdata.data.length - 1);
		};
		p.parseOptions = function(options) {
			var reslines = this.datdata.data.getResLines();

			this.options = {};

			if(/^\|(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = reslines.length - match[0];

				if(this.options.start < 1)
				{
					this.options.start = 1;
				}

				this.options.end = reslines.length;
			}
			else if(/^(\d+)-(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = Number(match[1]);
			}
			else if(/^-(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = 1;
				this.options.end   = Number(match[0]);
			}
			else if(/^(\d+)-n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = reslines.length;
			}
			else if(/^(\d+)n?$/.test(options))
			{
				var match = options.match(/\d+/g);

				if(/n$/.test(options))
				{
					this.options.first = false;
				}
				else
				{
					this.options.first = true;
				}

				this.options.start = Number(match[0]);
				this.options.end   = Number(match[0]);
			}
			else if(/^$/.test(options))
			{
				this.options.first = false;
				this.options.start = 1;
				this.options.end   = reslines.length;
			}
			else
			{
				window.alert("IvVw肪słB");
			}

			this.pastfrom = this.options.start - 100;
			if(this.pastfrom < 1)
			{
				this.pastfrom = 1;
			}

			this.pastto = this.options.start - 1;
			if(this.pastto < 1)
			{
				this.pastto = 1;
			}

			this.nextfrom = this.options.end + 1;
			this.nextto   = this.options.end + 100;

		};
	})(BBSThread.prototype);

	window.BBSDat = BBSDat;
	window.BBSThread = BBSThread;
})();
<|endoftext|>


<commit_before>"use strict";
var db = require('../neo4j/neo-connection.js');

/* /claims/:claimid
 * returns:
 *
 *  - the claim who's ID has been passed
 *  - the arguments that link to it
 *  - the claims that make up those arguments
 */

var returnObj = {
    "meta": "No meta yet",
    "data": {
        "id": "33",
        "text": "text text",
        "probability": "null",
        "arguments": [
            {
                "type": "SUPPORTS",
                "probability": "50",
                "premises": [
                    {
                        "id": "34",
                        "text": "premis text",
                        "probability": "50"
                    }
                ]
            }
        ]
    }
}

// query: `MATCH (claim:Claim)
//                     WHERE ID(claim) = ${req.params.claimid}
//                     OPTIONAL MATCH (subClaim:Claim)-[subLink]->(argument:ArgGroup)-[argLink]->(claim)
//                     OPTIONAL MATCH (claim)-[usedInLink]->(usedInArg)<-[usedInSiblingLink]-(usedInSibling)
//                     RETURN
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInSibling), text: usedInSibling.text, state: usedInSibling.state, type: "claim"}) END AS usedInSiblings,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInSiblingLink), type: "USED_IN", source: ID(startNode(usedInSiblingLink)), target: ID(endNode(usedInLink))}) END AS usedInSiblingLinks,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInArg), state: usedInArg.state, type: "argument"}) END AS usedInArgs,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInLink), type: "USED_IN", source: ID(startNode(usedInLink)), target: ID(endNode(usedInLink))}) END AS usedInLinks,
//                         {id: id(claim), text: claim.text, state: claim.state, type: "claim"} AS claim,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argLink), type: TYPE(argLink), source: ID(startNode(argLink)), target: ID(endNode(argLink))}) END AS argLinks,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argument), state: argument.state, type: "argument"}) END AS arguments,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subLink), type: TYPE(subLink), source: ID(startNode(subLink)), target: ID(endNode(subLink))}) END AS subLinks,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subClaim), text: subClaim.text, state: subClaim.state, type: "claim"}) END AS subClaims
//                     LIMIT 100`
module.exports = function(req, res){

                    //this would return USED_IN links and thir argument nodes - but not the other claims that make up uthose argument groups
                        //CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subLink), type: TYPE(subLink), source: ID(startNode(subLink)), target: ID(endNode(subLink))}) END AS subLinks,
                        //CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argLink), type: TYPE(argLink), source: ID(startNode(argLink)), target: ID(endNode(argLink))}) END AS argLinks,
    try {
        db.cypher({
            query: `MATCH (claim)
                    WHERE (claim:Claim OR claim:Axiom) AND (ID(claim) = ${req.params.claimid})
                    OPTIONAL MATCH (argument:ArgGroup)-[argLink]->(claim)
                    OPTIONAL MATCH (premis:Claim)-[premisLink]->(argument)
                    WITH claim, argument, argLink,
                        CASE WHEN ID(premis) IS NULL THEN null ELSE {id: ID(premis), text: premis.text, labels: LABELS(premis), probability: premis.probability} END AS premises
                    WITH claim,
                        CASE WHEN ID(argument) IS NULL THEN null ELSE {id: ID(argument), type:TYPE(argLink), probability: argument.probability, premises: COLLECT(premises)} END AS arguments
                    WITH {id: id(claim), text: claim.text, labels: LABELS(claim), probability: claim.probability, arguments: COLLECT(arguments)} AS claim
                    RETURN claim
                    LIMIT 100`
        }, function (err, results) {
            if (err) throw err;

            if (!results) {
                console.log('No claims found.');
                res.json({ error: 'No claims found' });
            } else {
                if (results.length == 0){

                    res.json({
                        meta: 'No claims match ' + req.params.claimid,
                        data: {}
                    });
                    return;
                }

                if (results.length > 1){
                    //should only return one claim when getting by id... something's wrong with the data (scream!)
                    console.log('many many many');
                }

                res.json({
                    meta: 'No meta yet',
                    data: results[0]
                });
            }
        });

    }
    catch(err){
        console.log('error happened - meep moop');
        res.json({
            errors: JSON.stringify(err),
        });
    }
}<commit_msg>encapsulated more cypher into procedures<commit_after>"use strict";
var db = require('../neo4j/neo-connection.js');

/* /claims/:claimid
 * returns:
 *
 *  - the claim who's ID has been passed
 *  - the arguments that link to it
 *  - the claims that make up those arguments
 */

var returnObj = {
    "meta": "No meta yet",
    "data": {
        "id": "33",
        "text": "text text",
        "probability": "null",
        "arguments": [
            {
                "type": "SUPPORTS",
                "probability": "50",
                "premises": [
                    {
                        "id": "34",
                        "text": "premis text",
                        "probability": "50"
                    }
                ]
            }
        ]
    }
}

// query: `MATCH (claim:Claim)
//                     WHERE ID(claim) = ${req.params.claimid}
//                     OPTIONAL MATCH (subClaim:Claim)-[subLink]->(argument:ArgGroup)-[argLink]->(claim)
//                     OPTIONAL MATCH (claim)-[usedInLink]->(usedInArg)<-[usedInSiblingLink]-(usedInSibling)
//                     RETURN
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInSibling), text: usedInSibling.text, state: usedInSibling.state, type: "claim"}) END AS usedInSiblings,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInSiblingLink), type: "USED_IN", source: ID(startNode(usedInSiblingLink)), target: ID(endNode(usedInLink))}) END AS usedInSiblingLinks,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInArg), state: usedInArg.state, type: "argument"}) END AS usedInArgs,
//                         CASE WHEN ID(usedInArg) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(usedInLink), type: "USED_IN", source: ID(startNode(usedInLink)), target: ID(endNode(usedInLink))}) END AS usedInLinks,
//                         {id: id(claim), text: claim.text, state: claim.state, type: "claim"} AS claim,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argLink), type: TYPE(argLink), source: ID(startNode(argLink)), target: ID(endNode(argLink))}) END AS argLinks,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argument), state: argument.state, type: "argument"}) END AS arguments,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subLink), type: TYPE(subLink), source: ID(startNode(subLink)), target: ID(endNode(subLink))}) END AS subLinks,
//                         CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subClaim), text: subClaim.text, state: subClaim.state, type: "claim"}) END AS subClaims
//                     LIMIT 100`
module.exports = function(req, res){

                    //this would return USED_IN links and thir argument nodes - but not the other claims that make up uthose argument groups
                        //CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(subLink), type: TYPE(subLink), source: ID(startNode(subLink)), target: ID(endNode(subLink))}) END AS subLinks,
                        //CASE WHEN ID(argument) IS NULL THEN [] ELSE COLLECT(DISTINCT {id: ID(argLink), type: TYPE(argLink), source: ID(startNode(argLink)), target: ID(endNode(argLink))}) END AS argLinks,
    try {
        db.cypher({
            query: `call WL.GetClaimWithArgs(${req.params.claimid})`
        }, function (err, results) {
            if (err) throw err;

            if (!results) {
                console.log('No claims found.');
                res.json({ error: 'No claims found' });
            } else {
                if (results.length == 0){

                    res.json({
                        meta: 'No claims match ' + req.params.claimid,
                        data: {}
                    });
                    return;
                }

                if (results.length > 1){
                    //should only return one claim when getting by id... something's wrong with the data (scream!)
                    console.log('many many many');
                }

                res.json({
                    meta: 'No meta yet',
                    data: results[0]
                });
            }
        });

    }
    catch(err){
        console.log('error happened - meep moop');
        res.json({
            errors: JSON.stringify(err),
        });
    }
}<|endoftext|>


<commit_before>var path = require('path'),
    expect = require('chai').expect,
    AtomUtil = require('../src/atom-util');

describe('Atom Util', function() {
    var object;

    beforeEach(function() {
        object = {
            'project1': {
                title: 'Project #1',
                paths: ['dir/path1']
            },
            'project2': {
                title: 'Project #2',
                paths: ['dir/path2']
            }
        };
    });

    describe('Projects object parsing', function() {
        it('parses basic object', function() {
            var projects = AtomUtil.parseProjects(object);
            expect(projects).to.have.lengthOf(2);
            expect(projects[0]).to.deep.equal({
                title: 'Project #1',
                subtitle: 'dir/path1',
                icon: 'icon.png',
                arg: 'dir/path1',
                valid: true
            });
            expect(projects[1]).to.deep.equal({
                title: 'Project #2',
                subtitle: 'dir/path2',
                icon: 'icon.png',
                arg: 'dir/path2',
                valid: true
            });
        });

        it('handles no arguments', function() {
            var projects = AtomUtil.parseProjects();
            expect(projects).to.be.a('array');
            expect(projects).to.have.lengthOf(0);
        });

        it('handles undefined object', function() {
            var projects = AtomUtil.parseProjects(undefined, 'project');
            expect(projects).to.be.a('array');
            expect(projects).to.have.lengthOf(0);
        });

        it('parses project with multiple paths', function() {
            object.project1.paths = ['dir/path3', 'dir/path4'];
            var projects = AtomUtil.parseProjects(object);
            expect(projects).to.have.lengthOf(2);
            expect(projects[0]).to.deep.include({
                subtitle: 'dir/path3, dir/path4',
                arg: 'dir/path3 dir/path4'
            });
        });

        it('sets development flag', function() {
            object.project1.devMode = true;
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].arg).to.equal('dir/path1 -d');
        });

        it('append group', function() {
            object.project1.group = 'group1';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].subtitle).to.equal('[group1] dir/path1');
        });

        it('checks paths for an icon', function() {
            var projectPath = path.join(__dirname, '..');
            object.project1.paths.push(projectPath);
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].icon).to.equal(path.join(projectPath, 'icon.png'));
            expect(projects[1].icon).to.equal('icon.png');
        });

        it('accepts icon key', function() {
            object.project1.icon = 'icon-book';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].icon).to.equal('octicons/book-128.png');
            expect(projects[1].icon).to.equal('icon.png');
        });

        it('handles non-existing icon', function() {
            object.project2.icon = 'non-existing';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[1].icon).to.equal('icon.png');
        });
    });

    describe('Projects filtering', function() {
        it('filters results by title', function() {
            var projects = AtomUtil.parseProjects(object, 'ct2');
            expect(projects).to.have.lengthOf(1);
            expect(projects[0].title).to.equal('Project #2');
        });

        it('filters results by group', function() {
            object.project1.group = 'test group';
            var projects = AtomUtil.parseProjects(object, 'test group');
            expect(projects).to.have.lengthOf(1);
            expect(projects[0].title).to.equal('Project #1');
        });

        it('handles empty filter query', function() {
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(2);
        });
    });

    describe('Malformed projects object', function() {
        it('handles missing title', function() {
            delete object.project1.title;
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(1);
        });

        it('handles missing path (templates)', function() {
            delete object.project1.paths;
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(1);
        });
    });
});
<commit_msg>Update tests<commit_after>var path = require('path'),
    expect = require('chai').expect,
    AtomUtil = require('../src/atom-util');

describe('Atom Util', function() {
    var object;

    beforeEach(function() {
        object = {
            'project1': {
                title: 'Project #1',
                paths: ['dir/path1']
            },
            'project2': {
                title: 'Project #2',
                paths: ['dir/path2']
            }
        };
    });

    describe('Projects object parsing', function() {
        it('parses basic object', function() {
            var projects = AtomUtil.parseProjects(object);
            expect(projects).to.have.lengthOf(2);
            expect(projects[0]).to.deep.equal({
                title: 'Project #1',
                subtitle: 'dir/path1',
                icon: 'icon.png',
                arg: '\"dir/path1\"',
                valid: true,
                uid: 'project_#1',
                text: {
                    copy: '\"dir/path1\"'
                }
            });
            expect(projects[1]).to.deep.equal({
                title: 'Project #2',
                subtitle: 'dir/path2',
                icon: 'icon.png',
                arg: '\"dir/path2\"',
                valid: true,
                uid: 'project_#2',
                text: {
                    copy: '\"dir/path2\"'
                }
            });
        });

        it('handles no arguments', function() {
            var projects = AtomUtil.parseProjects();
            expect(projects).to.be.a('array');
            expect(projects).to.have.lengthOf(0);
        });

        it('handles undefined object', function() {
            var projects = AtomUtil.parseProjects(undefined, 'project');
            expect(projects).to.be.a('array');
            expect(projects).to.have.lengthOf(0);
        });

        it('parses project with multiple paths', function() {
            object.project1.paths = ['dir/path3', 'dir/path4'];
            var projects = AtomUtil.parseProjects(object);
            expect(projects).to.have.lengthOf(2);
            expect(projects[0]).to.deep.include({
                subtitle: 'dir/path3, dir/path4',
                arg: '\"dir/path3\" \"dir/path4\"'
            });
        });

        it('append group', function() {
            object.project1.group = 'group1';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].title).to.equal('Project #1 - group1');
        });

        it('checks paths for an icon', function() {
            var projectPath = path.join(__dirname, '..');
            object.project1.paths.push(projectPath);
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].icon).to.equal(path.join(projectPath, 'icon.png'));
            expect(projects[1].icon).to.equal('icon.png');
        });

        it('accepts icon key', function() {
            object.project1.icon = 'icon-book';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[0].icon).to.equal('octicons/book-128.png');
            expect(projects[1].icon).to.equal('icon.png');
        });

        it('handles non-existing icon', function() {
            object.project2.icon = 'non-existing';
            var projects = AtomUtil.parseProjects(object);
            expect(projects[1].icon).to.equal('icon.png');
        });
    });

    describe('Projects filtering', function() {
        it('filters results by title', function() {
            var projects = AtomUtil.parseProjects(object, 'ct2');
            expect(projects).to.have.lengthOf(1);
            expect(projects[0].title).to.equal('Project #2');
        });

        it('filters results by group', function() {
            object.project1.group = 'test group';
            var projects = AtomUtil.parseProjects(object, 'test group');
            expect(projects).to.have.lengthOf(1);
            expect(projects[0].title).to.equal('Project #1 - test group');
        });

        it('handles empty filter query', function() {
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(2);
        });
    });

    describe('Malformed projects object', function() {
        it('handles missing title', function() {
            delete object.project1.title;
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(1);
        });

        it('handles missing path (templates)', function() {
            delete object.project1.paths;
            var projects = AtomUtil.parseProjects(object, '');
            expect(projects).to.have.lengthOf(1);
        });
    });
});
<|endoftext|>


<commit_before>var firstUpload = true;
var uploads = 0;

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function adOptOut() {
    createCookie('ad-opt-out', '1', 0);
    var gad = document.getElementById('gad');
    var lgad = document.getElementById('lgad');
    gad.parentElement.removeChild(gad);
    lgad.parentElement.removeChild(lgad);
}

function handleFiles(files) {
    uploadFiles(files);
}

function uploadFiles(files) {
    var droparea = document.getElementById('droparea');
    droparea.style.overflowY = 'scroll';
    if (firstUpload) {
        droparea.innerHTML = '';
        firstUpload = false;
    }
    for (var i = 0; i < files.length; i++) {
        uploads++;
        var element = document.createElement('div');
        element.className = 'image-loading';
        prepareImage(element, files[i]);

        var name = document.createElement('h2');
        name.innerHTML = files[i].name;

        var result = document.createElement('div');

        var progress = document.createElement('div');
        progress.className = 'progress';

        var clearfix = document.createElement('div');
        clearfix.className = 'clearfix';

        element.appendChild(name);
        element.appendChild(result);
        element.appendChild(progress);
        element.appendChild(clearfix);
        droparea.appendChild(element);

        uploadFile(progress, result, files[i]);
    }
}

function prepareImage(parentElement, file) {
    var wrapper = document.createElement('div');
    wrapper.setAttribute('class', 'img-wrapper');
    var reader = new FileReader();

    if(file.type.indexOf("image") != -1) {
        var image = document.createElement('img');

        reader.onloadend = function(e) {
            image.src = e.target.result;
        };
        reader.readAsDataURL(file);

        wrapper.appendChild(image);
    } else if (file.type.indexOf("audio") != -1) {
        var image = document.createElement('img');
        image.src = '/static/audio.png';
        wrapper.appendChild(image);
    } else {
        var video = document.createElement('video');
        video.setAttribute('loop', 'loop');
        var source = document.createElement('source');

        reader.onloadend = function(e) {
            source.setAttribute('src', e.target.result);
            source.setAttribute('type', file.type);
            video.appendChild(source);
            wrapper.appendChild(video);
            video.volume = 0;
            video.play();
        };
        reader.readAsDataURL(file);
    }
    parentElement.appendChild(wrapper);
}

function showURL(result, url) {
    var text = document.createElement('p');
    text.innerHTML = 'Upload complete!';
    var link = document.createElement('a');
    link.href = '/' + url;
    link.setAttribute('target', '_blank');
    link.innerHTML = window.location.origin + '/' + url;
    result.appendChild(text);
    result.appendChild(link);
    uploads--;
}

function checkStatus(processing, progress, result, url) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', '/upload/status/' + url);
    xhr.onload = function() {
        var response = this.responseText;
        if (response == 'done') {
            progress.style.width = 0;
            processing.parentElement.removeChild(processing);
            showURL(result, url)
        } else if (response == 'timeout' || response == 'error') {
            error = document.createElement("span");
            if (response == 'timeout') {
                error.innerHTML = "This file took too long to process.";
            } else {
                error.innerHTML = "There was an error processing this file.";
            }

            error.className = "error";
            result.appendChild(error);
            uploads--;
        } else {
            // Try again.
            setTimeout(function() {
                checkStatus(processing, progress, result, url);
            }, 1000);
        }
    };

    xhr.send();
}

function uploadFile(progress, result, file) {
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '/upload/');
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            progress.style.width = (e.loaded / e.total) * 100 + '%';
        }
    };
    xhr.onload = function() {
        progress.style.width = 0;
        var status = this.status;
        var error = '';
        var url = this.responseText;

        if (status == 415) {        // Unsupported media type
            error = 'This image format is not supported.';
        } else if (status == 409) { // Already uploaded
            showURL(result, url);
        } else if (status == 200) { // OK
            processing = document.createElement('span');
            processing.innerHTML = 'Processing...';

            progress.style.width = "100%";
            progress.className += " progress-green"
            result.appendChild(processing);

            // Start a timer that checks whether the gif has finished processing successfully.
            checkStatus(processing, progress, result, url);
        } else if (status == 400) {
            error = 'You have consumed your hourly quota. Please try again later.';
        } else {
            error = 'An error has occured. Please try again.';
        }
        if (error != '') {
            var errorText = document.createElement('p');
            errorText.innerHTML = 'Error: ' + error;
            errorText.className = 'error';
            result.appendChild(errorText);
        }
    };

    var formData = new FormData();
    formData.append('file', file);
    xhr.send(formData);
}

function dragNop(e) {
    e.stopPropagation();
    e.preventDefault();
}

function dragDrop(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = null;
    var files = e.dataTransfer.files;
    var count = files.length;

    if (count > 0) {
        handleFiles(files);
    }
}

function dragEnter(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = 'hover';
}

function dragLeave(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = null;
}

function dropEnable() {
    var droparea = document.getElementById('droparea');
    droparea.addEventListener('dragenter', dragEnter, false);
    droparea.addEventListener('dragleave', dragLeave, false);
    droparea.addEventListener('dragover', dragNop, false);
    droparea.addEventListener('drop', dragDrop, false);
}

window.onload = dropEnable;
window.onbeforeunload = function() {
    if (uploads != 0) {
        return "If you leave the page, these uploads will be cancelled.";
    }
};
<commit_msg>Inform users when uploads are too large, closes #75<commit_after>var firstUpload = true;
var uploads = 0;

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function adOptOut() {
    createCookie('ad-opt-out', '1', 0);
    var gad = document.getElementById('gad');
    var lgad = document.getElementById('lgad');
    gad.parentElement.removeChild(gad);
    lgad.parentElement.removeChild(lgad);
}

function handleFiles(files) {
    uploadFiles(files);
}

function uploadFiles(files) {
    var droparea = document.getElementById('droparea');
    droparea.style.overflowY = 'scroll';
    if (firstUpload) {
        droparea.innerHTML = '';
        firstUpload = false;
    }
    for (var i = 0; i < files.length; i++) {
        uploads++;
        var element = document.createElement('div');
        element.className = 'image-loading';
        prepareImage(element, files[i]);

        var name = document.createElement('h2');
        name.innerHTML = files[i].name;

        var result = document.createElement('div');

        var progress = document.createElement('div');
        progress.className = 'progress';

        var clearfix = document.createElement('div');
        clearfix.className = 'clearfix';

        element.appendChild(name);
        element.appendChild(result);

        if (files[i].size > 26214400) {
            var error = document.createElement("span");
            error.innerHTML = "This file is too large. The maximum is 25 MB.";
            error.className = "error";
            result.appendChild(error);
            droparea.appendChild(element);
            uploads--;
        } else {
            element.appendChild(progress);
            element.appendChild(clearfix);
            droparea.appendChild(element);
            uploadFile(progress, result, files[i]);
        }
    }
}

function prepareImage(parentElement, file) {
    var wrapper = document.createElement('div');
    wrapper.setAttribute('class', 'img-wrapper');
    var reader = new FileReader();

    if(file.type.indexOf("image") != -1) {
        var image = document.createElement('img');

        reader.onloadend = function(e) {
            image.src = e.target.result;
        };
        reader.readAsDataURL(file);

        wrapper.appendChild(image);
    } else if (file.type.indexOf("audio") != -1) {
        var image = document.createElement('img');
        image.src = '/static/audio.png';
        wrapper.appendChild(image);
    } else {
        var video = document.createElement('video');
        video.setAttribute('loop', 'loop');
        var source = document.createElement('source');

        reader.onloadend = function(e) {
            source.setAttribute('src', e.target.result);
            source.setAttribute('type', file.type);
            video.appendChild(source);
            wrapper.appendChild(video);
            video.volume = 0;
            video.play();
        };
        reader.readAsDataURL(file);
    }
    parentElement.appendChild(wrapper);
}

function showURL(result, url) {
    var text = document.createElement('p');
    text.innerHTML = 'Upload complete!';
    var link = document.createElement('a');
    link.href = '/' + url;
    link.setAttribute('target', '_blank');
    link.innerHTML = window.location.origin + '/' + url;
    result.appendChild(text);
    result.appendChild(link);
    uploads--;
}

function checkStatus(processing, progress, result, url) {
    var xhr = new XMLHttpRequest();

    xhr.open('GET', '/upload/status/' + url);
    xhr.onload = function() {
        var response = this.responseText;
        if (response == 'done') {
            progress.style.width = 0;
            processing.parentElement.removeChild(processing);
            showURL(result, url)
        } else if (response == 'timeout' || response == 'error') {
            error = document.createElement("span");
            if (response == 'timeout') {
                error.innerHTML = "This file took too long to process.";
            } else {
                error.innerHTML = "There was an error processing this file.";
            }

            error.className = "error";
            result.appendChild(error);
            uploads--;
        } else {
            // Try again.
            setTimeout(function() {
                checkStatus(processing, progress, result, url);
            }, 1000);
        }
    };

    xhr.send();
}

function uploadFile(progress, result, file) {
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '/upload/');
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            progress.style.width = (e.loaded / e.total) * 100 + '%';
        }
    };
    xhr.onload = function() {
        progress.style.width = 0;
        var status = this.status;
        var error = '';
        var url = this.responseText;

        if (status == 415) {        // Unsupported media type
            error = 'This image format is not supported.';
        } else if (status == 409) { // Already uploaded
            showURL(result, url);
        } else if (status == 200) { // OK
            processing = document.createElement('span');
            processing.innerHTML = 'Processing...';

            progress.style.width = "100%";
            progress.className += " progress-green"
            result.appendChild(processing);

            // Start a timer that checks whether the gif has finished processing successfully.
            checkStatus(processing, progress, result, url);
        } else if (status == 400) {
            error = 'You have consumed your hourly quota. Please try again later.';
        } else {
            error = 'An error has occured. Please try again.';
        }
        if (error != '') {
            var errorText = document.createElement('p');
            errorText.innerHTML = 'Error: ' + error;
            errorText.className = 'error';
            result.appendChild(errorText);
        }
    };

    var formData = new FormData();
    formData.append('file', file);
    xhr.send(formData);
}

function dragNop(e) {
    e.stopPropagation();
    e.preventDefault();
}

function dragDrop(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = null;
    var files = e.dataTransfer.files;
    var count = files.length;

    if (count > 0) {
        handleFiles(files);
    }
}

function dragEnter(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = 'hover';
}

function dragLeave(e) {
    dragNop(e);
    var droparea = document.getElementById('droparea');
    droparea.className = null;
}

function dropEnable() {
    var droparea = document.getElementById('droparea');
    droparea.addEventListener('dragenter', dragEnter, false);
    droparea.addEventListener('dragleave', dragLeave, false);
    droparea.addEventListener('dragover', dragNop, false);
    droparea.addEventListener('drop', dragDrop, false);
}

window.onload = dropEnable;
window.onbeforeunload = function() {
    if (uploads != 0) {
        return "If you leave the page, these uploads will be cancelled.";
    }
};
<|endoftext|>


<commit_before>var Survey = require('./survey');
var Question = require('./question');
var Option   = require('./option');
var Response   = require('./response');
var Request   = require('./request');

var Sentiment = require('sentiment');

var findResponses = function(Obj, cb){
	Response.sortASC(Obj, function(err, responses){
      if(err) return cb(err, Obj);
      else {
        var userResponse = [];
        var surveyResponse = [];
        var next = '';
        for(var i in responses){
          if(next == responses[i].respondant){
            userResponse.push(responses[i]);
            var lengt = i;
            lengt++;
            if(responses[lengt]){
              if(responses[i].respondant !== responses[lengt].respondant){
                surveyResponse.push(userResponse);
                userResponse = [];
              }
            } else surveyResponse.push(userResponse);
          } else {
            if(next == '') {
              userResponse.push(responses[i]);
            } else {
              userResponse.push(responses[i]);
            }
          }
          next = responses[i].respondant;
          var leng = i;
          leng++;
        }
        return cb(null, surveyResponse);
      }
    });
};

var findSurveyForm = function(Obj, cb){
	Survey({_id:Obj.id}, function(err, survey){
		if(err) return cb(err, Obj);
		else {
			Question({survey:Obj.id}, function(err, questions){
				if(err) return cb(err, Obj);
				else {
					survey[0].questions = questions;
					Option({survey:Obj.id}, function(err, options){
						if(err) return cb(err, Obj);
						else {
							for(var i in survey[0].questions){
								survey[0].questions[i].options = [];
								for(var j in options){
									if(options[j].question){
										if(survey[0].questions[i].id.toString() == options[j].question.toString()){
											survey[0].questions[i].options.push(options[j]);
										}
									}
								}
							}
							return cb(null, survey[0]);
						}
					});
				}
			});
		}
	});
};

var isUniqueResponse = function(id, Obj){
  var count = 0;
  for(var i in Obj){
    if(Obj[i].question.toString() == id){
      count++;
    }
  }
  return 1 < count ? false : true;
};

module.exports = function(Obj, cb){
	if(Obj){
		var search = Obj;
		if(Obj.id){
			search._id = Obj.id;
			delete search.id;
		}
		Survey(search, function(err, survey){
			if(err) return cb(err, Obj);
			else {
				Question({survey:search._id}, function(err, questions){
					if(err) return cb(err, Obj);
					else {
						if(questions[0]){
							survey[0].questions = questions;
							Option({survey:search._id}, function(err, options){
								if(err) return cb(err, Obj);
								else {
									if(options[0]){
										survey[0].options = options;
										return cb(null, survey);
									} else return cb(null, survey);
								}
							});
						} else return cb(null, survey);
					}
				});
			}
		});
	} else {
		return cb({type:'!No READ Item'}, Obj);
	}
};

module.exports.survey    = Survey;
module.exports.question  = Question;
module.exports.option    = Option;
module.exports.response  = Response;
module.exports.request   = Request;

module.exports.responses  = function(Obj, cb){
  if(Obj){
		findResponses(Obj, function(err, responses){
			if(err) return cb(err, Obj);
			else return cb(null, responses);

		});
  } else return cb({type:'!No Object to lookup.'}, Obj);
};

module.exports.surveyForm = function(Obj, cb){
	if(Obj){
		findSurveyForm(Obj, function(err, form){
			if(err) return cb(err, Obj);
			else return cb(null, form);

		});
	} else return cb({type:'!No Object To Create'}, Obj);
};

module.exports.recentSurveys = function(Obj, cb){
	Survey.recent(5, function(err, surveys){
		if(err) return cb(err, Obj);
		else return cb(null, surveys);
	});
};

module.exports.surveyResult = function(Obj, cb){
	if(Obj){
		findSurveyForm(Obj, function(err, form){
			if(err) return cb(err, Obj);
			else findResponses({survey:Obj.id}, function(err, responses){
				if(err) return cb(err, Obj);
				else {
					for(var i in responses){
					  var guage = true;
						for(var n in responses[i]){
							for(var j in form.questions){
								if(responses[i][n].question.toString() == form.questions[j].id.toString()){
									for(var k in form.questions[j].options){
										if(form.questions[j].options[k].id.toString() == responses[i][n].option.toString()){
											if(form.questions[j].options[k].option != 'opinion'){
											    if(form.questions[j].options[k].selected) form.questions[j].options[k].selected++;
											    else form.questions[j].options[k].selected = 1;
											    var checker = isUniqueResponse(form.questions[j].id.toString(), responses[i]);
									            if(checker){
									              if(form.questions[j].selected) form.questions[j].selected++;
									              else form.questions[j].selected = 1;
									            } else {
									              if(guage){
									                if(form.questions[j].selected) form.questions[j].selected++;
									                else form.questions[j].selected = 1;
									                guage = false;
									              }
									            }
											} else {
											  if(responses[i][n].response != undefined){
												  var sentiment = Sentiment(responses[i][n].response);
											      if(form.questions[j].options[k].selected) {
											    	  form.questions[j].options[k].score.push(sentiment.score);
											    	  form.questions[j].options[k].comparative.push(sentiment.comparative);
											    	  form.questions[j].options[k].selected++;
											    	  form.questions[j].selected++;
											      } else {
											    	  form.questions[j].options[k].score = ['Score',sentiment.score];
											    	  form.questions[j].options[k].comparative = ['Relevance',sentiment.comparative];
											    	  form.questions[j].options[k].selected = 1;
											    	  form.questions[j].selected = 1;
											      }
											  }
											}
										}
									}
								}
							}
						}
					}
					if(responses.length) form.responded = responses.length;
					else form.responded = 0;
					return cb(null, form);
				}
			});
		});
	} else return cb({type:'!No Object To Create'}, Obj);
};

module.exports.requestedResponse = function(Obj, cb){
	if(Obj){
		Request(Obj, function(err, respondants){
			if(err) return cb(err, Obj);
			else return cb(null, respondants);
		});
	}

};<commit_msg>query alg addition to response analysis<commit_after>var Survey = require('./survey');
var Question = require('./question');
var Option   = require('./option');
var Response   = require('./response');
var Request   = require('./request');

var Sentiment = require('sentiment');

var findResponses = function(Obj, cb){
	Response.sortASC(Obj, function(err, responses){
      if(err) return cb(err, Obj);
      else {
        var userResponse = [];
        var surveyResponse = [];
        var next = '';
        for(var i in responses){
          if(next == responses[i].respondant){
            userResponse.push(responses[i]);
            var lengt = i;
            lengt++;
            if(responses[lengt]){
              if(responses[i].respondant !== responses[lengt].respondant){
                surveyResponse.push(userResponse);
                userResponse = [];
              }
            } else surveyResponse.push(userResponse);
          } else {
            if(next == '') {
              userResponse.push(responses[i]);
            } else {
              userResponse.push(responses[i]);
            }
            var lengt = i;
            lengt++;
            if(responses[lengt]){
              if(responses[i].respondant !== responses[lengt].respondant){
                surveyResponse.push(userResponse);
                userResponse = [];
              }
            } else surveyResponse.push(userResponse);
          }
          next = responses[i].respondant;
          var leng = i;
          leng++;
        }
        return cb(null, surveyResponse);
      }
    });
};

var findSurveyForm = function(Obj, cb){
	Survey({_id:Obj.id}, function(err, survey){
		if(err) return cb(err, Obj);
		else {
			Question({survey:Obj.id}, function(err, questions){
				if(err) return cb(err, Obj);
				else {
					survey[0].questions = questions;
					Option({survey:Obj.id}, function(err, options){
						if(err) return cb(err, Obj);
						else {
							for(var i in survey[0].questions){
								survey[0].questions[i].options = [];
								for(var j in options){
									if(options[j].question){
										if(survey[0].questions[i].id.toString() == options[j].question.toString()){
											survey[0].questions[i].options.push(options[j]);
										}
									}
								}
							}
							return cb(null, survey[0]);
						}
					});
				}
			});
		}
	});
};

var isUniqueResponse = function(id, Obj){
  var count = 0;
  for(var i in Obj){
    if(Obj[i].question.toString() == id){
      count++;
    }
  }
  return 1 < count ? false : true;
};

module.exports = function(Obj, cb){
	if(Obj){
		var search = Obj;
		if(Obj.id){
			search._id = Obj.id;
			delete search.id;
		}
		Survey(search, function(err, survey){
			if(err) return cb(err, Obj);
			else {
				Question({survey:search._id}, function(err, questions){
					if(err) return cb(err, Obj);
					else {
						if(questions[0]){
							survey[0].questions = questions;
							Option({survey:search._id}, function(err, options){
								if(err) return cb(err, Obj);
								else {
									if(options[0]){
										survey[0].options = options;
										return cb(null, survey);
									} else return cb(null, survey);
								}
							});
						} else return cb(null, survey);
					}
				});
			}
		});
	} else {
		return cb({type:'!No READ Item'}, Obj);
	}
};

module.exports.survey    = Survey;
module.exports.question  = Question;
module.exports.option    = Option;
module.exports.response  = Response;
module.exports.request   = Request;

module.exports.responses  = function(Obj, cb){
  if(Obj){
		findResponses(Obj, function(err, responses){
			if(err) return cb(err, Obj);
			else return cb(null, responses);

		});
  } else return cb({type:'!No Object to lookup.'}, Obj);
};

module.exports.surveyForm = function(Obj, cb){
	if(Obj){
		findSurveyForm(Obj, function(err, form){
			if(err) return cb(err, Obj);
			else return cb(null, form);

		});
	} else return cb({type:'!No Object To Create'}, Obj);
};

module.exports.recentSurveys = function(Obj, cb){
	Survey.recent(5, function(err, surveys){
		if(err) return cb(err, Obj);
		else return cb(null, surveys);
	});
};

module.exports.surveyResult = function(Obj, cb){
	if(Obj){
		findSurveyForm(Obj, function(err, form){
			if(err) return cb(err, Obj);
			else findResponses({survey:Obj.id}, function(err, responses){
				if(err) return cb(err, Obj);
				else {
					for(var i in responses){
					  var guage = true;
						for(var n in responses[i]){
							for(var j in form.questions){
								if(responses[i][n].question.toString() == form.questions[j].id.toString()){
									for(var k in form.questions[j].options){
										if(form.questions[j].options[k].id.toString() == responses[i][n].option.toString()){
											if(form.questions[j].options[k].option != 'opinion'){
											    if(form.questions[j].options[k].selected) form.questions[j].options[k].selected++;
											    else form.questions[j].options[k].selected = 1;
											    var checker = isUniqueResponse(form.questions[j].id.toString(), responses[i]);
									            if(checker){
									              if(form.questions[j].selected) form.questions[j].selected++;
									              else form.questions[j].selected = 1;
									            } else {
									              if(guage){
									                if(form.questions[j].selected) form.questions[j].selected++;
									                else form.questions[j].selected = 1;
									                guage = false;
									              }
									            }
											} else {
											  if(responses[i][n].response != undefined){
												  var sentiment = Sentiment(responses[i][n].response);
											      if(form.questions[j].options[k].selected) {
											    	  form.questions[j].options[k].score.push(sentiment.score);
											    	  form.questions[j].options[k].comparative.push(sentiment.comparative);
											    	  form.questions[j].options[k].selected++;
											    	  form.questions[j].selected++;
											      } else {
											    	  form.questions[j].options[k].score = ['Score',sentiment.score];
											    	  form.questions[j].options[k].comparative = ['Relevance',sentiment.comparative];
											    	  form.questions[j].options[k].selected = 1;
											    	  form.questions[j].selected = 1;
											      }
											  }
											}
										}
									}
								}
							}
						}
					}
					if(responses.length) form.responded = responses.length;
					else form.responded = 0;
					return cb(null, form);
				}
			});
		});
	} else return cb({type:'!No Object To Create'}, Obj);
};

module.exports.requestedResponse = function(Obj, cb){
	if(Obj){
		Request(Obj, function(err, respondants){
			if(err) return cb(err, Obj);
			else return cb(null, respondants);
		});
	}

};<|endoftext|>


<commit_before>//Variables for items on menu
var toggleBar = document.getElementById('toggleBar');
var allSchoolsToggle = document.getElementById('listToggle');
var filtersToggle = document.getElementById('filtersToggle');
var searchToggle = document.getElementById('searchToggle');

var markerList = document.getElementById('markers-list')
var typesList = document.getElementById('types-list');
var interestAreasList = document.getElementById('interest-areas-list');
var clusterGroup, featureLayer;
var filterItemObj = {}, checkboxes=[];
var rawData;

//Place all school markers on map at load
$.ajax({
  dataType: 'json',
  url: '/',
  type: 'GET'
}).success(function(data){
  rawData = data;
  loadAllSchools(data);
});

//Function that places all schools on map
function loadAllSchools(data) {
  $("#search-option").hide();
  $("#filters").hide();
  $("#markers-list").show();
  featureLayer = L.mapbox.featureLayer(data)
  clusterGroup = createClusterGroup(featureLayer)
  map.addLayer(clusterGroup);
  clusterGroup.eachLayer(function(marker) {
    addMarkerContent(marker);
  })
  createAllSchoolsMarkerList(featureLayer);
  finishedLoading();
}

//Displaying of markers methods
function addMarkerContent(marker) {
  var rightArrow = document.createElement("img")
  rightArrow.src = "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png";
  rightArrow.alt="Right Arrow";
  rightArrow.id="right-arrow";
  rightArrow.className= "right-arrow";

  rightArrow.addEventListener('click',function(){openModal(properties)});

  var properties = marker.feature.properties;
  popupContent =
  '
' +
  '
' +
  // '

' +
  '
' +
  '
' +
  '
' + properties.name + '
' +
  '
' + properties.address + ', ' + properties.zip + '
' +
  '
' +
  '' +
  rightArrow.outerHTML + ''
  '
';

  addModalContent(marker);

  marker.bindPopup(popupContent, {
    closeButton: false,
    minWidth: 320
  });
}

function createClusterGroup(data) {
  var clusterGroup = new L.MarkerClusterGroup();
  data.eachLayer(function(layer) {
    clusterGroup.addLayer(layer);
  })
  return clusterGroup;
}

function createAllSchoolsMarkerList(data) {
  data.eachLayer(function(layer) {
    var school = markerList.appendChild(document.createElement('a'));
    school.setAttribute('class', 'col6 button quiet');
    school.innerHTML = layer.toGeoJSON().properties.name;
    school.onclick = function() {
     map.setView(layer.getLatLng(), 22);
     layer.openPopup();
   };
 });
}

//Search toggle
searchToggle.onclick = function(e) {
  $("#filters").hide()
  $("#markers-list").hide();
  $("#filtered-list").hide();
  $("#search-option").show();
}

//Marker list toggle
allSchoolsToggle.onclick = function(e) {
  startLoading();
  setTimeout(function() {
    loadAllSchools(rawData);
  }, 500);
}

//Filters toggle
filtersToggle.onclick = function(e) {
  map.removeLayer(clusterGroup);
  $("#markers-list").hide();
  $("#search-option").hide();
  $("#filters").show();
  typesList.innerHTML = '';
  interestAreasList.innerHTML = '';
  filtersLayer = L.mapbox.featureLayer(rawData);
  var typesArr = createFilterList(filtersLayer, 'type');
  var programsArr = createFilterList(filtersLayer, 'interest_area');

  displayFilterList(typesList, typesArr, 'type');
  displayFilterList(interestAreasList, programsArr, 'interest_area');
}

//Filtering methods
function createFilterList(data, field) {
  var filterItems = [], filterItemObj = {};
  data.eachLayer(function(marker) {
    if (field === "type") {
      var feature = marker.feature
      filterItemObj[feature.properties[field]] = true;
    } else if (field === "interest_area") {
      var programsList = marker.feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        filterItemObj[programsList[i][field]] = true;
      }
    }
  })
  for (var k in filterItemObj) filterItems.push(k);
    return filterItems;
}

function displayFilterList(pageElement, array, field) {
  if (typesList.innerHTML == '' || interestAreasList.innerHTML == '') {
    for (var i = 0; i < array.length; i++) {
      // Create an an input checkbox and label inside.
      var listItem = pageElement.appendChild(document.createElement('a'));
      listItem.setAttribute('class', 'col4 button quiet');

      var checkbox = listItem.appendChild(document.createElement('input'));
      var label = listItem.appendChild(document.createElement('label'));
      checkbox.type = 'checkbox';
      checkbox.id = array[i];
      checkbox.checked = false;
      checkbox.name = field;
      label.innerHTML = array[i];
      label.setAttribute('for', array[i]);
      checkboxes.push(checkbox);
    }
  }
}

var filters = document.getElementById("filters");
filters.onchange = changeMap;

function changeMap() {
  var enabled = {};
  var namesOfChecked = {};
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      enabled[checkboxes[i].id] = true;
      namesOfChecked[checkboxes[i].name] = true;
    }
  }
  console.log(namesOfChecked);

  featureLayer = L.mapbox.featureLayer(rawData);

  featureLayer.setFilter(function(feature) {
    if ("type" in namesOfChecked && "interest_area" in namesOfChecked) {
      var programsList = feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        if (programsList[i]['interest_area'] in enabled && feature.properties['type'] in enabled) {
          return true;
        }
      }
    } else if ("type" in namesOfChecked) {
      return (feature.properties["type"] in enabled);
    } else if ("interest_area" in namesOfChecked) {
      var programsList = feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        if (programsList[i]['interest_area'] in enabled) {
          return true;
        }
      }
    }
  });

  map.removeLayer(clusterGroup);
  clusterGroup = createClusterGroup(featureLayer)

  map.addLayer(clusterGroup).setView([40.75, -74.09], 11);

  clusterGroup.eachLayer(function(marker) {
    addMarkerContent(marker)
    var feature = marker.feature
    filterItemObj[feature.properties['type']] = true;
  })
  createMarkerList(featureLayer)
}

function createMarkerList(data) {
  var filteredListSection = document.getElementById('filtered-list');
  filteredListSection.innerHTML = '';
  data.eachLayer(function(layer) {
    var school = filteredListSection.appendChild(document.createElement('a'));
    school.setAttribute('class', 'col4 quiet button');
    school.innerHTML = layer.toGeoJSON().properties.name;
    school.onclick = function() {
     map.setView(layer.getLatLng(), 22);
     layer.openPopup();
   };
 });
  $(filteredListSection).show()
}

//Find user's location
var geolocate = document.getElementById('geolocate');
var userLocationLayer = L.mapbox.featureLayer().addTo(map);
if (!navigator.geolocation) {
  geolocate.innerHTML = 'Geolocation is not available';
} else {
  geolocate.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();
    map.locate();
  };
}

// Once we've got a position, zoom and center the map
// on it, and add a single marker.
map.on('locationfound', function(e) {
  map.fitBounds(e.bounds);
  userLocationLayer.setGeoJSON({
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [e.latlng.lng, e.latlng.lat]
    },
    properties: {
      'marker-color': '#ff8888',
      'marker-symbol': 'star'
    }
  });
});

// If the user chooses not to allow their location
// to be shared, display an error message.
map.on('locationerror', function() {
  geolocate.innerHTML = 'Position could not be found';
});

<commit_msg>Add search keyup method to sidebar-filter.js file<commit_after>//Variables for items on menu
var toggleBar = document.getElementById('toggleBar');
var allSchoolsToggle = document.getElementById('listToggle');
var filtersToggle = document.getElementById('filtersToggle');
var searchToggle = document.getElementById('searchToggle');

var markerList = document.getElementById('markers-list')
var typesList = document.getElementById('types-list');
var interestAreasList = document.getElementById('interest-areas-list');
var clusterGroup, featureLayer;
var filterItemObj = {}, checkboxes=[];
var rawData;

//Place all school markers on map at load
$.ajax({
  dataType: 'json',
  url: '/',
  type: 'GET'
}).success(function(data){
  rawData = data;
  loadAllSchools(data);
});

//Function that places all schools on map
function loadAllSchools(data) {
  $("#search-option").hide();
  $("#filters").hide();
  $("#markers-list").show();
  featureLayer = L.mapbox.featureLayer(data)
  clusterGroup = createClusterGroup(featureLayer)
  map.addLayer(clusterGroup);
  clusterGroup.eachLayer(function(marker) {
    addMarkerContent(marker);
  })
  createAllSchoolsMarkerList(featureLayer);
  finishedLoading();
}

//search keyup callback
$("#search_text").keyup(function(event) {
  $.get('/search?search='+ $(this).val());
});

//Displaying of markers methods
function addMarkerContent(marker) {
  var rightArrow = document.createElement("img")
  rightArrow.src = "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-arrow-right-128.png";
  rightArrow.alt="Right Arrow";
  rightArrow.id="right-arrow";
  rightArrow.className= "right-arrow";

  rightArrow.addEventListener('click',function(){openModal(properties)});

  var properties = marker.feature.properties;
  popupContent =
  '
' +
  '
' +
  // '

' +
  '
' +
  '
' +
  '
' + properties.name + '
' +
  '
' + properties.address + ', ' + properties.zip + '
' +
  '
' +
  '' +
  rightArrow.outerHTML + ''
  '
';

  addModalContent(marker);

  marker.bindPopup(popupContent, {
    closeButton: false,
    minWidth: 320
  });
}

function createClusterGroup(data) {
  var clusterGroup = new L.MarkerClusterGroup();
  data.eachLayer(function(layer) {
    clusterGroup.addLayer(layer);
  })
  return clusterGroup;
}

function createAllSchoolsMarkerList(data) {
  data.eachLayer(function(layer) {
    var school = markerList.appendChild(document.createElement('a'));
    school.setAttribute('class', 'col6 button quiet');
    school.innerHTML = layer.toGeoJSON().properties.name;
    school.onclick = function() {
     map.setView(layer.getLatLng(), 22);
     layer.openPopup();
   };
 });
}

//Search toggle
searchToggle.onclick = function(e) {
  $("#filters").hide()
  $("#markers-list").hide();
  $("#filtered-list").hide();
  $("#search-option").show();
}

//Marker list toggle
allSchoolsToggle.onclick = function(e) {
  startLoading();
  setTimeout(function() {
    loadAllSchools(rawData);
  }, 500);
}

//Filters toggle
filtersToggle.onclick = function(e) {
  map.removeLayer(clusterGroup);
  $("#markers-list").hide();
  $("#search-option").hide();
  $("#filters").show();
  typesList.innerHTML = '';
  interestAreasList.innerHTML = '';
  filtersLayer = L.mapbox.featureLayer(rawData);
  var typesArr = createFilterList(filtersLayer, 'type');
  var programsArr = createFilterList(filtersLayer, 'interest_area');

  displayFilterList(typesList, typesArr, 'type');
  displayFilterList(interestAreasList, programsArr, 'interest_area');
}

//Filtering methods
function createFilterList(data, field) {
  var filterItems = [], filterItemObj = {};
  data.eachLayer(function(marker) {
    if (field === "type") {
      var feature = marker.feature
      filterItemObj[feature.properties[field]] = true;
    } else if (field === "interest_area") {
      var programsList = marker.feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        filterItemObj[programsList[i][field]] = true;
      }
    }
  })
  for (var k in filterItemObj) filterItems.push(k);
    return filterItems;
}

function displayFilterList(pageElement, array, field) {
  if (typesList.innerHTML == '' || interestAreasList.innerHTML == '') {
    for (var i = 0; i < array.length; i++) {
      // Create an an input checkbox and label inside.
      var listItem = pageElement.appendChild(document.createElement('a'));
      listItem.setAttribute('class', 'col4 button quiet');

      var checkbox = listItem.appendChild(document.createElement('input'));
      var label = listItem.appendChild(document.createElement('label'));
      checkbox.type = 'checkbox';
      checkbox.id = array[i];
      checkbox.checked = false;
      checkbox.name = field;
      label.innerHTML = array[i];
      label.setAttribute('for', array[i]);
      checkboxes.push(checkbox);
    }
  }
}

var filters = document.getElementById("filters");
filters.onchange = changeMap;

function changeMap() {
  var enabled = {};
  var namesOfChecked = {};
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      enabled[checkboxes[i].id] = true;
      namesOfChecked[checkboxes[i].name] = true;
    }
  }
  console.log(namesOfChecked);

  featureLayer = L.mapbox.featureLayer(rawData);

  featureLayer.setFilter(function(feature) {
    if ("type" in namesOfChecked && "interest_area" in namesOfChecked) {
      var programsList = feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        if (programsList[i]['interest_area'] in enabled && feature.properties['type'] in enabled) {
          return true;
        }
      }
    } else if ("type" in namesOfChecked) {
      return (feature.properties["type"] in enabled);
    } else if ("interest_area" in namesOfChecked) {
      var programsList = feature.properties.programs
      for (i=0; i<programsList.length; i++) {
        if (programsList[i]['interest_area'] in enabled) {
          return true;
        }
      }
    }
  });

  map.removeLayer(clusterGroup);
  clusterGroup = createClusterGroup(featureLayer)

  map.addLayer(clusterGroup).setView([40.75, -74.09], 11);

  clusterGroup.eachLayer(function(marker) {
    addMarkerContent(marker)
    var feature = marker.feature
    filterItemObj[feature.properties['type']] = true;
  })
  createMarkerList(featureLayer)
}

function createMarkerList(data) {
  var filteredListSection = document.getElementById('filtered-list');
  filteredListSection.innerHTML = '';
  data.eachLayer(function(layer) {
    var school = filteredListSection.appendChild(document.createElement('a'));
    school.setAttribute('class', 'col4 quiet button');
    school.innerHTML = layer.toGeoJSON().properties.name;
    school.onclick = function() {
     map.setView(layer.getLatLng(), 22);
     layer.openPopup();
   };
 });
  $(filteredListSection).show()
}

//Find user's location
var geolocate = document.getElementById('geolocate');
var userLocationLayer = L.mapbox.featureLayer().addTo(map);
if (!navigator.geolocation) {
  geolocate.innerHTML = 'Geolocation is not available';
} else {
  geolocate.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();
    map.locate();
  };
}

// Once we've got a position, zoom and center the map
// on it, and add a single marker.
map.on('locationfound', function(e) {
  map.fitBounds(e.bounds);
  userLocationLayer.setGeoJSON({
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [e.latlng.lng, e.latlng.lat]
    },
    properties: {
      'marker-color': '#ff8888',
      'marker-symbol': 'star'
    }
  });
});

// If the user chooses not to allow their location
// to be shared, display an error message.
map.on('locationerror', function() {
  geolocate.innerHTML = 'Position could not be found';
});

<|endoftext|>