/*
 Converts all links to ExpressionEngine.com into affiliate links.
 Courtesy of Brandon Kelly (http://gist.github.com/283093).
 Adjusted to test for www in URLs too
*/
 
$(document).ready(function() {
	 
	var ee_affiliate_name = 'versastudio',
		external_re = new RegExp('^https?://(?!' +document.location.hostname +')'),
		external_ee_re = new RegExp('^(https?://(secure\\.|www\\.)?expressionengine.com\\/)([^#]*)(#(\\w+))?$'),
		ee_affiliate_re = new RegExp('^index\\.php\\?affiliate=' +ee_affiliate_name);
	 
	$('a').each(function(){
		
		// is this an external link?
		if (this.href.match(external_re)) {	
			/*
			 Convert all non-affliliate links to ExpressionEngine.com
			 into affiliate links.
			*/
			
			var href = this.href,
				match = href.match(external_ee_re);
				
			if (match && ! match[3].match(ee_affiliate_re)) {
				
				this.href = match[1] +'index.php?affiliate=' +ee_affiliate_name
					+(match[3] ? '&page=/' +match[3] : '')
					+(match[5] ? '&anchor=' +match[5] : '');
			}
		}	
	});
	
});
