<commit_before>window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

String.prototype.default = function(value) {
	return this == "" ? value : this;
}

String.prototype.escape = function() {
	return this.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
};

String.prototype.isNumeric = function() {
	return !isNaN(parseFloat(this)) && isFinite(this);
};

String.prototype.list = function() {
	if (delimiter == undefined) delimiter = ",";
	if (this.trim() == "") return [];
	return this.split(delimiter).map(function(item) {
		return item.trim();
	});
};

HTMLElement.prototype.insertAfter = function(element, target) {
	this.insertBefore(element, target.nextSibling);
};

HTMLElement.prototype.closest = function(selector) {
	var elements = Array.prototype.slice.call(document.querySelectorAll(selector));
	var element = this;
	while (element != null && elements.indexOf(element) < 0)
		element = element.parentElement;
	return element;
};

HTMLElement.prototype.index = function() {
	return Array.prototype.slice.call(this.parentElement.children).indexOf(this);
};

String.prototype.repeat = function(count) {
	return new Array(count + 1).join(this);
};

Number.prototype.format = function(length) {
	var value = this.toString();
	return ("0".repeat(Math.max(0, length - value.length)) + value).substr(-length);
};

Date.ISO = "YYYY-MM-DDTHH:mm:ssZ";

Date.prototype.format = function(format, utc) {
	if (utc == null) utc = format[format.length - 1] == "Z";
	var regex = /[YMDHhms]{1,4}/g;
	var time = format;
	while (match = regex.exec(format)) {
		var match = match[0],
		type = match[0];
		time = time.replace(match, (
			type == "Y" ? (utc ? this.getUTCFullYear() : this.getFullYear()) :
			type == "M" ? (utc ? this.getUTCMonth() : this.getMonth()) :
			type == "D" ? (utc ? this.getUTCDate() : this.getDate()) :
			type == "H" ? (utc ? this.getUTCHours() : this.getHours()) :
			type == "h" ? ((utc ? this.getUTCHours() : this.getHours()) - 1) % 12 + 1 :
			type == "m" ? (utc ? this.getUTCMinutes() : this.getMinutes()) :
			type == "s" ? (utc ? this.getUTCSeconds() : this.getSeconds()) :
			"").format(match.length));
	}
	return time;
};

if (!Array.prototype.findIndex) {
	Array.prototype.findIndex = function(callback, scope) {
		for (var i = this.length - 1; i >= 0; i--) {
			if (i in this && callback.call(scope, this[i], i, this)) {
				return i;
			}
		}
		return -1;
	};
}

(function() {
	var markdown = (function() {
		var parse = function(markdown) {
			var html = "";
			var debug = markdown[0] == "T";
			var matches = (markdown.replace(/\t/g, "    ") + "\n\n").match(/(.*\n)+?\n+/g);
			for (var i = 0; i < matches.length; i++) {
				var block = matches[i];
				if (block[0] === ">") {
					html += "
" + parse(block.replace(
						/^(?:>|\s)?\s?/gm, "")) + "
";
				} else if (match = /^(#{1,5})\s+(.*)\n/.exec(block)) {
					var tag = "h" + (match[1].length + 1);
					html += "<" + tag + ">" + inline(match[2]) + "</" + tag + ">";
				} else if (block.match(/^\s{4}/)) {
					html += "" + block.trim()
						.replace(/^\s{4}/gm, "").escape() + "";
				} else if (match = /^\s?(\*|\+|\-|\d+\.)\s/.exec(block)) {
					var tag, regex = match[0][0] === " " ? "\\s" : "";
					if (match[1][0].isNumeric()) {
						tag = "ol";
						regex += "\\d+\\.";
					} else {
						tag = "ul";
						regex += "[\\*\\+\\-]";
					};
					if (match[0][match[0].length - 1] === " ")
						regex += "\\s";
					html += "<" + tag + ">";
					var regexp = new RegExp(regex + "(.*\\n)+?(?=" + regex + "|$)", "g");
					while (item = regexp.exec(block)) {
						html += "
";
						if (match = new RegExp("^" + regex + "\\s*(.*?)\\n?\\s*$").exec(item[0])) {
							html += inline(match[1]);
						} else {
							var match = new RegExp("^"
								+ regex, "g").exec(item);
							html += parse(item[0].replace(
								new RegExp("^(?:" + regex
									+ "|\\s{0," + match[0].length + "})", "gm"), ""));
						};
						html += "
";
					};
					html += "</" + tag + ">";
				} else {
					html += "
" + inline(block) + "
";
				};
			};
			return html;
		},
		inline = function(markdown) {
			return markdown.trim().escape()
				.replace(/\s{2,}$/gm, "
")
				.replace(/(?:\*|\_){2}((?:.|\n)*?)(?:\*|\_){2}/g, "$1")
				.replace(/(?:\*|\_)((?:.|\n)*?)(?:\*|\_)/g, "$1")
				.replace(/`((?:.|\n)*?)`/g, "$1")
				.replace(/\!\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
					"")
				.replace(/\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
					"$1");
		};
		return parse;
	})();
	var app = function(db) {
		var aside = document.querySelector("aside"),
		note = document.querySelector("#note"),
		main = document.querySelector("main"),
		source = document.querySelector("#source textarea"),
		preview = document.querySelector("#preview"),
		title = document.querySelector("header input"),
		hover = 0, item, store = [], saving = false,
		display = function(note) {
			var index = Math.max(store.findIndex(function(time) {
				return time < note.time;
			}), 0);
			store.splice(index, 0, note.time);
			var element = document.createElement("article");
			var title = document.createElement("h1");
			title.innerHTML = note.title.escape();
			element.appendChild(title);
			var time = document.createElement("time");
			var date = new Date(note.time);
			time.setAttribute("datetime", date.format(Date.ISO));
			time.innerHTML = date.format("HH:mm DD/MM/YYYY");
			element.appendChild(time);
			aside.insertAfter(element, aside.children[index]);
		},
		fetch = function() {
			var update = {
				title: title.value.trim().default(title.placeholder),
				content: source.value,
				tags: []
			};
			if (item != null) update.id = item.id;
			return update;
		},
		inputs = function() {
			title.readOnly = window.innerWidth < 800 && !main.classList.contains("edit");
		},
		scroll = (function() {
			var ignore = false;
			return function(from, to) {
				ignore = !ignore;
				if (ignore) {
					to.scrollTop = from.scrollTop *
						(to.scrollHeight - to.clientHeight) /
						(from.scrollHeight - from.clientHeight);
				}
			};
		})();
		this.find = function(args, callback) {
			if (callback == undefined) {
				callback = args;
				args = null; }
			var list = [];
			var keys = args == null ? [] : Object.keys(args);
			db.transaction("notes").objectStore("notes").openCursor().onsuccess = function() {
				var cursor = event.target.result;
				if (cursor) {
					var item = cursor.value;
					keys.every(function(key) {
						return args[key] == item[key];
					}) && list.push(item);
					cursor.continue();
				} else callback.call(null, list);
			};
		};
		this.get = function(item, callback) {
			db.transaction("notes").objectStore("notes").get(item).onsuccess = function(event) {
				callback.call(null, event.target.result);
			};
		};
		this.add = function(item, callback) {
			item.time = item.time || new Date().getTime();
			item.id = item.id || item.time;
			db.transaction("notes", "readwrite").objectStore("notes").add(item).onsuccess = function() {
				display(item);
				if (callback != undefined) callback.call(null, item);
			};
		};
		this.remove = function(item, callback) {
			aside.children[store.indexOf(item) + 1].remove();
			store.splice(store.indexOf(item), 1);
			db.transaction("notes", "readwrite").objectStore("notes").delete(item).onsuccess = function() {
				if (callback != undefined) callback.call(null);
			};
		};
		this.update = function(item, update, callback) {
			this.remove(item, function() {
				this.add(update, callback);
			}.bind(this));
		};
		this.new = function() {
			item = null;
			title.value = "";
			source.value = "";
			preview.innerHTML = "";
			main.classList.add("edit");
			document.body.classList.add("open");
			note.innerHTML = "";
		};
		this.open = function(id) {
			this.get(id, function(note) {
				item = note;
				title.value = item.title;
				source.value = item.content;
				preview.innerHTML = markdown(item.content);
				document.body.classList.add("open");
				note.innerHTML = "";
			});
		};
		this.save = function(callback) {
			if (!saving) {
				saving = true;
				var complete = function(update) {
					item = update;
					saving = false;
					if (callback != undefined) callback.call(null, update);
				}.bind(this);
				if (item == null) {
					this.add(fetch(), complete);
				} else {
					this.update(item.time, fetch(), complete);
				}
			}
		};
		this.close = function() {
			main.classList.remove("edit");
			document.body.classList.remove("open");
		};
		aside.addEventListener("click", function(event) {
			if (event.target.nodeName == "H2")
				this.new();
			else if (element = event.target.closest("aside > *"))
				this.open(store[element.index() - 1]);
		}.bind(this));
		aside.addEventListener("mouseover", function(event) {
			if (event.target.nodeName == "H2") {
				hover = 0;
				note.innerHTML = "";
			} else if (element = event.target.closest("aside article")) {
				var index = element.index();
				if (index != hover) {
					hover = index;
					this.get(store[element.index() - 1], function(item) {
						note.innerHTML = "
" + item.title + "
" + markdown(item.content);
					});
				}
			}
		}.bind(this));
		source.addEventListener("keyup", function(event) {
			preview.innerHTML = markdown(source.value);
			scroll(source, preview);
			this.save();
		}.bind(this));
		title.addEventListener("keyup", function(event) {
			this.save();
		}.bind(this));
		source.addEventListener("scroll", function() {
			scroll(source, preview);
		});
		preview.addEventListener("scroll", function() {
			scroll(preview, source);
		});
		document.querySelector("#back").addEventListener("click", function() {
			this.close();
		}.bind(this));
		window.addEventListener("resize", inputs);
		/*
		document.querySelector("#switch-edit").addEventListener("click", function() {
			main.classList.add("edit");
		});
		document.querySelector("#switch-preview").addEventListener("click", function() {
			main.classList.remove("edit");
		});
		*/
		this.find(function(notes) {
			notes.forEach(display);
		});
	};
	var request = window.indexedDB.open("notes", 1);
	request.onupgradeneeded = function() {
		request.result.createObjectStore("notes", { keyPath: "time" });
	};
	request.onsuccess = function() {
		window.notes = new app(request.result);
	};
})();<commit_msg>Scroll to top when switching note preview<commit_after>window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;

