/******
Filename:		externallinks.js
Author:			James Condliffe
Date:			11/07/2006
Amended:        Andrei Vais - 23/07/2009
Description:	Makes all external links open in a new window
				decides if a link is external by comparing it to the current hostname
******/

function setupExternalLinks()
{
	// Grab our current base hostname
	var baseHref;
	var regexp = /(https?:\/\/)([^\/]+)/i;
	matches = regexp.exec(window.location);	
	baseHref = matches[2];

	var pageBaseHRef = document.getElementsByTagName('base');
	//alert("basehref: " + baseHref +"\nwindow.location: " + window.location + "\npageBaseHRef: " + pageBaseHRef[0].getAttribute("href"));
	
	// Grab the links	
	var docLinks = document.getElementsByTagName("a");

	// Loop through the links
	for (var i=0; i<docLinks.length; i++)
	{
		var anchor = docLinks[i];

		if (anchor.getAttribute("href"))                                                                                     // if it's a link
		{
			var href = anchor.getAttribute("href");
				
			if ((href.indexOf(baseHref) < 0 && href.indexOf("http://") > -1) || anchor.getAttribute("rel") == "external")   // it's an external link
			{
				anchor.onclick = function(){window.open(this.getAttribute('href').replace(pageBaseHRef[0].getAttribute("href"), "")); return false;};
				// Update the title attribute to include new window information
				anchor.setAttribute("title", anchor.getAttribute("title") + " (opens in new window)");
			}
			else if (href.indexOf(".pdf") > 0)				                                                                // it's a PDF or DOC document
			{
				anchor.onclick = function(){window.open(pageBaseHRef[0].getAttribute("href") + this.getAttribute('href').replace(pageBaseHRef[0].getAttribute("href"), "")); return false;};
				// Update the title attribute to include new window information
				anchor.setAttribute("title", anchor.getAttribute("title") + " (opens in new window)");
			}	
		}
	}
}


addLoadEvent(setupExternalLinks);
