var tseanalytics = {
	
	track: function(appid,acctid,siteid,sectionid,userid,assetid){
		var loc = document.location.href;
	    var ref = document.referrer;
		tseanalytics.trackHit(loc,ref,appid,acctid,siteid,sectionid,userid,assetid);
	},
	
	trackClick: function(loc,appid,acctid,siteid,sectionid,userid,assetid){
	    var ref = document.location.href;
		tseanalytics.trackHit(loc,ref,appid,acctid,siteid,sectionid,userid,assetid);
	},
	
	trackHit: function(loc,ref,appid,acctid,siteid,sectionid,userid,assetid) {	
	    var days = 7; // Number of days to keep cookie alive
		var qs = '';
		
		if( loc.length > 0 ) {
	        if( ref != '' ) {
	            ref = tseanalytics.urlencode( ref );
	        }
			
	        // If there's a query string, grab it and stick all the parameters on the end.
	        var spliturl = loc.split( '?' );
	        if( spliturl.length > 1 ) {
	            qs = spliturl[ 1 ];
	        }
			
	        loc = tseanalytics.urlencode( loc );
			ref = tseanalytics.urlencode( ref );
			
	        var clicked_time = new Date();
	        clicked_time = Math.round(clicked_time.getTime()/1000);
	
	        // Build data.
	        var d = 'ref=' + ref;
			if( loc.length > 0 ) {
	            d += '&loc=' + loc;
	        }
	        /*if( qs.length > 0 ) {
				qs = tseanalytics.urlencode( qs );
	            d += '&qs=' + qs;
	        }*/
	        d += '&ct=' + clicked_time;
			
	        // If the cookie already exists for this bonus code, this isn't a unique hit
	        var unique = 1;
			var cookieValue;
			
	        var old_cookie = tseanalytics.readCookie( 'analytics_unique' );
	        if( old_cookie != null && old_cookie != "" ) {
	            unique = 0;
				cookieValue = old_cookie;
	        }
			else
				cookieValue = (new Date()).getTime() + '_' + tseanalytics.randNums(5);
			
	        // Set cookie.
			
	        tseanalytics.setCookie( 'analytics_unique', cookieValue, days, '/' ); // For uniqueness
	        d += '&u=' + unique;
			d += '&cid=' + cookieValue;
			
			// Add extra data passed
			d += typeof(appid) != 'undefined' ? '&appid='+appid : '';
			d += typeof(acctid) != 'undefined' ? '&acctid='+acctid : '';
			d += typeof(siteid) != 'undefined' ? '&siteid='+siteid : '';
			d += typeof(sectionid) != 'undefined' ? '&sectionid='+sectionid: '';
			d += typeof(userid) != 'undefined' ? '&userid='+userid : '';
			d += typeof(assetid) != 'undefined' ? '&assetid='+assetid : '';
			
			var imageURL = wa_url + '?' + d;
			
	        // Now request the 1x1 pixel gif to record the click.
	        var timage = new Image();
			timage.src = imageURL;
			
			// pause request to allow time for image load request to be triggered before continuing
			tseanalytics.pauseRequest(100);		
	    }
	    return true;
	},
	
	randNums: function(length){
		var num = '';
		for(var i=0; i <= length; i++){
			num += Math.floor(Math.random()*10);
		}
		return num;
	},
	
	pauseRequest: function(mstimelimit){
		var startDate = new Date();
		for(var i=0; i>=0; i++){
			if (i % 100 == 0){
				if ((new Date()) - startDate > mstimelimit) {
					break;
				}
			}
		}
	},
	
	isExternalAddress: function(addr,currentdomain){
		// compare document domain to link domain
		var urlcheck = new RegExp('^[a-z]+://([^/]+)(/|$)');
		if(!urlcheck.test(addr) )
			// if doesn't have url prefix and domain then must be internal
			return false;
		else if(addr.split('/')[2] == currentdomain)
			// if address's domain is same as current domain then internal
			return false;
		else
			return true;		
	},
	
	addOnClickTracking: function(includeOutbound,appid,acctid,siteid,sectionid,userid,assetid){
		// set argument defaults
		includeOutbound = typeof(includeOutbound) == 'boolean' ? includeOutbound : false;
		
		// extensions of documents links to be tracked
		var docext=[];
		var link;
		
		docext[0] = 'doc';
		docext[1] = 'pdf';
		docext[2] = 'xls';
		
		if(!Array.indexOf){
		    Array.prototype.indexOf = function(obj){
		        for(var i=0; i<this.length; i++){
		            if(this[i]==obj){
		                return i;
		            }
		        }
		        return -1;
		    }
		}
		
		for(var i=0;i<document.links.length;i++){
			link = document.links[i];
			if ((!tseanalytics.isExternalAddress(link.href,document.domain) && docext.indexOf(tseanalytics.getFileExt) != -1)
					|| (tseanalytics.isExternalAddress(link.href,document.domain) && includeOutbound)){
				if (!link.onclick)	
					link.onclick = function(){ tseanalytics.trackClick(this.href,appid,acctid,siteid,sectionid,userid,assetid) };
			}
		}
	},
	
	setCookie: function( name, value, days, path ) {
	    var date = new Date();
	    date.setTime( date.getTime() + ( days*24*60*60*1000 ) );
	    var expires = "; expires=" + date.toGMTString();
	    document.cookie = name + '=' + value + expires + '; path=' + path;
	},
	
	readCookie: function(cookieName) {
	    var theCookie=""+document.cookie;
	    var ind=theCookie.indexOf(cookieName);
	    if (ind==-1 || cookieName=="") return "";
	    var ind1=theCookie.indexOf(';',ind);
	    if (ind1==-1) ind1=theCookie.length;
	    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	},
	
	deleteCookie: function( cookieName ) {
	    if( tseanalytics.readCookie( cookieName ) ) {
	        tseanalytics.setCookie( cookieName, '', 0, '/' );
	    }
	},
	
	urlencode: function(str) {
	    str = escape(str);
	    str = str.replace(/\+/g, '%2B');
	    str = str.replace(/%20/g, '+');
	    str = str.replace(/\*/g, '%2A');
	    str = str.replace(/\//g, '%2F');
	    str = str.replace(/@/g, '%40');
	    return str;
	},
	
	getFileExt: function(addr){
		var hrefbase = addr.split('?')[0];
		return hrefbase.search(/\.\w+$/) != -1 ? hrefbase.match(/\.\w+$/)[0].slice(1) : ''; 
	}
}
