/**
 * Web page load tracking javascript
 * measures the real round trip time in milliseconds
 * between a klick on a link until the next page is fully loaded
 * as experienced by the user / browser
 *
 * Compress with yuicompressor before deploying
 */


// Create the rttTracker object.
// This is the one and only interface which is accessed from the XHTML documents.
if ("undefined" === typeof(rttTracker) && "undefined" === typeof(this.rttTracker)) {
	this.rttTracker = {
		// Constants. Adjust to your site
		COOKIE_NAME:    "rtt_ts",
		TRACK_URL:		"/pageloadrtt.gif",

		// we overwrite this method to provide an IE workaround
		addEventListener: function(node, type, listener, useCapture) {
			if ("function" !== typeof(node.addEventListener)) {
				if (node.attachEvent) {
					node.attachEvent("on" + type, listener);
				}
			} else {
				node.addEventListener(type, listener, useCapture);
			}
		},

		onLinkClick: function(ev) {
			// set the path to the target URL of the clicked link if possible
			// to avoid wrong tracking and cookies being sent unecessary 
			if(!ev) ev=window.event;
			var target = ev.target || ev.srcElement;
			var path = '/';
			if(target.pathname) {
				path = target.pathname;
			}
			// when someone clicks a link, take the timestamp and store it in cookie
			// be nice and set a limited TTL for the cookie, slightly above one hour to allow for wrong clocks
			var exp = new Date((new Date()).getTime() +3900000);
			document.cookie = rttTracker.COOKIE_NAME+'='+(new Date()).getTime()+'; path='+path+'; expires='+exp.toGMTString()+';';
		},

		onPageLoaded: function() {
			// if we already have a cookie, calculate page load time and ping it to tracking pixel
			if(document.cookie) {
				var cname = rttTracker.COOKIE_NAME+'=';
				var cvalue ='';
				var ca = document.cookie.split(';');
				for(var i=0;i < ca.length;i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
						if (c.indexOf(cname) == 0) {
							cvalue=c.substring(cname.length,c.length);
						}
					}
				var diff = (new Date()).getTime()-parseInt(cvalue);
				var trackingpixel = (new Image()).src = rttTracker.TRACK_URL + '?u=' + window.location + '&t=' + diff;
			}

			// attach ourselves to all anchors/links on page
			var alinks = document.getElementsByTagName('a');
			for(var i=0; i < alinks.length; i++) {
				// we only attach to links leading to our domain, since we can't track and don't care about external links
				if(alinks[i].hostname == window.location.hostname) {
					rttTracker.addEventListener(alinks[i],"click", function(ev) { rttTracker.onLinkClick(ev); }, false);
				}
			}
		},
	};

	// setup and register events
	rttTracker.addEventListener(window,"load", function() { rttTracker.onPageLoaded(); }, false);
}