String.prototype.default = function(value) {
	return this == "" ? value : this;
}

String.prototype.escape = function() {
	return this.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
};

String.prototype.isNumeric = function() {
	return !isNaN(parseFloat(this)) && isFinite(this);
};

String.prototype.list = function() {
	if (delimiter == undefined) delimiter = ",";
	if (this.trim() == "") return [];
	return this.split(delimiter).map(function(item) {
		return item.trim();
	});
};

HTMLElement.prototype.insertAfter = function(element, target) {
	this.insertBefore(element, target.nextSibling);
};

HTMLElement.prototype.closest = function(selector) {
	var elements = Array.prototype.slice.call(document.querySelectorAll(selector));
	var element = this;
	while (element != null && elements.indexOf(element) < 0)
		element = element.parentElement;
	return element;
};

HTMLElement.prototype.index = function() {
	return Array.prototype.slice.call(this.parentElement.children).indexOf(this);
};

String.prototype.repeat = function(count) {
	return new Array(count + 1).join(this);
};

Number.prototype.format = function(length) {
	var value = this.toString();
	return ("0".repeat(Math.max(0, length - value.length)) + value).substr(-length);
};

Date.ISO = "YYYY-MM-DDTHH:mm:ssZ";

Date.prototype.format = function(format, utc) {
	if (utc == null) utc = format[format.length - 1] == "Z";
	var regex = /[YMDHhms]{1,4}/g;
	var time = format;
	while (match = regex.exec(format)) {
		var match = match[0],
		type = match[0];
		time = time.replace(match, (
			type == "Y" ? (utc ? this.getUTCFullYear() : this.getFullYear()) :
			type == "M" ? (utc ? this.getUTCMonth() : this.getMonth()) :
			type == "D" ? (utc ? this.getUTCDate() : this.getDate()) :
			type == "H" ? (utc ? this.getUTCHours() : this.getHours()) :
			type == "h" ? ((utc ? this.getUTCHours() : this.getHours()) - 1) % 12 + 1 :
			type == "m" ? (utc ? this.getUTCMinutes() : this.getMinutes()) :
			type == "s" ? (utc ? this.getUTCSeconds() : this.getSeconds()) :
			"").format(match.length));
	}
	return time;
};

if (!Array.prototype.findIndex) {
	Array.prototype.findIndex = function(callback, scope) {
		for (var i = this.length - 1; i >= 0; i--) {
			if (i in this && callback.call(scope, this[i], i, this)) {
				return i;
			}
		}
		return -1;
	};
}

(function() {
	var markdown = (function() {
		var parse = function(markdown) {
			var html = "";
			var debug = markdown[0] == "T";
			var matches = (markdown.replace(/\t/g, "    ") + "\n\n").match(/(.*\n)+?\n+/g);
			for (var i = 0; i < matches.length; i++) {
				var block = matches[i];
				if (block[0] === ">") {
					html += "
" + parse(block.replace(
						/^(?:>|\s)?\s?/gm, "")) + "
";
				} else if (match = /^(#{1,5})\s+(.*)\n/.exec(block)) {
					var tag = "h" + (match[1].length + 1);
					html += "<" + tag + ">" + inline(match[2]) + "</" + tag + ">";
				} else if (block.match(/^\s{4}/)) {
					html += "" + block.trim()
						.replace(/^\s{4}/gm, "").escape() + "";
				} else if (match = /^\s?(\*|\+|\-|\d+\.)\s/.exec(block)) {
					var tag, regex = match[0][0] === " " ? "\\s" : "";
					if (match[1][0].isNumeric()) {
						tag = "ol";
						regex += "\\d+\\.";
					} else {
						tag = "ul";
						regex += "[\\*\\+\\-]";
					};
					if (match[0][match[0].length - 1] === " ")
						regex += "\\s";
					html += "<" + tag + ">";
					var regexp = new RegExp(regex + "(.*\\n)+?(?=" + regex + "|$)", "g");
					while (item = regexp.exec(block)) {
						html += "
";
						if (match = new RegExp("^" + regex + "\\s*(.*?)\\n?\\s*$").exec(item[0])) {
							html += inline(match[1]);
						} else {
							var match = new RegExp("^"
								+ regex, "g").exec(item);
							html += parse(item[0].replace(
								new RegExp("^(?:" + regex
									+ "|\\s{0," + match[0].length + "})", "gm"), ""));
						};
						html += "
";
					};
					html += "</" + tag + ">";
				} else {
					html += "
" + inline(block) + "
";
				};
			};
			return html;
		},
		inline = function(markdown) {
			return markdown.trim().escape()
				.replace(/\s{2,}$/gm, "
")
				.replace(/(?:\*|\_){2}((?:.|\n)*?)(?:\*|\_){2}/g, "$1")
				.replace(/(?:\*|\_)((?:.|\n)*?)(?:\*|\_)/g, "$1")
				.replace(/`((?:.|\n)*?)`/g, "$1")
				.replace(/\!\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
					"")
				.replace(/\[(.*?)\]\((.+?)(?:\s+"(.*?)")?\)/g,
					"$1");
		};
		return parse;
	})();
	var app = function(db) {
		var aside = document.querySelector("aside"),
		note = document.querySelector("#note"),
		main = document.querySelector("main"),
		source = document.querySelector("#source textarea"),
		preview = document.querySelector("#preview"),
		title = document.querySelector("header input"),
		hover = 0, item, store = [], saving = false,
		display = function(note) {
			var index = Math.max(store.findIndex(function(time) {
				return time < note.time;
			}), 0);
			store.splice(index, 0, note.time);
			var element = document.createElement("article");
			var title = document.createElement("h1");
			title.innerHTML = note.title.escape();
			element.appendChild(title);
			var time = document.createElement("time");
			var date = new Date(note.time);
			time.setAttribute("datetime", date.format(Date.ISO));
			time.innerHTML = date.format("HH:mm DD/MM/YYYY");
			element.appendChild(time);
			aside.insertAfter(element, aside.children[index]);
		},
		fetch = function() {
			var update = {
				title: title.value.trim().default(title.placeholder),
				content: source.value,
				tags: []
			};
			if (item != null) update.id = item.id;
			return update;
		},
		inputs = function() {
			title.readOnly = window.innerWidth < 800 && !main.classList.contains("edit");
		},
		scroll = (function() {
			var ignore = false;
			return function(from, to) {
				ignore = !ignore;
				if (ignore) {
					to.scrollTop = from.scrollTop *
						(to.scrollHeight - to.clientHeight) /
						(from.scrollHeight - from.clientHeight);
				}
			};
		})();
		this.find = function(args, callback) {
			if (callback == undefined) {
				callback = args;
				args = null; }
			var list = [];
			var keys = args == null ? [] : Object.keys(args);
			db.transaction("notes").objectStore("notes").openCursor().onsuccess = function() {
				var cursor = event.target.result;
				if (cursor) {
					var item = cursor.value;
					keys.every(function(key) {
						return args[key] == item[key];
					}) && list.push(item);
					cursor.continue();
				} else callback.call(null, list);
			};
		};
		this.get = function(item, callback) {
			db.transaction("notes").objectStore("notes").get(item).onsuccess = function(event) {
				callback.call(null, event.target.result);
			};
		};
		this.add = function(item, callback) {
			item.time = item.time || new Date().getTime();
			item.id = item.id || item.time;
			db.transaction("notes", "readwrite").objectStore("notes").add(item).onsuccess = function() {
				display(item);
				if (callback != undefined) callback.call(null, item);
			};
		};
		this.remove = function(item, callback) {
			aside.children[store.indexOf(item) + 1].remove();
			store.splice(store.indexOf(item), 1);
			db.transaction("notes", "readwrite").objectStore("notes").delete(item).onsuccess = function() {
				if (callback != undefined) callback.call(null);
			};
		};
		this.update = function(item, update, callback) {
			this.remove(item, function() {
				this.add(update, callback);
			}.bind(this));
		};
		this.new = function() {
			item = null;
			title.value = "";
			source.value = "";
			preview.innerHTML = "";
			main.classList.add("edit");
			document.body.classList.add("open");
			note.innerHTML = "";
		};
		this.open = function(id) {
			this.get(id, function(note) {
				item = note;
				title.value = item.title;
				source.value = item.content;
				preview.innerHTML = markdown(item.content);
				document.body.classList.add("open");
				note.innerHTML = "";
			});
		};
		this.save = function(callback) {
			if (!saving) {
				saving = true;
				var complete = function(update) {
					item = update;
					saving = false;
					if (callback != undefined) callback.call(null, update);
				}.bind(this);
				if (item == null) {
					this.add(fetch(), complete);
				} else {
					this.update(item.time, fetch(), complete);
				}
			}
		};
		this.close = function() {
			main.classList.remove("edit");
			document.body.classList.remove("open");
		};
		aside.addEventListener("click", function(event) {
			if (event.target.nodeName == "H2")
				this.new();
			else if (element = event.target.closest("aside > *"))
				this.open(store[element.index() - 1]);
		}.bind(this));
		aside.addEventListener("mouseover", function(event) {
			if (event.target.nodeName == "H2") {
				hover = 0;
				note.innerHTML = "";
			} else if (element = event.target.closest("aside article")) {
				var index = element.index();
				if (index != hover) {
					hover = index;
					this.get(store[element.index() - 1], function(item) {
						note.scrollTop = 0;
						note.innerHTML = "
" + item.title + "
" + markdown(item.content);
					});
				}
			}
		}.bind(this));
		source.addEventListener("keyup", function(event) {
			preview.innerHTML = markdown(source.value);
			scroll(source, preview);
			this.save();
		}.bind(this));
		title.addEventListener("keyup", function(event) {
			this.save();
		}.bind(this));
		source.addEventListener("scroll", function() {
			scroll(source, preview);
		});
		preview.addEventListener("scroll", function() {
			scroll(preview, source);
		});
		document.querySelector("#back").addEventListener("click", function() {
			this.close();
		}.bind(this));
		window.addEventListener("resize", inputs);
		/*
		document.querySelector("#switch-edit").addEventListener("click", function() {
			main.classList.add("edit");
		});
		document.querySelector("#switch-preview").addEventListener("click", function() {
			main.classList.remove("edit");
		});
		*/
		this.find(function(notes) {
			notes.forEach(display);
		});
	};
	var request = window.indexedDB.open("notes", 1);
	request.onupgradeneeded = function() {
		request.result.createObjectStore("notes", { keyPath: "time" });
	};
	request.onsuccess = function() {
		window.notes = new app(request.result);
	};
})();<|endoftext|>


