(function() {
	var slideView;
	var linksByTarget = {};

	var linkHandler = function(id, a, allLinks) {
		var f = function(theEvent) {
			theEvent.preventDefault();

			var n, o;
			for (n = 0; n < allLinks.length; n++) {
				o = allLinks[n];
				o.className = "";
			}

			a.className = "active";

			document.title = "QWERTED: " + this.textContent;
			// document.location = this.href;

			slideView.showSlide(id);

			/* fix ugly border in Firefox */
			this.blur();
		};

		return f;
	}

	var patchLinkActions = function() {
		var links = document.getElementsByTagName("a");
		var n, a, matches, allLinks = [];

		var targetRegex = /#([a-z0-9]+)$/;

		for (n = 0; n < links.length; ++n) {
			a = links[n];
			matches = a.href.match(targetRegex);
			if (matches !== null) {
				allLinks.push(a);
				linksByTarget[matches[1]] = a;
				a.addEventListener("click", linkHandler(matches[1], a, allLinks), false);
			}
		}
	};

	var initSlideView = function(theEvent) {
		slideView = org.brainwidth.SlideView.create("slides");
	};

	var showTargetSlide = function(theEvent) {
		var hash = document.location.hash;
		var id = hash.substr(1, hash.length-1);
		var a = linksByTarget[id];

		if (a) {
			var mouse = document.createEvent("MouseEvents");
			mouse.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			a.dispatchEvent(mouse);
		}
	}

	window.addEventListener("load", initSlideView, false);
	window.addEventListener("load", patchLinkActions, false);
	window.addEventListener("load", showTargetSlide, false);
})();
