//TL Dynamic Response v1.42 Standalone
//last modified 12/01/2009
//parnaudov@technologyleaders.com
// modified by dsmith@technologyleaders.com
// Insert this file in the <head> section of the page and
// where your analytics server object is set up call drAnalytics with
// the analytics object as follows.
// For WebTrends: drAnalytics(_tag);
// For Omniture: drAnalytics(s);
// For Google: drAnalytics(pageTracker);

// This should be done before the server call itself is sent.

function DynRes() {

	// begin: user modifiable

	this.enabled=true;

	//click-to-bottom cookie name
	this.c2b='C2B';

	//visit rollup cookie name
	this.vrc='VRC';

	//abandon page load cookie name
	this.apl='APL';


	//WebTrends parameters names

	this.wt = {
			vars:{
			apl:"WT.z_apl",// = 1 if aborted page
			plt:"WT.z_plt", //DT.plt = page load time in seconds.00
			plg:"WT.z_plg", //DT.plg - page load time time grop
			rtt: "WT.z_rtt", //DT.rtt = page round trip time (to bottom)
			rtg: "WT.z_rtg", //DT.rtg = page round trip time grup
			aplt:"WT.z_aplt",//DT.aplt = average page load time this visit
			aplg:"WT.z_aplg",//DT.aplg = average page load time group
			artt: "WT.z_artt",//DT.artt = average page round trip time (to bottom)
			artg:"WT.z_artg"//DT.artg = average page round trip time grup
			}
	}
	// Google parameter names

	this.google = {
			events:{
			apl:"Aborted Page", // = 1 if aborted page
			plt:"Page Load Time",  //DT.plg - page load time time grop
			rtt: "Round Trip Time" //DT.rtg = page round trip time grup
		},
		vars:{
			aplg:"Average Page Load Time", //DT.aplg = average page load time group
			artg:"Average Round Trip Time" //DT.artg = average page round trip time grup
		}
	};
	// Omniture parameter names defined here

	this.omtr = {
			events: {
				apl:["event5"], // = 1 if aborted page
				plt:["event2","event4"],  //DT.plt = page load time in seconds.00
				rtt: ["event1","event3"]  //DT.rtt = page round trip time (to bottom)
				},
			vars: {
				plg:["prop44","eVar44"],  //DT.plg - page load time time grop
				rtg: ["prop43","eVar43"], //DT.rtg = page round trip time grup
				aplg:["prop45","eVar45"], //DT.aplg = average page load time group
				artg:["prop46","eVar46"] //DT.artg = average page round trip time grup
				}
	};
	// Click-to-Bottom response time buckets (in second fractions) defined here.
	this.rtt = [

	['Fast',    '0', '1'],
        ['Medium', '1', '4'],
        ['Slow',    '4', '60']

	];

	// Top-to-Bottom loading time buckets (in second fractions) defined here.\
	this.plt = [

	['Fast',    '0',   '0.5'],
 	['Medium', '0.5', '4'],
	['Slow',    '4',   '60']

	];

	// end: user modifiable
	// Variables:
	//DT.apl = 1 if aborted page
	//DT.plt = page load time in seconds.00
	//DT.plg - page load time time group
	//DT.rtt = page round trip time (to bottom)
	//DT.rtg = page round trip time group
	//DT.aplt = average page load time this visit
	//DT.aplg = average page load time group
	//DT.artt = average page round trip time (to bottom)
	//DT.artg = average page round trip time group

	this.DT={};
	this.top = new Date();
	this.bottom=null;
	this.abortPage="";
	this.abortTitle="";
	setTimeout("_dr.drCollect()",(this.plt[this.plt.length-1][2]+1)*1000);
}
DynRes.prototype.drGetCookie=function(A){
	var nameEQ = A + "=";
	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(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
DynRes.prototype.drWriteCookie=function(C, D, A){
    var B = "";
    if (A != null) {
        B = new Date((new Date()).getTime() + A * 1000);
        B = "; expires=" + B.toGMTString()
    }
    document.cookie = C + "=" + D + B + ";path=/;"
}
DynRes.prototype.createDeltaCookie=function(href) {
	var time = new Date();
	if (href) var dc = this.c2b+"="+href.replace(/http\:\/\//g,"")+"|"+time.getTime()+";path=/";
	if (dc) document.cookie = dc;
}
DynRes.prototype.deleteCookie=function(A) {
	if (this.drGetCookie(A) )
    		document.cookie = A+"=;expires=Thu, 01-Jan-1970 00:00:01 GMT;path=/";
}
DynRes.prototype.drSetup=function() {
	var a = this.drGetCookie(this.apl);
	if (a) { this.DT.apl=1; this.abortTitle=a; this.abortPage=document.referrer;this.deleteCookie(this.apl); };

	var c = this.drGetCookie(this.c2b);
	if (!c) return;

	if (c.indexOf("|")!=-1)
	    var cts = c.split("|");
	else if (c)
	    this.deleteCookie(this.c2b);
	else
	    return;

	if (cts[0] && cts[1]) {
	   if(window.location.href.indexOf(cts[0])==-1)
		this.deleteCookie(this.c2b);
	}


}
DynRes.prototype.trackClick=function(evt) {
	evt = evt||(window.event||"");
	if (evt) {
		var e = this.drEvt(evt, "A");
		if ( typeof(e) != 'undefined' && e) {
			if (e.href && e.href.indexOf(window.location.hostname)==-1) {
				//alert ("Detected site exit from link. Aborting");
				this.deleteCookie(this.c2b);
			}
			else if (e.href) {
				//alert("creating C2B cookie");
				this.createDeltaCookie(e.href);
			}
		} // end if e
	} // end if evt
}
DynRes.prototype.drBind=function(event,func){
	if ((typeof(func)=="function")&&document.body){
		if (document.body.addEventListener){
			document.body.addEventListener(event, func.fnbind(this), true);
		}
		else if(document.body.attachEvent){
			document.body.attachEvent("on"+event, func.fnbind(this));
		}
	}
}

DynRes.prototype.drEvt=function(evt,tag){
	var e=evt.target||evt.srcElement;
	while (e.tagName&&(e.tagName!=tag)){
		e=e.parentElement||e.parentNode;
	}
	return e;
}
DynRes.prototype.setSpeedGroup=function(A, B) {

			for (t=0;t<this.plt.length;t++) {

				if (B[t][1] <= A && A <= B[t][2])
					return B[t][0]+" ("+B[t][1]+"-"+B[t][2]+" sec.)";

				if (t==B.length-1 && A > B[t][2])
					return "Slow beyond Range ("+B[t][1]+"+ sec.)";

			}
}
DynRes.prototype.checkDelta=function() {
		if (this.top) {
		    this.bottom = new Date();
		    this.DT.plt = roundN((this.bottom-this.top) / 1000, 2);
		    this.DT.plg = this.setSpeedGroup(this.DT.plt, this.plt);
		    this.top="";
		}  //end top-to-bottom eval

		var c = this.drGetCookie(this.c2b);
		this.deleteCookie(this.c2b);

		if (c && c.indexOf("|")!=-1)
		    var cts = c.split("|");
		else if (c) //corrupt cookie
	    	    this.deleteCookie(this.c2b);
		else return;

		if (cts[0] && cts[1] && window.location.href.indexOf(cts[0])!=-1) {
			var now = new Date();
			var delta = now - cts[1];
		    	this.DT.rtt = roundN(delta / 1000, 2);
			this.DT.rtg = this.setSpeedGroup(this.DT.rtt, this.rtt);
	   	}
}

DynRes.prototype.rollupVisit=function() {

		var c = this.drGetCookie(this.vrc);
		if (c && c.indexOf("|")!=-1) var a = c.split("|");
		else if (c) this.deleteCookie(this.vrc);

		if (a && this.DT.plt) {
			var t = a[0]*a[1];a[0]++;a[1]=roundN((t+this.DT.plt)/a[0], 2);
				if (a[0] > 3)
					{ this.DT.aplt = a[1]; this.DT.aplg = this.setSpeedGroup(a[1], this.plt); }
		}
		if (a && this.DT.rtt) {
			var t = a[2]*a[3];a[2]++;a[3]=roundN((t+this.DT.rtt)/a[2], 2);
				if (a[2] > 3)
					{ this.DT.artt = a[3]; this.DT.artg = this.setSpeedGroup(a[3], this.rtt); }
		}

		if (!a) {
			var a = new Array();
			a[0]=this.DT.plt?'1':'0';
			a[1]=this.DT.plt?this.DT.plt:'0';
			a[2]=this.DT.rtt?'1':'0';
			a[3]=this.DT.rtt?this.DT.rtt:'0';
		}

		a = a.join('|');
		this.drWriteCookie(this.vrc, a, 1800);


}

Function.prototype.fnbind = function(obj){
	var method=this;
	var temp=function(){
		return method.apply(obj,arguments);
	};
	return temp;
}
function roundN(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}
//tracks page abandonment & potential site return via cookie
DynRes.prototype.drTrackLeave=function() {
	if (this.bottom) return;
	this.DT.apl=1;
	this.drWriteCookie(this.apl, document.title, 1800);
}
// after data collection, set up event listeners for click-to-load tracking
DynRes.prototype.drBeginListen=function() {
	var e=(navigator.appVersion.indexOf("MSIE")!=-1)?"click":"mousedown";
	this.drBind(e,this.trackClick);
}
//Main Data Collection wrapper for WT dcsCollect and GA trackPageview
DynRes.prototype.drCollect=function(){
    if (this.enabled){
    	this.enabled=false;
	  this.checkDelta();
	  this.rollupVisit();
	  this.sendAnalytics();
	  this.deleteCookie(this.apl); // IF the analytics were sent successfully after an abort, drop the cookie
    }
}

// Common code to insert into analytics object
// This will place the collector object into three places:
// 1) in teh onload event
// 2) in the onunload (or beginunload) event
// 3) in a timer event based on the highest time in the histogram table
//
//  The first one to fire will send teh server call and cancel the rest
//

DynRes.prototype.setAnalytics = function (collector) {
	if ("WT" in collector ||  (typeof WT == "object" && collector == WT)) { // It's webtrends
		this.wt.analytics = collector;
	}  else if ("trackingServer" in collector) { // Omniture
		this.omtr.analytics=collector;
	}else if ("_setVar" in collector && typeof collector._setVar == "function") { // Google
		this.google.analytics=collector;
		this.google.tracker=collector._createEventTracker("Dynamic Response");
	}
}
DynRes.prototype.sendAnalytics=function() {
	// don't fire this yet this.drCollect();
	if (typeof this.wt.analytics == "object") { // It's new webtrends
		var vnd = this.wt.vars;
		for (parm in vnd) {
			if (this.DT[parm]) {
				var wtvars = vnd[parm].split(".");
				this.wt.analytics[wtvars[0]][wtvars[1]] = this.DT[parm];
			}
		}
		if (this.DT.apl==1 && this.abortPage!="") {
			var curPage = this.wt.analytics.DCS.dcsuri;
			var curTitle=this.wt.analytics.WT.ti;
			this.wt.analytics.DCS.dcsuri = this.abortPage;
			this.wt.analytics.WT.ti=this.abortTitle;

			// send the abort page
			if (typeof this.wt.analytics.dcsCollect == "function") {
				this.wt.analytics.dcsCollect();
			} else if (typeof dcsTag == "function")  {
				dcsTag();
			}
			this.wt.analyti
			cs.DCS.dcsuri =curPage;
			this.wt.analytics.WT.ti = curTitle;
		}
		if (typeof this.wt.analytics.dcsCollect == "function") {
			this.wt.analytics.dcsCollect();
		} else if (typeof dcsTag == "function")  {
			dcsTag();
		}
	}
	if (typeof this.omtr.analytics=="object") { // Omniture
		if (this.DT.apl==1 && this.abortPage!="") {
			var curPage = this.omtr.analytics.pageName;
			this.omtr.analytics.pageName=this.abortTitle;
			var events=this.omtr.analytics.events;
			var products = this.omtr.analytics.products;
			this.omtr.analytics.events = this.omtr.events.apl;
			this.omtr.analytics.products="";
			var scode = this.omtr.analytics.t();if (scode)document.write(scode);
			this.omtr.analytics.events=events;
			this.omtr.analytics.products=products;
			this.omtr.analytics.pageName=curPage;
			this.DT.apl==null;
		}
		var vnd = this.omtr.events;
		for (parm in vnd) {
			if ( typeof vnd[parm] == "object" && this.DT[parm] ) {
				if (this.omtr.analytics.events == 'undefined' || typeof this.omtr.analytics.events == 'undefined')
					this.omtr.analytics.events=vnd[parm][0];
				else this.omtr.analytics.events+=","+vnd[parm][0];
				if (vnd[parm].length==2) {
					this.omtr.analytics.events+=","+vnd[parm][1];
					var t = vnd[parm][0]+"="+this.DT[parm];
					if (this.omtr.analytics.products == 'undefined' || typeof this.omtr.analytics.products == 'undefined')
						this.omtr.analytics.products=";;;;"+t;
					else if (this.omtr.analytics.products.indexOf("event")!=-1) {
						this.omtr.analytics.products+="|"+t;
					} else this.omtr.analytics.products+=t;
				}
			}
		}
		vnd = this.omtr.vars
		for ( parm in vnd) {
			if (vnd[parm]!="" && this.DT[parm]  ){
				for  (prop in parm) {
					this.omtr.analytics[vnd[parm][prop]]=this.DT[parm];
				}
			}
		}
		var scode = this.omtr.analytics.t();if (scode)document.write(scode);

	}
	if (typeof this.google.analytics == "object") { // Google
		if (this.DT.artg) this.google.analytics._setCustomVar(1,this.google.vars.artg,this.DT.artg,2);
		if (this.DT.aplg) this.google.analytics._setCustomVar(2,this.google.vars.aplg,this.DT.aplg,2);

		this.google.analytics._trackPageview();

		if (this.DT.apl==1 && this.abortPage=="") {
			this.google.analytics._trackEvent("Dynamic Response",this.google.events.apl,document.URL);

		} else {
			if (this.DT.rtt) this.google.tracker._trackEvent(this.google.events.rtt,document.URL,roundN(this.DT.rtt,0));
			if (this.DT.plt) this.google.tracker._trackEvent(this.google.events.plt,document.URL,roundN(this.DT.plt,0));
			if (this.DT.apl==1) this.google.tracker._trackEvent(this.google.events.apl,this.abortPage,1);
		}

	}
	return;
}


if (typeof window.attachEvent != "undefined") {
	 document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
	  var contentloadtag=document.getElementById("contentloadtag");
	  contentloadtag.onreadystatechange=function(){
	    if (this.readyState=="complete"){
	     _dr.drBeginListen();
	    }
	  }

    	window.attachEvent("onload", function(){_dr.drBeginListen();_dr.drCollect()});
    	window.attachEvent("onbeforeunload",function(){ _dr.drTrackLeave();_dr.drCollect();});
}
else if (typeof window.addEventListener != "undefined") {
		document.addEventListener("DOMContentLoaded",
				function(){
					_dr.drBeginListen();
				}, false)
        window.addEventListener("load",
        		function(){
        			_dr.drBeginListen();
        			_dr.drCollect()
        		}, false);
        window.addEventListener("unload", function(){
        	_dr.drTrackLeave();
        	_dr.drCollect();
        	}, false);
}

//insert the following to start the code:

//init delta object
var _dr=new DynRes();

//early check and clean to avoid on-site navigate away-return
_dr.drSetup();
_dr.drBeginListen();
//event listeners