<commit_before>// Init background image
$.backstretch(["img/bg.jpg"]);

// To the global namespace just for now
var theme = new Soundgun("sounds/theme.ogg");

$(function () {

    // Music & Sounds
    var hit = new Soundgun("sounds/hit.ogg");
    var gameover = new Soundgun("sounds/gameover.ogg");
    theme.setVolume(0);
    theme.play();
    theme.fadeIn(70, 0.5);
    theme.loop();

    // Text
    var score = new Textgun("#score");
    score.useTransition(1);
    score.setValue('0');
    var time = new Textgun("#time");

    engine = new PongEngine();
    engine.startEngine();

    // Start timer
    var timer = new Timer();
    timer.start();
    var timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
            engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            // for now, move paddle 10 times right
            for(var i =  0; i < 10; i++) {
                engine.paddle.movePaddleRight();
            }
        },
        leftPressed = function() {
            for(var i = 0; i < 10; i++) {
                engine.paddle.movePaddleLeft();
            }
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        var isArrowkey = function(keycode) {
            return keycode >= 37 && keycode <= 40;
        },
            forwardKeyPress = true;

        if (!isArrowkey(e.keyCode)) {
            forwardKeyPress = true;
        }  else {
            try {
                keyHandlers[e.keyCode]();
            } catch(e) {
                // Do nothing
            }
            forwardKeyPress = false;
        }
        return forwardKeyPress;
    });

    // Bind all game events. Game engine triggers them to canvas
    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
        hit.play();
        score.setValue(Number(score.getValue()) + 150);
    });
    $('#main-canvas').bind('gameOver', function() {
        gameover.play();
        theme.fadeOut();
        engine.stopEngine();
        timer.stop();
        time.setValue(timer.getFormattedTime(timer.getFinalTime()));
        clearInterval(timeInterval);
        console.log(timer.getFormattedTime(timer.getFinalTime()));

        // Display the nameModal
        $('#nameModal').fadeIn();

    });

    // When user submits scoreform
    $('#yes-button').click(function(){
        var nick = $('#nick').val();
        var dataString = 'nick=' + nick + '&time=' + timer.getFormattedTime(timer.getFinalTime()) + '&score=' + score.getValue();
        $.ajax({
            type: 'POST',
            url: 'commit.php',
            data: dataString,
            success: function(data) {
                alert("Wrote to database ;)"); // testing
                loadHighscore();
            }
        });
        $('#nameModal').fadeOut();
    });

    // When user restarts game
    $('#no-button').click(function(){
        $('#nameModal').fadeOut();
        window.location.reload();
        // TODO
    });

});
<commit_msg>changed form click to submit<commit_after>// Init background image
$.backstretch(["img/bg.jpg"]);

// To the global namespace just for now
var theme = new Soundgun("sounds/theme.ogg");

$(function () {

    // Music & Sounds
    var hit = new Soundgun("sounds/hit.ogg");
    var gameover = new Soundgun("sounds/gameover.ogg");
    theme.setVolume(0);
    theme.play();
    theme.fadeIn(70, 0.5);
    theme.loop();

    // Text
    var score = new Textgun("#score");
    score.useTransition(1);
    score.setValue('0');
    var time = new Textgun("#time");

    engine = new PongEngine();
    engine.startEngine();

    // Start timer
    var timer = new Timer();
    timer.start();
    var timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
            engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            // for now, move paddle 10 times right
            for(var i =  0; i < 10; i++) {
                engine.paddle.movePaddleRight();
            }
        },
        leftPressed = function() {
            for(var i = 0; i < 10; i++) {
                engine.paddle.movePaddleLeft();
            }
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        var isArrowkey = function(keycode) {
            return keycode >= 37 && keycode <= 40;
        },
            forwardKeyPress = true;

        if (!isArrowkey(e.keyCode)) {
            forwardKeyPress = true;
        }  else {
            try {
                keyHandlers[e.keyCode]();
            } catch(e) {
                // Do nothing
            }
            forwardKeyPress = false;
        }
        return forwardKeyPress;
    });

    // Bind all game events. Game engine triggers them to canvas
    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
        hit.play();
        score.setValue(Number(score.getValue()) + 150);
    });
    $('#main-canvas').bind('gameOver', function() {
        gameover.play();
        theme.fadeOut();
        engine.stopEngine();
        timer.stop();
        time.setValue(timer.getFormattedTime(timer.getFinalTime()));
        clearInterval(timeInterval);
        console.log(timer.getFormattedTime(timer.getFinalTime()));

        // Display the nameModal
        $('#nameModal').fadeIn();

    });

    // When user submits scoreform
    $('#scoreform').submit(function(){
        var nick = $('#nick').val();
        var dataString = 'nick=' + nick + '&time=' + timer.getFormattedTime(timer.getFinalTime()) + '&score=' + score.getValue();
        $.ajax({
            type: 'POST',
            url: 'commit.php',
            data: dataString,
            success: function(data) {
                alert("Wrote to database ;)"); // testing
                loadHighscore();
            }
        });
        $('#nameModal').fadeOut();
    });

    // When user restarts game
    $('#no-button').click(function(){
        $('#nameModal').fadeOut();
        window.location.reload();
        // TODO
    });

});
<|endoftext|>


