var host = location.host.toLowerCase()

function addLinkTracker()
{
	//if (!document.getElementsByTagName) return false;
	//linksElements = document.getElementsByTagName('a')
	var len = document.links.length;
	for (var i = 0; i < len; i++) 
	{
	  var link = document.links[i];
	  var href = link.href;
	  if (href.indexOf(host) == -1
		  && href.indexOf("javascript:") == -1 && href.indexOf("mailto:") == -1
		  && href.indexOf("adserver.adtech") == -1 && href.indexOf("google") == -1)
	  {
	    addEvent(link, 'mousedown', recordClick, false);
	    //Pass all the links to the redirect.html to display now leaving IJ
	    if (link.getAttribute('href'))
	    {
	      link.href = "/Redirect.aspx?url=" + encodeURIComponent(href);
	      link.target = "_blank";
	    }
	  }
	}
}

//On mousedown, link is passed to addClick.asp using an ajax request
function recordClick(e)
{
	if (typeof e == 'undefined')
	var e = window.event;
	var source;

	if (typeof e.target != 'undefined') 
	{
		source = e.target;
	} else if (typeof e.srcElement != 'undefined') {
		source = e.srcElement;
  } 
	else {		return true;	}
	
	if (source.nodeType == 3)
		source = source.parentNode;

var target;

	//Hyperlinks around images, fonts 
	if(source.tagName == "IMG" || source.tagName == "FONT")
	{
		if( source.parentNode.tagName == "A" )
		  target = source.parentNode.getAttribute('href');
  }
	else{		target = source.getAttribute('href');	}
	
	var lastChar = target.charAt(target.length-1)
	//IE appends / to end of hyperlink. This removes it so that records are consistant 
	if(lastChar == '/')
	  target = target.slice(0, target.length - 1);

	target = target.replace("/redirect.htm?=", "")

	var response = 
        $.ajax({
          type: "POST",
          url: "../WebService/AjaxWS.asmx/TrackLinkClick",
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify({ pageUrl:document.location.href, clickedLink:target })
        });
	return false;	
}

//Function adds listeners to all the links
function addEvent(elm, evType, fn, useCapture) 
{
  //cross-browser event handling, there are 3 different standards 
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}

//On load calls addlinktracker which adds mousedown listeners to all links on the page
addEvent(window, 'load', addLinkTracker, false);
