$('document').ready(function() {
	$('#content a').not('.addthis_toolbox a').not('h3 a').not('h4 a').not('#image-cycler a').not('a.no-ext').each(processAll);
	
	$('#content h3 a').each(processSelected);
	
	$('#content #image-cycler a').each(processSelected);
	
	$('#content a[rel=new-window],#sidebar a[rel=new-window],.menu-holder a[rel=new-window]').attr('target', '_blank');
});

function processAll() {
	processExternalIcon($(this));
	
	processExternalGA($(this));
	
	processDocuments($(this));
}

function processSelected() {
	processExternalGA($(this));
	
	processDocuments($(this));
}

function processExternalIcon(anchor) {
	// Add 'external' class to non-RSP links
	var href = anchor.attr('href');
	
	if(href.indexOf('http') == 0 && href.indexOf('rsp.ac.uk') == -1)
	{
		anchor.addClass('external');
	}
}

function processExternalGA(anchor) {
	// Add Google Analytics code to exit links
	var href = anchor.attr('href');
	
	if(href.indexOf('http') == 0 && href.indexOf('rsp.ac.uk') == -1)
	{
		var offset = (href.indexOf('https') == 0) ? 8 : 7;
		
		var gaRef = href.substring(offset, href.length);
		if(gaRef != '')
		{
			anchor.click(function() { _gaq.push(['_trackPageview', '/exit/' + gaRef]); });
		}
	}
}

function processDocuments(anchor) {
	// Add Google Analytics code to document links
	var href = anchor.attr('href');
	
	if(href.indexOf('http') == -1 || href.indexOf('rsp.ac.uk') > 0)
	{
		if(href.indexOf('documents/') > 0)
		{
			var gaRef = '';
			var endPos = (href.indexOf('&') == -1) ? href.length : href.indexOf('&');
			
			if(href.indexOf('file=') > 0)
			{
				var endPos
				// Download link for uploaded file
				gaRef = href.substring(href.indexOf('file=') + 5, endPos);
			}
			else
			{
				// Direct link to document
				gaRef = href.substring(href.lastIndexOf('/') + 1, href.length);
			}
			
			if(gaRef != '')
			{
				anchor.click(function() { _gaq.push(['_trackPageview', '/documents/' + gaRef]); });
			}
		}
	}
}