<commit_before>$(function(){

    /* ---- particles.js config ---- */

    particlesJS("particles-after-filter", {
        "particles": {
            "number": {
                "value": 22,
                "density": {
                    "enable": true,
                    "value_area": 800
                }
            },
            "color": {
                "value": "#ffffff"
            },
            "shape": {
                "type": "circle",
                "stroke": {
                    "width": 0,
                    "color": "#000000"
                },
                "polygon": {
                    "nb_sides": 5
                },
                "image": {
                    "src": "img/github.svg",
                    "width": 100,
                    "height": 100
                }
            },
            "opacity": {
                "value": 0.5,
                "random": false,
                "anim": {
                    "enable": false,
                    "speed": 1,
                    "opacity_min": 0.1,
                    "sync": false
                }
            },
            "size": {
                "value": 8,
                "random": true,
                "anim": {
                    "enable": false,
                    "speed": 40,
                    "size_min": 0.1,
                    "sync": false
                }
            },
            "line_linked": {
                "enable": false,
                "distance": 150,
                "color": "#ffffff",
                "opacity": 0.4,
                "width": 1
            },
            "move": {
                "enable": true,
                "speed": 4,
                "direction": "top-right",
                "random": true,
                "straight": false,
                "out_mode": "out",
                "bounce": false,
                "attract": {
                    "enable": false,
                    "rotateX": 600,
                    "rotateY": 1200
                }
            }
        },
        "interactivity": {
            "detect_on": "canvas",
            "events": {
                "onhover": {
                    "enable": true,
                    "mode": "grab"
                },
                "onclick": {
                    "enable": false,
                    "mode": "push"
                },
                "resize": true
            },
            "modes": {
                "grab": {
                    "distance": 119.88011988011988,
                    "line_linked": {
                        "opacity": 0.2509491544632522
                    }
                },
                "bubble": {
                    "distance": 292.34779642848423,
                    "size": 5,
                    "duration": 1.3805312609122866,
                    "opacity": 0.4,
                    "speed": 3
                },
                "repulse": {
                    "distance": 200,
                    "duration": 0.4
                },
                "push": {
                    "particles_nb": 4
                },
                "remove": {
                    "particles_nb": 2
                }
            }
        },
        "retina_detect": true
    });

    particlesJS("particles", {
        "particles": {
            "number": {
                "value": 65,
                "density": {
                    "enable": true,
                    "value_area": 800
                }
            },
            "color": {
                "value": "#ffffff"
            },
            "shape": {
                "type": "circle",
                "stroke": {
                    "width": 0,
                    "color": "#000000"
                },
                "polygon": {
                    "nb_sides": 5
                },
                "image": {
                    "src": "img/github.svg",
                    "width": 100,
                    "height": 100
                }
            },
            "opacity": {
                "value": 0.5,
                "random": false,
                "anim": {
                    "enable": false,
                    "speed": 1,
                    "opacity_min": 0.1,
                    "sync": false
                }
            },
            "size": {
                "value": 4,
                "random": true,
                "anim": {
                    "enable": false,
                    "speed": 40,
                    "size_min": 0.1,
                    "sync": false
                }
            },
            "line_linked": {
                "enable": false,
                "distance": 150,
                "color": "#ffffff",
                "opacity": 0.4,
                "width": 1
            },
            "move": {
                "enable": true,
                "speed": 4,
                "direction": "top-right",
                "random": true,
                "straight": false,
                "out_mode": "out",
                "bounce": false,
                "attract": {
                    "enable": false,
                    "rotateX": 600,
                    "rotateY": 1200
                }
            }
        },
        "interactivity": {
            "detect_on": "canvas",
            "events": {
                "onhover": {
                    "enable": true,
                    "mode": "grab"
                },
                "onclick": {
                    "enable": false,
                    "mode": "push"
                },
                "resize": true
            },
            "modes": {
                "grab": {
                    "distance": 119.88011988011988,
                    "line_linked": {
                        "opacity": 0.2509491544632522
                    }
                },
                "bubble": {
                    "distance": 292.34779642848423,
                    "size": 5,
                    "duration": 1.3805312609122866,
                    "opacity": 0.4,
                    "speed": 3
                },
                "repulse": {
                    "distance": 200,
                    "duration": 0.4
                },
                "push": {
                    "particles_nb": 4
                },
                "remove": {
                    "particles_nb": 2
                }
            }
        },
        "retina_detect": true
    });

    // 签名
    console.log('%c\n'+
                '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@*.@.     @@@@@@@@@@@@@@@@@@@@@@@@@@@@**@@@@@@@*@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@.  @@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@  @@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@*   .@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@@@@@@ *@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@      .*@@@@@@@* .*   *@@@*  @. .@@.    @  .    @. .@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@*.      .*@@@  .@@@ .@@@   @@@   *@@@  @**@@@  @@*@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@@@@*.     @.  @@@@@@@@.  *@@@@   @@*  @@@@@@  *@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@ .@@@@@@*   .   *@@@@@@@.  @@@@@  .@@*  @*@@@@  .@*@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@*    .@@@@@   @*   .***  @@   @@@  *@@@*    *@@@    .@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@*     *. .@@@@@*.   .*@@@@. .@.*@@@@@@ .*@@@@@..*@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n',
                'color:#ff3355');

    // 播放器
    setTimeout(function(){
        if($('#musicContainer').css('display') !== "none"){
            if(!$('#skPlayer').find('audio').length){
                skPlayer({
                    src:'http://o9vplcp9o.bkt.clouddn.com/Solitude.mp3',//音乐文件，必填
                    name:'Solitude',//歌曲名称，必填
                    author:'Re:plus',//歌手，必填
                    cover:'http://o9vplcp9o.bkt.clouddn.com/Solitude_cover.jpg',//专辑封面，必填
                    loop:true//是否单曲循环，选填
                });
            }
        }
    },7000);
    $('#musicSwitch').on('click',function(){
        $(this).hasClass('active')?$(this).removeClass('active'):$(this).addClass('active');
        if(!$('#skPlayer').find('audio').length){
            skPlayer({
                src:'http://o9vplcp9o.bkt.clouddn.com/Solitude.mp3',//音乐文件，必填
                name:'Solitude',//歌曲名称，必填
                author:'Re:plus',//歌手，必填
                cover:'http://o9vplcp9o.bkt.clouddn.com/Solitude_cover.jpg',//专辑封面，必填
                loop:true//是否单曲循环，选填
            });
        }
    });

    // 图片延迟加载
    $("img.lazy").unveil(1000);
    $('.post-listing').scroll(function(){
        $(window).trigger('scroll');
    });

    // 返回按钮
    $('a','.back-home').on('click',function(){
        if(window.history.length > 1){
            window.history.back();
        }else{
            window.location.href = 'http://www.chengfeilong.com';
        }
    });
});
<commit_msg>update music<commit_after>$(function(){

    /* ---- particles.js config ---- */

    particlesJS("particles-after-filter", {
        "particles": {
            "number": {
                "value": 22,
                "density": {
                    "enable": true,
                    "value_area": 800
                }
            },
            "color": {
                "value": "#ffffff"
            },
            "shape": {
                "type": "circle",
                "stroke": {
                    "width": 0,
                    "color": "#000000"
                },
                "polygon": {
                    "nb_sides": 5
                },
                "image": {
                    "src": "img/github.svg",
                    "width": 100,
                    "height": 100
                }
            },
            "opacity": {
                "value": 0.5,
                "random": false,
                "anim": {
                    "enable": false,
                    "speed": 1,
                    "opacity_min": 0.1,
                    "sync": false
                }
            },
            "size": {
                "value": 8,
                "random": true,
                "anim": {
                    "enable": false,
                    "speed": 40,
                    "size_min": 0.1,
                    "sync": false
                }
            },
            "line_linked": {
                "enable": false,
                "distance": 150,
                "color": "#ffffff",
                "opacity": 0.4,
                "width": 1
            },
            "move": {
                "enable": true,
                "speed": 4,
                "direction": "top-right",
                "random": true,
                "straight": false,
                "out_mode": "out",
                "bounce": false,
                "attract": {
                    "enable": false,
                    "rotateX": 600,
                    "rotateY": 1200
                }
            }
        },
        "interactivity": {
            "detect_on": "canvas",
            "events": {
                "onhover": {
                    "enable": true,
                    "mode": "grab"
                },
                "onclick": {
                    "enable": false,
                    "mode": "push"
                },
                "resize": true
            },
            "modes": {
                "grab": {
                    "distance": 119.88011988011988,
                    "line_linked": {
                        "opacity": 0.2509491544632522
                    }
                },
                "bubble": {
                    "distance": 292.34779642848423,
                    "size": 5,
                    "duration": 1.3805312609122866,
                    "opacity": 0.4,
                    "speed": 3
                },
                "repulse": {
                    "distance": 200,
                    "duration": 0.4
                },
                "push": {
                    "particles_nb": 4
                },
                "remove": {
                    "particles_nb": 2
                }
            }
        },
        "retina_detect": true
    });

    particlesJS("particles", {
        "particles": {
            "number": {
                "value": 65,
                "density": {
                    "enable": true,
                    "value_area": 800
                }
            },
            "color": {
                "value": "#ffffff"
            },
            "shape": {
                "type": "circle",
                "stroke": {
                    "width": 0,
                    "color": "#000000"
                },
                "polygon": {
                    "nb_sides": 5
                },
                "image": {
                    "src": "img/github.svg",
                    "width": 100,
                    "height": 100
                }
            },
            "opacity": {
                "value": 0.5,
                "random": false,
                "anim": {
                    "enable": false,
                    "speed": 1,
                    "opacity_min": 0.1,
                    "sync": false
                }
            },
            "size": {
                "value": 4,
                "random": true,
                "anim": {
                    "enable": false,
                    "speed": 40,
                    "size_min": 0.1,
                    "sync": false
                }
            },
            "line_linked": {
                "enable": false,
                "distance": 150,
                "color": "#ffffff",
                "opacity": 0.4,
                "width": 1
            },
            "move": {
                "enable": true,
                "speed": 4,
                "direction": "top-right",
                "random": true,
                "straight": false,
                "out_mode": "out",
                "bounce": false,
                "attract": {
                    "enable": false,
                    "rotateX": 600,
                    "rotateY": 1200
                }
            }
        },
        "interactivity": {
            "detect_on": "canvas",
            "events": {
                "onhover": {
                    "enable": true,
                    "mode": "grab"
                },
                "onclick": {
                    "enable": false,
                    "mode": "push"
                },
                "resize": true
            },
            "modes": {
                "grab": {
                    "distance": 119.88011988011988,
                    "line_linked": {
                        "opacity": 0.2509491544632522
                    }
                },
                "bubble": {
                    "distance": 292.34779642848423,
                    "size": 5,
                    "duration": 1.3805312609122866,
                    "opacity": 0.4,
                    "speed": 3
                },
                "repulse": {
                    "distance": 200,
                    "duration": 0.4
                },
                "push": {
                    "particles_nb": 4
                },
                "remove": {
                    "particles_nb": 2
                }
            }
        },
        "retina_detect": true
    });

    // 签名
    console.log('%c\n'+
                '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@*.@.     @@@@@@@@@@@@@@@@@@@@@@@@@@@@**@@@@@@@*@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@.  @@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@  @@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@*   .@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@@@@@@ *@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@      .*@@@@@@@* .*   *@@@*  @. .@@.    @  .    @. .@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@*.      .*@@@  .@@@ .@@@   @@@   *@@@  @**@@@  @@*@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@@@@*.     @.  @@@@@@@@.  *@@@@   @@*  @@@@@@  *@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@ .@@@@@@*   .   *@@@@@@@.  @@@@@  .@@*  @*@@@@  .@*@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@*    .@@@@@   @*   .***  @@   @@@  *@@@*    *@@@    .@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@*     *. .@@@@@*.   .*@@@@. .@.*@@@@@@ .*@@@@@..*@@@@@@@@@@@@@@\n'+
                '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n',
                'color:#ff3355');

    // 播放器
    setTimeout(function(){
        if($('#musicContainer').css('display') !== "none"){
            if(!$('#skPlayer').find('audio').length){
                skPlayer({
                    src:'http://o9vplcp9o.bkt.clouddn.com/CountingStars.mp3',//音乐文件，必填
                    name:'Counting Stars',//歌曲名称，必填
                    author:'OneRepublic',//歌手，必填
                    cover:'http://o9vplcp9o.bkt.clouddn.com/CountingStars_cover.jpg',//专辑封面，必填
                    loop:true//是否单曲循环，选填
                });
            }
        }
    },7000);
    $('#musicSwitch').on('click',function(){
        $(this).hasClass('active')?$(this).removeClass('active'):$(this).addClass('active');
        if(!$('#skPlayer').find('audio').length){
            skPlayer({
                src:'http://o9vplcp9o.bkt.clouddn.com/CountingStars.mp3',//音乐文件，必填
                name:'Counting Stars',//歌曲名称，必填
                author:'OneRepublic',//歌手，必填
                cover:'http://o9vplcp9o.bkt.clouddn.com/CountingStars_cover.jpg',//专辑封面，必填
                loop:true//是否单曲循环，选填
            });
        }
    });

    // 图片延迟加载
    $("img.lazy").unveil(1000);
    $('.post-listing').scroll(function(){
        $(window).trigger('scroll');
    });

    // 返回按钮
    $('a','.back-home').on('click',function(){
        if(window.history.length > 1){
            window.history.back();
        }else{
            window.location.href = 'http://www.chengfeilong.com';
        }
    });
});
<|endoftext|>


