/* Google Analytics tracking extension for redirection of the GA visit link in custom pageviews

   This script redirects the browser to a functional URL from the visit link in the GA user
   interface in cases where the tracked URL doesn't correspond to an actual, functional URL 
   (e.g. in the case of outgoing links or artificially categorised links such as file downloads)
   
   This file should be included in the page source before the main GA tracking code snippet. This
   is in order to avoid tracking an extra pageview in the tracked URL. This file must also be
   included in the 404 or resource not found error page of the site. Otherwise it will not work.
   
   In the majority of cases it is actually preferable that this file be included only on the 404
   error page of the site. (Because that's where the tracked custom URLs will lead)
*/

/* First check that the requested URL includes a http or https part without the following colon.
   This is how we track file download and outgoing links & forms since it's an almost fool-proof
   way to ensure that this redirection isn't triggered accidentally */ 

if ( document.location.href.match(/https?\/\//) ) {
  /* Further check that the requested URL includes one of the key phrases used in tracking these
     non-standard URLs */
  if ( document.location.href.match("/file-download/") ||
       document.location.href.match("/outgoing-link/") ||
       document.location.href.match("/outgoing-form/") ) {
    var GA_redirection_target_url = ""+document.location.href.match(/https?\/\/.*$/);
    GA_redirection_target_url = GA_redirection_target_url.split("//");
    GA_redirection_target_url = GA_redirection_target_url[0] + "://" + GA_redirection_target_url[1];
    document.location.replace(GA_redirection_target_url);
  }
}

