/*
 * Usage:
 * <script>
 * LB.speedbump(confirmMessage,/excluded-domain1\.com/,/excluded-domain2\.com/);
 * </script>
 * Near the end of the document.
 */

if(!window.LB) LB = {};
LB.speedbump = function(message){
	var oldMousedown = document.onmousedown;
	var exclude = [].slice.call(arguments,1);
	
	var normalizeEvent = function(event){
		e = { original:event ? event : window.event };
		e.button = e.original.target ? e.original.button : {1:0,2:2,4:1}[e.original.button];
		e.target = e.original.target ? e.original.target : e.original.srcElement;
		return e;
	};
	
	var getLinkClicked = function(e){
		var link = e.target;
		while(link && (!link.tagName || link.tagName.toLowerCase()!='a' || !link.href)) link = link.parentNode;
		return link;
	};
	
	document.onmousedown = function(e){
		// defer to (unlikely) existing mousedown
		if(oldMousedown && oldMousedown.call(window,event)==false) return false;
		// get link, normalize event
		var link = getLinkClicked(e = normalizeEvent(e));
		if(!link) return true;
		// return if no protocol in link
		var match = /^(http|https|ftp):\/\/([^\/]+)\//.exec(link.href);
		if(!match) return true;
		// return if domain in list of excluded domains
		var domain = match[2];
		for(var i = 0; i< exclude.length; i++) {
			if(exclude[i].exec(domain)) return true;
		}
		// trap left mouse button and confirm
		if(e.button==0) {
			var oldClick = link.onclick; 
			link.onclick = function(e){
				if(oldClick && oldClick.call(link,e)==false) return false;
				this.onclick = oldClick;
				return confirm(message);
			}
		}
		return true;
	}
};