<commit_before>//Script for demonstrating BeamTrace2D.js

$(function() {
    //Basic drawing stuff
    var canvas = document.getElementById('beamCanvas');
    var ctx;
    if (canvas.getContext)
    {
        ctx = canvas.getContext('2d');
    }
    else
    {
        //Canvas not supported
        console.log("Error: canvas not supported");
    }

    //First init the walls
    var walls = new Array();
    walls.push(new BeamTrace2D.Wall([100,130],[120,220])); //Wall id 0
    walls.push(new BeamTrace2D.Wall([50,55],[220,60])); //Wall id 1
    walls.push(new BeamTrace2D.Wall([220,60],[250,220])); //Wall id 2...
    walls.push(new BeamTrace2D.Wall([50,220],[200,220])); //etc
    walls.push(new BeamTrace2D.Wall([50,220],[50,55]));
    walls.push(new BeamTrace2D.Wall([200,220],[40,230]));
    walls.push(new BeamTrace2D.Wall([40,230],[30,290]));
    walls.push(new BeamTrace2D.Wall([30,290],[60,270]));
    walls.push(new BeamTrace2D.Wall([60,270],[290,270]));
    walls.push(new BeamTrace2D.Wall([290,270],[250,220]));

    //Then a listener and a source
    var listener = new BeamTrace2D.Listener([80,100]);
    var source = new BeamTrace2D.Source([200,80]);

    //Pass the walls and the source to the solver, which does pre-calculations for fast solving
    var reflection_order = 4; //How many reflections do we want to calculate?
    var solver = new BeamTrace2D.Solver(walls,source,reflection_order); //Init the solver

    //**This is stupid, but my chrome works much faster if I do this again (?? some optimization thing ??)**
    solver = new BeamTrace2D.Solver(walls,source,reflection_order);
    //**

    //path_tree will contain the reflection paths according to: [ [[x,y,wall index],[x,y,wall index],[x,y,wall index],...],[path2],... ]
    var path_array = solver.getPaths(listener);

    //A function for painting the solution
    function redraw()
    {
        if(!ctx) return;
        ctx.clearRect(0,0,300,300);
        ctx.lineWidth = 2.0;
        walls.forEach(function(wall){
            wall.draw(ctx);
        });
        ctx.lineWidth = 1.0;
        listener.draw(ctx);
        source.draw(ctx);

        //Draw the paths
        if(path_array)
        {
            for(var i = 0; i < path_array.length; i++) //Go through all reflection paths
            {
                //Draw each path
                var first = true;
                ctx.strokeStyle = "rgba(0,0,255,0.2)";
                ctx.beginPath();
                ctx.lineWidth = 2;
                path_array[i].forEach(function(p){
                    if(first) { ctx.moveTo(p[0],p[1]); first = false; }
                    else { ctx.lineTo(p[0],p[1]); }
                });
                ctx.stroke();
                ctx.strokeStyle = "black";
                ctx.lineWidth = 1;
            }
        }
    }

    //If the walls or listener position are updated, the solver needs to be initialized again
    $('#beamCanvas').click(function(e) {
        source.p0 = [e.offsetX, e.offsetY]; //Change the source position
        solver = new BeamTrace2D.Solver(walls,source,reflection_order); //Init the solver with the new source position
        path_array = solver.getPaths(listener); //Update reflection paths
        redraw();
    });

    //Update the listener position
    $('#beamCanvas').mousemove(function(e) {
        listener.p0 = [e.offsetX, e.offsetY];
        path_array = solver.getPaths(listener); //Update reflection paths
        redraw();
    });

    redraw(); //First redraw
});<commit_msg>Fixed typo in main.js<commit_after>//Script for demonstrating BeamTrace2D.js

$(function() {
    //Basic drawing stuff
    var canvas = document.getElementById('beamCanvas');
    var ctx;
    if (canvas.getContext)
    {
        ctx = canvas.getContext('2d');
    }
    else
    {
        //Canvas not supported
        console.log("Error: canvas not supported");
    }

    //First init the walls
    var walls = new Array();
    walls.push(new BeamTrace2D.Wall([100,130],[120,220])); //Wall id 0
    walls.push(new BeamTrace2D.Wall([50,55],[220,60])); //Wall id 1
    walls.push(new BeamTrace2D.Wall([220,60],[250,220])); //Wall id 2...
    walls.push(new BeamTrace2D.Wall([50,220],[200,220])); //etc
    walls.push(new BeamTrace2D.Wall([50,220],[50,55]));
    walls.push(new BeamTrace2D.Wall([200,220],[40,230]));
    walls.push(new BeamTrace2D.Wall([40,230],[30,290]));
    walls.push(new BeamTrace2D.Wall([30,290],[60,270]));
    walls.push(new BeamTrace2D.Wall([60,270],[290,270]));
    walls.push(new BeamTrace2D.Wall([290,270],[250,220]));

    //Then a listener and a source
    var listener = new BeamTrace2D.Listener([80,100]);
    var source = new BeamTrace2D.Source([200,80]);

    //Pass the walls and the source to the solver, which does pre-calculations for fast solving
    var reflection_order = 4; //How many reflections do we want to calculate?
    var solver = new BeamTrace2D.Solver(walls,source,reflection_order); //Init the solver

    //**This is stupid, but my chrome works much faster if I do this again (?? some optimization thing ??)**
    solver = new BeamTrace2D.Solver(walls,source,reflection_order);
    //**

    //path_tree will contain the reflection paths according to: [ [[x,y,wall index],[x,y,wall index],[x,y,wall index],...],[path2],... ]
    var path_array = solver.getPaths(listener);

    //A function for painting the solution
    function redraw()
    {
        if(!ctx) return;
        ctx.clearRect(0,0,300,300);
        ctx.lineWidth = 2.0;
        walls.forEach(function(wall){
            wall.draw(ctx);
        });
        ctx.lineWidth = 1.0;
        listener.draw(ctx);
        source.draw(ctx);

        //Draw the paths
        if(path_array)
        {
            for(var i = 0; i < path_array.length; i++) //Go through all reflection paths
            {
                //Draw each path
                var first = true;
                ctx.strokeStyle = "rgba(0,0,255,0.2)";
                ctx.beginPath();
                ctx.lineWidth = 2;
                path_array[i].forEach(function(p){
                    if(first) { ctx.moveTo(p[0],p[1]); first = false; }
                    else { ctx.lineTo(p[0],p[1]); }
                });
                ctx.stroke();
                ctx.strokeStyle = "black";
                ctx.lineWidth = 1;
            }
        }
    }

    //If the walls or source position are updated, the solver needs to be initialized again
    $('#beamCanvas').click(function(e) {
        source.p0 = [e.offsetX, e.offsetY]; //Change the source position
        solver = new BeamTrace2D.Solver(walls,source,reflection_order); //Init the solver with the new source position
        path_array = solver.getPaths(listener); //Update reflection paths
        redraw();
    });

    //Update the listener position
    $('#beamCanvas').mousemove(function(e) {
        listener.p0 = [e.offsetX, e.offsetY];
        path_array = solver.getPaths(listener); //Update reflection paths
        redraw();
    });

    redraw(); //First redraw
});<|endoftext|>


