document.observe('click', function(event) { RouteManager.eventObserver(event) });
document.observe('route:fire', function(event) { RouteManager.eventObserver(event) });

RouteManager = {
	eventObserver: function(event) {
		if(event.findElement('a')) {
			var element = event.findElement('a');
			var routePath = element.readAttribute('href');
			var route;
			
			if(route = RouteManager.doRouteWithPath(routePath, element)) {
				event.stop();
				if(!route.silent)
					window.location.hash = routePath;
			}
		}
	},
	
	doRouteWithPath: function(routePath, element) {
		var foundRoute = false;
		
		if(Routes) {
			Routes.each(function(route) {
				var pair = this.regexAndParamNamesFromRoute(route.route);
				var regex = pair.regex;
				var paramNames = pair.paramNames;
				var matches = routePath.match(regex);
				var params = {};
				
				if(matches) {
					foundRoute = route;
					matches.splice(0,1);
					
					for(var index = 0; index < matches.length; index++) {
						params[paramNames[index]] = matches[index];
					}
					
					params.element = element;
					params.route = {};
					params.route.match = route;
					params.route.request = routePath;
					
 					try { 
						window[route.namespace][route.action](params);
 					} 
 					catch(err) { 
/* 						console.log("Something went wrong: "+ err.message + "\n source: " + err.sourceURL + "\n line: " + err.line); */
 					} 
					
					throw $break;
				}
			}, this);
		}
		
		return foundRoute;
	},
	
	regexAndParamNamesFromRoute: function(route) {
		var selectorRegex = /(\w+):/g;
		
		var paramNames = route.match(selectorRegex);
		if(paramNames) {
			paramNames.each(function(paramName, index) { paramNames[index] = paramName.replace(/:/, '' ) });
			route = route.gsub(/([\w\d]+):/, '');
		}
		else {
			paramNames = [];
		}
		
		return {regex: new RegExp("^" + route + "$"), paramNames: paramNames };
	}
}

