// Analytics tracking code for documents and external links
function setupAnalyticsTracking() {
	var links       = document.getElementsByTagName('a');

	var setup_link;
	for (var i = links.length; i != 0; i--) {
		setup_link = false;
		var a = links[i-1];
		if (!a.href) continue;

		// Track external links
		if(a.href.indexOf('http') != -1 &&
			a.href.indexOf(window.location.hostname) == -1){
			setup_link = true;
		}else if(isEmail(a.href)){
			setup_link = true;
		}else{
			// Track documents
			setup_link = isDocument(a.href);
		}

		if (setup_link){
			a.onclick = function() {
				track_url(this.href);
				return true;
			}

		}
	}
}

function isDocument(href){
	var track_files = new Array('.pdf', '.doc', '.PDF', '.DOC');
	for(var f = 0; f < track_files.length; f++){
		if(href.indexOf(track_files[f]) == (href.length - track_files[f].length)){
			return true;
		}
	}

	return false;
}

function isEmail(href){
	if(href.indexOf('mailto:') != -1){
		return true;
	}else{
		return false;
	}
}

function removeDomain(href){
	if(href.indexOf('http') != -1 && href.indexOf(window.location.hostname) != -1){
		href = href.substring((window.location.hostname.length + 7));
	}
	return href;
}

function removeHTTP(href){
	if(href.indexOf('http') != -1){
		href = href.substring(7);
	}
	return href;
}

function removeMailTo(href){
	if(href.indexOf('mailto:') != -1){
		href = href.substring(7);
	}
	return href;
}

function track_url(href) {
	if(window._gaq){
		if(isDocument(href)){
			_gaq.push(['_trackEvent', 'Misc Clicks', 'Document', href]);
		}else if(isEmail(href)){
			_gaq.push(['_trackEvent', 'Misc Clicks', 'MailTo', href]);
		}else{
			_gaq.push(['_trackEvent', 'Misc Clicks', 'External url', href]);
		}
	}
}

function setupExternalLinks() {

  var links = document.getElementsByTagName('a');
  for (var i = links.length; i != 0; i--) {
	var a = links[i-1];
	if (!a.href) continue;

	if (a.href.indexOf('http') != -1 &&
			a.href.indexOf(window.location.hostname) == -1 &&
	  !excludeUrl(a.href)
		) {
		a.target = "_blank";

	}
  }
}

function excludeUrl(url){
  var excludeUrls = Array(
			  'http://www.rwt.org'
			  );
  for(var l = 0; l < excludeUrls.length; l++){
	if(url.indexOf(excludeUrls[l]) == 0){
	  return true;
	}
  }

  return false;
}