<commit_before>$(document).ready(function() {
});
<commit_msg>open a new tab when click a url contained other domain.<commit_after>// open a new tab when click a url contained other domain.
$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');
<|endoftext|>


<commit_before>$(document).ready(function() {
  var twitchUserName = ['frogsama','vvarrenstudios',"thenutzxd",'jamaica105'];

  //Iterate through the array of usernames and call getTwitch
  twitchUserName.forEach(function(name) {
    getTwitch(name)
  });

  //Activate Nav Pills
  $(".selector").click(function() {
		var status = $(this).attr('id');
		if (status === "all-streams") {
			$(".online, .offline").show();
		} else if (status === "online") {
			$(".online").show();
			$(".offline").hide();
		} else {
			$(".offline").show();
			$(".online").hide();
		}
	})
});

//GET TWITCH API INFO
  function getTwitch(twitchUserName){
    $.ajax({
      type:"GET",
      url:"https://api.twitch.tv/kraken/streams/" + twitchUserName,
      headers:{
        'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
      success: function twitchData(data) {
        // Call 'streams' and if the channel is active, get stream data
        if(data.stream !== null){

          var streamImage = data.stream.preview.large;
          var streamGame = data.stream.game;
          var streamInfo = data.stream.channel.status;
          var streamLogo = data.stream.channel.logo;
          var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
          var streamCard='';

          //IF EVERYTHING IS A SUCCESS IT BUILDS A STREAMCARD//

          streamCard = "
" + "
" + "ONLINE" + "
" + "" + "
" + "
" + twitchUserName + "

" + streamGame + ": " + streamInfo + "

";
          $(".card-container").append(streamCard);
       } else {
          // If the channel is offline, get channel data
          $.ajax({
            type:"GET",
            url:"https://api.twitch.tv/kraken/channels/" + twitchUserName,
            headers:{
              'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
            success: function(data){
              var streamBanner = data.video_banner;
              var streamLogo = data.logo;
              var streamError = data.status;
              var streamCard = "";

              //IF THERE IS NO CHANNEL INFO
              if (streamError == 404 || streamBanner == null || streamLogo == null){
                $.ajax({
                  type:"GET",
                  url:"https://api.twitch.tv/kraken/users/" + twitchUserName,
                  headers:{
                    'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
                  success: function(data){
                    var streamMessage = data.error;
                    // var streamBanner = data.video_banner;
                    var defaultImage = 'https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif';
                    var defaultThumb = 'http://www.leftpheild.com/img/orou.png';
                    //IF ACCOUNT HAS BEEN CLOSED BUILD STREAMCARD
                    if(streamMessage == "Unprocessable Entity"){
                      streamCard = "
" + "
" + "OFFLINE" + "
" + "" + "
" + "
" + twitchUserName + "

This Twitch account has been closed.

";
                  $(".card-container").append(streamCard);
		    } else if (streamMessage == "Not Found"){
                    //IF IT NEVER EXISTED
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

This Twitch account never existed.

";
                    $(".card-container").append(streamCard);
                    }else if (streamBanner == null && streamLogo == null){
                    //IF Banner AND  Logo don't Work
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                    $(".card-container").append(streamCard);
                    }
                    else if (streamBanner == null){
                    //IF Banner Doesn't Exist
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                    $(".card-container").append(streamCard);
                    }
                  }
                })
              } else { // If account exists, but user is not currently streaming, build streamCard
                streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                $(".card-container").append(streamCard);
              }
            }
          })
        }
      }
    })

  } //END OF FUNCTION);
<commit_msg>Update main.js<commit_after>$(document).ready(function() {
  var twitchUserName = ['frogsama','vvarrenstudios',"thenutzxd",'jamaica105','michiganspartan','ritterriffic'];

  //Iterate through the array of usernames and call getTwitch
  twitchUserName.forEach(function(name) {
    getTwitch(name)
  });

  //Activate Nav Pills
  $(".selector").click(function() {
		var status = $(this).attr('id');
		if (status === "all-streams") {
			$(".online, .offline").show();
		} else if (status === "online") {
			$(".online").show();
			$(".offline").hide();
		} else {
			$(".offline").show();
			$(".online").hide();
		}
	})
});

//GET TWITCH API INFO
  function getTwitch(twitchUserName){
    $.ajax({
      type:"GET",
      url:"https://api.twitch.tv/kraken/streams/" + twitchUserName,
      headers:{
        'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
      success: function twitchData(data) {
        // Call 'streams' and if the channel is active, get stream data
        if(data.stream !== null){

          var streamImage = data.stream.preview.large;
          var streamGame = data.stream.game;
          var streamInfo = data.stream.channel.status;
          var streamLogo = data.stream.channel.logo;
          var streamURL = 'http://www.twitch.tv/'+ twitchUserName;
          var streamCard='';

          //IF EVERYTHING IS A SUCCESS IT BUILDS A STREAMCARD//

          streamCard = "
" + "
" + "ONLINE" + "
" + "" + "
" + "
" + twitchUserName + "

" + streamGame + ": " + streamInfo + "

";
          $(".card-container").append(streamCard);
       } else {
          // If the channel is offline, get channel data
          $.ajax({
            type:"GET",
            url:"https://api.twitch.tv/kraken/channels/" + twitchUserName,
            headers:{
              'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
            success: function(data){
              var streamBanner = data.video_banner;
              var streamLogo = data.logo;
              var streamError = data.status;
              var streamCard = "";

              //IF THERE IS NO CHANNEL INFO
              if (streamError == 404 || streamBanner == null || streamLogo == null){
                $.ajax({
                  type:"GET",
                  url:"https://api.twitch.tv/kraken/users/" + twitchUserName,
                  headers:{
                    'Client-ID': 'dhtxhmg8vey6qz5y964c3u15vmcssa'
      },
                  success: function(data){
                    var streamMessage = data.error;
                    // var streamBanner = data.video_banner;
                    var defaultImage = 'https://media.giphy.com/media/l3q31122uBsO7hpmw/source.gif';
                    var defaultThumb = 'http://www.leftpheild.com/img/orou.png';
                    //IF ACCOUNT HAS BEEN CLOSED BUILD STREAMCARD
                    if(streamMessage == "Unprocessable Entity"){
                      streamCard = "
" + "
" + "OFFLINE" + "
" + "" + "
" + "
" + twitchUserName + "

This Twitch account has been closed.

";
                  $(".card-container").append(streamCard);
		    } else if (streamMessage == "Not Found"){
                    //IF IT NEVER EXISTED
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

This Twitch account never existed.

";
                    $(".card-container").append(streamCard);
                    }else if (streamBanner == null && streamLogo == null){
                    //IF Banner AND  Logo don't Work
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                    $(".card-container").append(streamCard);
                    }
                    else if (streamBanner == null){
                    //IF Banner Doesn't Exist
                    streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                    $(".card-container").append(streamCard);
                    }
                  }
                })
              } else { // If account exists, but user is not currently streaming, build streamCard
                streamCard = "
"+"
"+"OFFLINE"+"
"+""+"
"+"
" + twitchUserName + "

Not currently streaming.

";
                $(".card-container").append(streamCard);
              }
            }
          })
        }
      }
    })

  } //END OF FUNCTION);
<|endoftext|>


<commit_before>var column_counter = 0;
var row_counters = [0,0,0];
var row_maxs = [0,1,0];
var scrolling_allowed = true;
var row_colours = ['#ffffff', '#ff0000', '#00ff00'];

$(document).ready(function(){

    $('#slide-0-0').show();

    $('#right-arrow').click(function(){
        scrollRight();
    });

    $('#left-arrow').click(function(){
        scrollLeft();
    });

    $('.nav-button').click(function(){
        var $this = $(this);
        var next_slide_column = $this.data('panelNum');
        if(next_slide_column < 0 || next_slide_column >= row_counters.length || next_slide_column == column_counter || !scrolling_allowed){
            return;
        }

        var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
        var new_slide = '#slide-' + next_slide_column + "-"+row_counters[next_slide_column];
        var direction = 'up';
        if(column_counter < next_slide_column) {
            direction = 'down';
        }
        column_counter = next_slide_column;
        displayArrows();
        changeNav(next_slide_column);
        changeSlide($(current_slide), $(new_slide), direction);
    });

    $(window).bind('mousewheel DOMMouseScroll', function(event){
        if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
            scrollUp();
        }
        else {
            scrollDown();
        }
    });

    $(document).keydown(function(e){
        switch(e.which) {
            case 37: // left
                scrollLeft();
                break;

            case 38: // up
                scrollUp();
                break;

            case 39: // right
                scrollRight();
                break;

            case 40: // down
                scrollDown();
                break;

            default: return; // exit this handler for other keys
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
    });

});

function scrollRight(){
    if(row_maxs[column_counter] == 0 || !scrolling_allowed){
        return;
    }

    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    row_counters[column_counter] ++;
    if(row_counters[column_counter] > row_maxs[column_counter]){
        row_counters[column_counter] = 0;
    }

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    changeSlide($(current_slide), $(new_slide), 'right');
}

function scrollLeft(){
    if(row_maxs[column_counter] == 0 || !scrolling_allowed){
        return;
    }

    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    row_counters[column_counter] --;
    if(row_counters[column_counter] < 0){
        row_counters[column_counter] = row_maxs[column_counter];
    }

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    changeSlide($(current_slide), $(new_slide), 'left');
}

function scrollUp(){
    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    if(column_counter <= 0 || !scrolling_allowed){
        return;
    }
    column_counter --;

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
    displayArrows();
    changeNav(column_counter);
    changeSlide($(current_slide), $(new_slide), 'up');
}

function scrollDown(){
    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    if(column_counter >= row_counters.length -1 || !scrolling_allowed){
        return;
    }
    column_counter ++;

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
    displayArrows();
    changeNav(column_counter);
    changeSlide($(current_slide), $(new_slide), 'down');

}

function changeSlide($current_slide, $new_slide, direction_show){
    var direction_hide;
    switch (direction_show){
        case 'down':
            direction_hide = 'up';
            break;
        case 'up':
            direction_hide = 'down';
            break;
        case 'left':
            direction_hide = 'right';
            break;
        case 'right':
            direction_hide = 'left';
            break;
    }
    scrolling_allowed = false;
    $('.nav-button').addClass('no-hover');
    window.setTimeout(function(){
        scrolling_allowed = true;
        $('.nav-button').removeClass('no-hover');
    }, 1000);
    $current_slide.hide('slide', {direction: direction_hide}, 1000);
    $new_slide.show('slide', {direction: direction_show}, 1000);
}
function changeNav(column_num){
    $('.nav-button').removeClass('active');
    $('.nav-button[data-panel-num="'+column_num+'"]').addClass('active');
}

function displayArrows(){
    if(row_maxs[column_counter] == 0){
        $('#left-arrow').hide();
        $('#right-arrow').hide();
    }else{
        $('#left-arrow').show();
        $('#right-arrow').show();
    }
}<commit_msg>added background colour changing<commit_after>var column_counter = 0;
var row_counters = [0,0,0];
var row_maxs = [0,1,0];
var scrolling_allowed = true;
var row_colours = ['#ffffff', '#ff0000', '#00ff00'];

$(document).ready(function(){

    $('#slide-0-0').show();

    $('#right-arrow').click(function(){
        scrollRight();
    });

    $('#left-arrow').click(function(){
        scrollLeft();
    });

    $('.nav-button').click(function(){
        var $this = $(this);
        var next_slide_column = $this.data('panelNum');
        if(next_slide_column < 0 || next_slide_column >= row_counters.length || next_slide_column == column_counter || !scrolling_allowed){
            return;
        }

        var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
        var new_slide = '#slide-' + next_slide_column + "-"+row_counters[next_slide_column];
        var direction = 'up';
        if(column_counter < next_slide_column) {
            direction = 'down';
        }
        column_counter = next_slide_column;
        displayArrows();
        changeNav(next_slide_column);
        changeSlide($(current_slide), $(new_slide), direction);
    });

    $(window).bind('mousewheel DOMMouseScroll', function(event){
        if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
            scrollUp();
        }
        else {
            scrollDown();
        }
    });

    $(document).keydown(function(e){
        switch(e.which) {
            case 37: // left
                scrollLeft();
                break;

            case 38: // up
                scrollUp();
                break;

            case 39: // right
                scrollRight();
                break;

            case 40: // down
                scrollDown();
                break;

            default: return; // exit this handler for other keys
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
    });

});

function scrollRight(){
    if(row_maxs[column_counter] == 0 || !scrolling_allowed){
        return;
    }

    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    row_counters[column_counter] ++;
    if(row_counters[column_counter] > row_maxs[column_counter]){
        row_counters[column_counter] = 0;
    }

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    changeSlide($(current_slide), $(new_slide), 'right');
}

function scrollLeft(){
    if(row_maxs[column_counter] == 0 || !scrolling_allowed){
        return;
    }

    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    row_counters[column_counter] --;
    if(row_counters[column_counter] < 0){
        row_counters[column_counter] = row_maxs[column_counter];
    }

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    changeSlide($(current_slide), $(new_slide), 'left');
}

function scrollUp(){
    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    if(column_counter <= 0 || !scrolling_allowed){
        return;
    }
    column_counter --;

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
    displayArrows();
    changeNav(column_counter);
    changeSlide($(current_slide), $(new_slide), 'up');
}

function scrollDown(){
    var current_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];

    if(column_counter >= row_counters.length -1 || !scrolling_allowed){
        return;
    }
    column_counter ++;

    var new_slide = '#slide-' + column_counter + "-"+row_counters[column_counter];
    displayArrows();
    changeNav(column_counter);
    changeSlide($(current_slide), $(new_slide), 'down');

}

function changeSlide($current_slide, $new_slide, direction_show){
    var direction_hide;
    switch (direction_show){
        case 'down':
            direction_hide = 'up';
            break;
        case 'up':
            direction_hide = 'down';
            break;
        case 'left':
            direction_hide = 'right';
            break;
        case 'right':
            direction_hide = 'left';
            break;
    }
    scrolling_allowed = false;
    $('.nav-button').addClass('no-hover');
    window.setTimeout(function(){
        scrolling_allowed = true;
        $('.nav-button').removeClass('no-hover');
    }, 1000);
    $current_slide.hide('slide', {direction: direction_hide}, 1000);
    $new_slide.show('slide', {direction: direction_show}, 1000);
}
function changeNav(column_num){
    $('.nav-button').removeClass('active');
    $('.nav-button[data-panel-num="'+column_num+'"]').addClass('active');
    changeBackground(column_num);
}

function changeBackground(column_num){
    var color = row_colours[column_num];
    $('body').animate({backgroundColor: color}, 1000);
}

function displayArrows(){
    if(row_maxs[column_counter] == 0){
        $('#left-arrow').hide();
        $('#right-arrow').hide();
    }else{
        $('#left-arrow').show();
        $('#right-arrow').show();
    }
}<|endoftext|>


<commit_before>/*
 * 1) installazione moduli utilizzati
 * npm install request
 * npm install mongoose
 *
 * 2) creazione dello schema 'meps'
 *  TODO: ha senso aggiungere la creazione via script?
 *
 * 3) per la gestione/visualizzazione di mongdb si può installare RockMongo
 * 4) per eseguire lo script (ad esempio via crontab): >> node import-meps.js
 *
 */

// app configuration
var config = require('../config.js');
var request = require('request');
var mongoose = require('mongoose');
//var php = require('phpjs');
var fs = require('fs')

mongoose.set('debug', config.db_debug)
var mepCounter = 0;

// hack per fs
fs.exists = fs.exists || require('path').exists;
fs.existsSync = fs.existsSync || require('path').existsSync;

// TODO: iniziamo da qui, poi possiamo usare entrambi gli endpoint delle api
// TODO: va verificata l'univocità del record da inserire (eventualmente
// fatto update)
// TODO: gestire la paginazione: per ora ci sono valori fissi di comodo
var url_api = config.api_url;

var db = mongoose.createConnection(config.db_host, config.db_name);

// error handling
db.on('error', console.error.bind(console, 'connection error:'));

// close connection
db.on('close', function() {
  console.log('Thanks! You have correctly import/update ' + mepCounter + ' users.');
  process.exit(1);
});

// on opening connection
db.once('open', function() {
  console.log("open connection on\n%s\n", url_api)

  // creiamo lo schema
  var mepSchema = config.schema

  // creiamo il modello dati
  var MepModel = db.model(config.db_collection, mepSchema);
  //MEP.ensureIndexes(function(e) { /* TODO: serve? */  }); // @todo check this

  // create cache dir
  if (!fs.existsSync('./cache')) {
    fs.mkdirSync('./cache');
  }

  // get the stream and make a cache file, in order to be used by application (offline mode)
  request(url_api, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      dispatch(JSON.parse(body))
    }
  }).pipe(fs.createWriteStream('./cache/mep-cache-dump-' + new Date().getTime()));

  // add additional data, save to mongo
  function doSave(mep) {
    for (attr in mep) {
      if (attr === 'mep_twitterUrl') {
        var tw_url = mep[attr];
        if (tw_url) {
          //var username = php.array_pop(php.explode('/', tw_url));
	  var username = tw_url.split('/').pop();
          mep.mep_twitterUserName = username;
        }
      }
    }

    // create a fullname field to make search operation easy
    mep.mep_fullName = mep.mep_firstName + ' ' + mep.mep_lastName;

    mep.save(function(err, type) {
      if (err) {
        console.error('Saving user problem.');
        process.exit(0);
      }
      console.log('User "' + mep.mep_firstName + ' ' + mep.mep_lastName  + '" ' + type);
    });
  }

  // save/update handler
  function saveUpdate(remote_mep) {
    // udpate save the user
    MepModel.findOne({mep_userId: remote_mep.mep_userId}, function(err, user) {
      if (err) {
        console.error('Find users problems, please check mongodb connection.');
        process.exit(0);
      }
      // new user
      if (!user) {
        MepSchema = new MepModel(remote_mep);
        doSave(MepSchema, 'save');
      }
      // existing user
      else {
        for (attr in remote_mep) {
          if (attr != 'mep_userId') {
            user.attr = remote_mep[attr];
          }
        }
        doSave(user, 'update');
      }
    });
  }

  // json dispatching
  function dispatch(mepsList){
    mepCounter = mepsList.length;
    var len = mepsList.length;

    for (var i=0; i<len; ++i) {
      var remote_mep = mepsList[i];
      saveUpdate(remote_mep);
    }
    // close connection as described here: https://github.com/LearnBoost/mongoose/issues/330#issuecomment-1061042
    setTimeout( function () {
     mongoose.disconnect();
    }, 1000);
  }

});

<commit_msg>photo downloader (disabled)<commit_after>/*
 * 1) installazione moduli utilizzati
 * npm install request
 * npm install mongoose
 *
 * 2) creazione dello schema 'meps'
 *  TODO: ha senso aggiungere la creazione via script?
 *
 * 3) per la gestione/visualizzazione di mongdb si può installare RockMongo
 * 4) per eseguire lo script (ad esempio via crontab): >> node import-meps.js
 *
 */

// app configuration
var config = require('../config.js');
var request = require('request');
var mongoose = require('mongoose');
//var php = require('phpjs');
var fs = require('fs')

mongoose.set('debug', config.db_debug)
var mepCounter = 0;

// hack per fs
fs.exists = fs.exists || require('path').exists;
fs.existsSync = fs.existsSync || require('path').existsSync;

// TODO: iniziamo da qui, poi possiamo usare entrambi gli endpoint delle api
// TODO: va verificata l'univocità del record da inserire (eventualmente
// fatto update)
// TODO: gestire la paginazione: per ora ci sono valori fissi di comodo
var url_api = config.api_url;

var db = mongoose.createConnection(config.db_host, config.db_name);

// error handling
db.on('error', console.error.bind(console, 'connection error:'));

// close connection
db.on('close', function() {
  console.log('Thanks! You have correctly import/update ' + mepCounter + ' users.');
  process.exit(1);
});

// on opening connection
db.once('open', function() {
  console.log("open connection on\n%s\n", url_api)

  // creiamo lo schema
  var mepSchema = config.schema

  // creiamo il modello dati
  var MepModel = db.model(config.db_collection, mepSchema);
  //MEP.ensureIndexes(function(e) { /* TODO: serve? */  }); // @todo check this

  // create cache dir
  if (!fs.existsSync('./cache')) {
    fs.mkdirSync('./cache');
  }

  // get the stream and make a cache file, in order to be used by application (offline mode)
  request(url_api, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      dispatch(JSON.parse(body))
    }
  }).pipe(fs.createWriteStream('./cache/mep-cache-dump-' + new Date().getTime()));

  function validateURL(value) {
    return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
  }

  // add additional data, save to mongo
  function doSave(mep) {
    for (attr in mep) {
      if (attr === 'mep_twitterUrl') {
        var tw_url = mep[attr];
        if (tw_url) {
	        var username = tw_url.split('/').pop();
          mep.mep_twitterUserName = username;
        }
      }
      /* Disabled, we should check the privacy stuff in order to download locally photos
         This is an async call, we should find a better method to close the process when download is finished.
      */
      /*
      if (attr == 'mep_epFotoUrl') {
        // download photo locally
        var remote_photo = mep[attr];
        if (remote_photo && validateURL(remote_photo)) {
          var photo_name = remote_photo.split('/').pop();

          request(remote_photo, function (error, response, body) {
            console.log('Downloading photo: ' + remote_photo);
            fs.writeFile('./images/' + photo_name, body);
          });

          //request(remote_photo).pipe(fs.createWriteStream('./images/' + photo_name));
          mep.local_image = photo_name;
        }
      }
      */
    }

    // create a fullname field to make search operation easy
    mep.mep_fullName = mep.mep_firstName + ' ' + mep.mep_lastName;

    mep.save(function(err, type) {
      if (err) {
        console.error('Saving user problem.');
        process.exit(0);
      }
      console.log('User "' + mep.mep_firstName + ' ' + mep.mep_lastName  + '" ' + type);
    });
  }

  // save/update handler
  function saveUpdate(remote_mep) {
    // udpate save the user
    MepModel.findOne({mep_userId: remote_mep.mep_userId}, function(err, user) {
      if (err) {
        console.error('Find users problems, please check mongodb connection.');
        process.exit(0);
      }
      // new user
      if (!user) {
        MepSchema = new MepModel(remote_mep);
        doSave(MepSchema, 'save');
      }
      // existing user
      else {
        for (attr in remote_mep) {
          if (attr != 'mep_userId') {
            user.attr = remote_mep[attr];
          }
        }
        doSave(user, 'update');
      }
    });
  }

  // json dispatching
  function dispatch(mepsList){
    mepCounter = mepsList.length;
    var len = mepsList.length;

    for (var i=0; i<len; ++i) {
      var remote_mep = mepsList[i];
      saveUpdate(remote_mep);
    }
    // close connection as described here: https://github.com/LearnBoost/mongoose/issues/330#issuecomment-1061042
    setTimeout( function () {
     mongoose.disconnect();
    }, 1000);
  }

});

