/** This inspects each link on a page and alters each link so that it opens in a new page
 *  if it is explicitly marked #external or if its domain differs from the current domain
 *  and it is not explicitly marked #internal.
 *  
 *  <a> tags with class "user_url" that have a null href attribute are removed (while
 *  retaining the tag's child tags).
 *  If such an <a> also contains an img with a null src, the img is removed too.
 */


function checkLinks(){
	log('running checklinks()');
	var thisdomain = document.domain;
	var links = document.links;
	
	//scan for and fix empty user manipulated <a> tags.
	var atags = Q('a.user_url[href=""]');
	Q.each(atags, function(i, d_atag){
		var atag = Q(d_atag);
		var contents = Q(atag.html());
		contents.insertBefore(atag);
	});
	Q('a.user_url[href=""]').remove();
	
	//remove empty user-manipulated images 
	var imgtags = Q('img.user_url[src=""]').remove();
	
	//iterate through all links on the page
	for (var i = 0, l = links.length; i < l; i++) {
		//get the url of the link
		var linkurl = links[i].getAttribute("href");
		var template = links[i].getAttribute('template');
		var linkdomain = get_hostname_from_url(linkurl);
		
		//log(linkdomain + ' is the detected hostname for ' + linkurl);
		
		//determine if the link has been marked with #internal
		var forcedInternal = false;
		if (linkurl.search('#internal') > -1) {
			forcedInternal = true;
		}
		
		//determine if the link is to be opened in a new window
		//these are links marked with #external or with the redirection template( id 51)
		var forcedExternal = false;
		if (linkurl.search('#external') > -1 || template == 51) {
			forcedExternal = true;
		}
		
		//Update the link
		if (forcedExternal || (linkdomain != thisdomain && !forcedInternal)) {
			links[i].setAttribute('target', '_blank');
			log('setting this link to open in a new window: ' + linkurl);
		}
	}
}

function get_hostname_from_url(url) {
	protoIndex = url.indexOf('://');
	dotIndex = url.indexOf('.');
	slashIndex = url.indexOf('/');
	linkdomain = '';
	
	if (protoIndex > -1) {
		//Assumes url is fully formed
		linkdomain = url.split(/\/+/g)[1];
	} else if (dotIndex > -1 && slashIndex > -1 && dotIndex < slashIndex){
		//Assumes the protocol has been left out
		linkdomain = url.split(/\//)[0];
	} else if (dotIndex > -1 && slashIndex < 0) {
		//Assumes this is the domain itself
		linkdomain = url;
	}
	
	//return this as the domain if it passes verification
	if (verify_domain(linkdomain)) {
		return linkdomain;
	}
	
	//Assume what was passed was either an invalid url or a relative path
	//so return current domain as default
	return document.domain;
}

function verify_domain(domain) {
	valid = true;
	
	//Valid domain must contain a namespace (.com, .co.uk etc)
	chunks = domain.split('.');
	if (chunks.length < 2) valid = false;
	
	//Valid domain names must contain at least 3 characters
	//domain_name = chunks[chunks.length-2]; //DONT KNOW WHICH IS THE DOMAIN_NAME!
	//if (!(domain_name.match(/[\w-]{3,}/))) valid = false;
	
	//Valid domains contain only numbers letters hyphens and full stops
	//A colon may also be in this string if a port has been specified
	if (domain.search(/[^\w.-:]/) > -1) valid = false;
	
	if(valid) {
		return true;
	}
	return false;
}

// logging function for debugging
// use log(params) instead of alert() or console.log()

if (typeof console == "object"){
	log = console.log;
}
else {
	log = function() {};
}

