﻿//	This javascript tags file downloads and external links in Google Analytics.
//	You need to be using the Google Analytics New Tracking Code (ga.js) 
//	for this script to work.
//	To use, place this file on all pages just above the Google Analytics tracking code.
//	All links to DocumentViewer.aspx files should now be automatically tracked.
//  Also I call Todd's code to track the link clicks in database

//	This script has been provided by Goodwebpractices.com
//	Thanks to ShoreTel, MerryMan and Colm McBarron
//	www.goodwebpractices.com

$(function () {
    if (document.getElementsByTagName) {
        var hrefs = document.getElementsByTagName("a");
        for (var l = 0; l < hrefs.length; l++) {
            try {
                if (hrefs[l].hostname == location.host) {
                    var path = hrefs[l].pathname + hrefs[l].search;
                    var isDoc = path.match(/(?:DocumentViewer)/i);
                    if (isDoc) {
                        startListening(hrefs[l], "click", trackExternalLinks);
                    }
                } else {
                    startListening(hrefs[l], "click", trackExternalLinks);
                }
            }
            catch (e) {
                continue;
            }
        }
    }
});
//$(function () {
//    $('a[href*="DocumentViewer"]').click(function () {
//        alert("h");
//        pageTracker._trackPageview($(this).attr("href"));
//        gp_trackDocument($(this).attr("href"));
//    });
//});

function startListening (obj,evnt,func) {
    if (obj.addEventListener) {
        obj.addEventListener(evnt,func,false);
    } else if (obj.attachEvent) {        
        obj.attachEvent("on" + evnt,func);
    }
}

function trackExternalLinks (evnt) {            
    var e = (evnt.srcElement) ? evnt.srcElement : this;
    while (e.tagName != "A") {
            e = e.parentNode;
    }
    var lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname;
    if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search;
    if (e.hostname != location.host) lnk = "/external/" + e.hostname + lnk;        
    if (typeof(pageTracker) == "object") {        
        pageTracker._trackPageview(lnk);             
    }
    gp_trackDocument(lnk);
}
//Todd Tingen's code to track documents
var trackUrl = "/build/Tracker.aspx";
var app = "Build";

function gp_trackPageView(pageName) {
    gp_track(getPage(pageName));  
}
function gp_trackClick(pageName, linkClicked) {
    var qs = (getPage(pageName) + "&l=" + escape(linkClicked));
    gp_track(qs);
}
function gp_trackDocument(pageName) {
    //try {
        var qs = (getPage(pageName));
        gp_track(qs);
    //} catch (e) {}
}
function getPage(pn) {
    return ("a=Build&p=" + escape(pn));
}
function gp_track(qs) {
    var img = new Image(1,1);
    img.onLoad = function() { foo(); };
    img.src = trackUrl + "?" + qs;
}
function foo() { return true; }