<|endoftext|>


<commit_before>function scrollToHash(hash) {
  const offsetTop = -$('.title-bar').height();
  $(window).stop(true).scrollTo(hash, {
    axis: 'y',
    duration: 400,
    interrupt: false,
    offset: {
      top: offsetTop,
    },
  });
}

function hashLinkHandler(e) {
  e.preventDefault();
  history.pushState(null, null, this.hash);
  scrollToHash(this.hash);

  if (!Foundation.MediaQuery.atLeast('large')) {
    $('#main-menu').hide('fast');
  }
}

$(document).ready(function() {
  $(document).foundation();

  $('.faq-wrap').masonry({
    itemSelector: '.faq',
    columnWidth: '.faq-sizer',
    percentPosition: true,
  });

  // https://gist.github.com/flesler/3f3e1166690108abf747
  $('body').on('click', "a[href^='#'], a[href^='/#']", hashLinkHandler);

  $('.faq').on('on.zf.toggler off.zf.toggler', function() {
    $('.faq-wrap').masonry();
  });

  if (window.location.hash[0] === '#') {
    scrollToHash(window.location.hash);
  }

  // Read login status cookie, and show buttons if logged in
  var userId = Cookies.get('meteor_is_logged_in');
  if (userId === 'true') {
    $('.js-show-if-logged-out').addClass('hide');
    $('.js-show-if-logged-in').removeClass('hide');
  }
});
<commit_msg>hide chrome on ?embedded=1<commit_after>function scrollToHash(hash) {
  const offsetTop = -$('.title-bar').height();
  $(window).stop(true).scrollTo(hash, {
    axis: 'y',
    duration: 400,
    interrupt: false,
    offset: {
      top: offsetTop,
    },
  });
}

function hashLinkHandler(e) {
  e.preventDefault();
  history.pushState(null, null, this.hash);
  scrollToHash(this.hash);

  if (!Foundation.MediaQuery.atLeast('large')) {
    $('#main-menu').hide('fast');
  }
}

// https://stackoverflow.com/a/901144
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

$(document).ready(function() {
  $(document).foundation();

  $('.faq-wrap').masonry({
    itemSelector: '.faq',
    columnWidth: '.faq-sizer',
    percentPosition: true,
  });

  // https://gist.github.com/flesler/3f3e1166690108abf747
  $('body').on('click', "a[href^='#'], a[href^='/#']", hashLinkHandler);

  $('.faq').on('on.zf.toggler off.zf.toggler', function() {
    $('.faq-wrap').masonry();
  });

  if (window.location.hash[0] === '#') {
    scrollToHash(window.location.hash);
  }

  // Read login status cookie, and show buttons if logged in
  var userId = Cookies.get('meteor_is_logged_in');
  if (userId === 'true') {
    $('.js-show-if-logged-out').addClass('hide');
    $('.js-show-if-logged-in').removeClass('hide');
  }

  var embedded = (getParameterByName('embedded') == '1');
  if (embedded) {
    $('.main-wrapper > nav').hide();
    $('.main-wrapper > footer').hide();
    $('body').css('padding-top', 0);
  }
});
<|endoftext|>