// This .js file must be called at the very first opportunity on each page
var startTime = (new Date()).getTime();	// Start the timer as soon as possible
var strSearch = document.location.search;
var strSessionReferrer = '';
var intPageNo = 0;	
var intPageSkips = 0;
var strDomainName = getDomainName();
var strCookie = document.cookie;
var isLandingPage = setIsLandingPage();
var flt30Mins = 0.5/24;

	// Called before s_code file loaded so s.* functions and plug-ins not available
function setIsLandingPage() {
	try { var strPreviousPage = unescape(strCookie.match(/;*vkiPreviousPage=([^;]*)/)[1]) } catch (e){};
	strCookie = vkiSetCookie( 'vkiPreviousPage', document.location.href, 30, '/', strDomainName, '');

	var strReferrer = unescape(document.referrer ? document.referrer : 'Direct');

		// setIsLandingPage determined only by HTTP.
		// Visit definition: 30 minutes inactivity or 12 hours of continuous activity (12 hours not catered for here)
		// 30 minute cookie = vki30currentReferrer
	var isCookieMissing = (strCookie.search(/vki30currentReferrer=/) == -1);

		// Session cookie=vkiSessionReferrer; - stores the referrer of the visit (only written once per session)
	if (isCookieMissing || strCookie.search(/vkiSessionReferrer=/) == -1) {
		strCookie = vkiSetCookie( 'vkiSessionReferrer', strReferrer, 30, '/', strDomainName, ''); 
		strSessionReferrer = strReferrer;
		isCookieMissing = true;
	} else {
		strSessionReferrer = unescape(document.cookie.match(/;*vkiSessionReferrer=([^;]*)/)[1]);
	}
		// 30 minute cookie = vki30currentReferrer - rewrite on every page to keep cookie alive for 30 mins of inactivity
		// stores the referrer for the current page
	strCookie = vkiSetCookie( 'vki30currentReferrer', strReferrer, 30, '/', strDomainName, '');

		// to deal with diff between 30 min cookies and session cookies to determine if visit has ended
		// vki_* cookies are session cookies but deleted here if 30 mins have passed
	if (isCookieMissing)  {
			// Keep all cookies in sync - if the session has ended, kill the visit-level cookies
		strCookie = vkiSetCookie('vki_eVar32_HTTPSessionReferrer', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('vkiSerialNumber', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('vki_LastPageNo', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('vki_TotalTime', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('vki_TrackedPages', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('gpv_currentPage', '', -1, '/', strDomainName, '');
		strCookie = vkiSetCookie('vki_PageNo', ++intPageNo, 30, '/', strDomainName, '');	// =1
	}
	else {
		try { intPageNo = parseInt(strCookie.match(/;*vki_PageNo=([^;]*)/)[1]) } catch (e){intPageNo = -2;};
		strCookie = vkiSetCookie('vki_PageNo', ++intPageNo, 30, '/', strDomainName, ''); // increment then save
	}
		
	return isCookieMissing;
}

/*
	eVars and events used in this code in VKI's sandbox report suite
eVar32    	HTTP Session Referrer
eVar33   	True Page Number in Visit
eVar34   	(spare) Skipped Pages Count
eVar35   	Pages Skipping SC
eVar36   	Load Time Histogram
eVar37   	Average Load Times
	e.g. if lngPageLoadTime = 2.9secs and intResolutionSeconds  = 2,   then eVar36 repoted as "2 < 3"
	e.g. if lngPageLoadTime = 3.9secs and intResolutionSeconds  = 2,   then eVar36 repoted as "3 < 4"

event21	Visit Events 
event22	Load Times
event23	Landing Page Skips
event24	Previous Page Skips (not including landing page skips)
*/


	// Runs immediately before the call to s.t(), usually after all s. fields have been populated
	// call to s.t() looks something like  "s_code=s.t();if(s_code)document.write(s_code)"
	// s_code file will already have been loaded so s object, plugins and functions are available
function sc_reportReferrers() {

		// Only for calculating avg load times
	var intTrackedPages = parseInt(s.c_r('vki_TrackedPages')) || 0;
	strCookie = vkiSetCookie( 'vki_TrackedPages', ++intTrackedPages, 30, '/', strDomainName, '');

	s.eVar33 = intPageNo;
	s.events = s.apl(s.events, 'event9', ','); // Page View Events - will be moved to s_code later
	
	var intRand = Math.ceil(Math.random()*10000)
	
		// event21:Visit Events: limit 1 per browser by logic - use vki_eVar32_HTTPSessionReferrer cookie to test
	if (document.cookie.search(/;*vki_eVar32_HTTPSessionReferrer=([^;]*)/) == -1) s.events = s.apl(s.events, 'event21', ',');
	
		// eVar32    	HTTP Session Referrer
		// getValOnce only lets it be set if its the 1st time since otherwise it returns ""
	s.eVar32 = s.getValOnce(strSessionReferrer, 'vki_eVar32_HTTPSessionReferrer', flt30Mins);
//	s.eVar1 = 	s.eVar32;				- only for VKI testing *
//	s.eVar2 = 	Math.random()*10000;	- only for VKI testing *
	
		// Landing Page Skips - 
		//If sc has just set s.eVar32 but its not the landing page - append event23 to s.events to count a skipped LP
	if (!isLandingPage && s.eVar32) {
		s.events = s.apl(s.events, 'event23', ',');
	}
	
		// use spare s.eVar34 to track if any multiple page skips
	var intLastPageNo = parseInt(s.c_r('vki_LastPageNo'));
	var intPageSkips = intPageNo-intLastPageNo-1;
	s.eVar34 = (intLastPageNo > 0 && intPageSkips > 0) ? intPageSkips : 0;
	
	strCookie = vkiSetCookie( 'vki_LastPageNo', intPageNo, 30, '/', strDomainName, '');

	// test if previous page (not a landing page) lost tracking
	try {
		strCurrentReferrer = unescape(document.cookie.match(/;*vki30currentReferrer=([^;]*)/)[1]);
			// s.getPreviousValue will return the previous value and write the current value.
			// the previous value should be the current page's referrer (if not direct or external)
		var strPreviousHref = unescape(s.getPreviousValue(document.location.href,"gpv_currentPage",""));
		if (strCurrentReferrer !== strPreviousHref && !isLandingPage && !s.eVar32) {
				// s.eVar35 = Pages Skipping SC. 
			s.eVar35 = strCurrentReferrer; // record the href that did not run the SC code
				//	s.eVar6 = 	s.eVar35;	- only for VKI testing *
				// this could happen any number of times per visit
			s.events = s.apl(s.events, 'event24', ',');
		}
	} catch (e) {s.eVar35 = "vki30currentReferrer cookie not being set"}

	var intResolutionSeconds = 3;
 	var intMaxSeconds = 45;
	var endTime = (new Date()).getTime();

 	var lngPageLoadTime = (endTime - startTime);
 	var fltSecs = (lngPageLoadTime/1000);
	
	lngPageLoadTime = fltSecs-(fltSecs % intResolutionSeconds);

		// some timings being reported as < 0 !!! 
	if (lngPageLoadTime >= 0) {
		s.eVar36 = (lngPageLoadTime > intMaxSeconds ?
					intMaxSeconds + 's':
					lngPageLoadTime + 's to ' + (lngPageLoadTime+intResolutionSeconds-0.1)  + 's'
					);
			// Running total of load times to calculate average
		var intTotalTime = parseFloat(s.c_r('vki_TotalTime')) || 0;
		intTotalTime += fltSecs;
		strCookie = vkiSetCookie( 'vki_TotalTime', intTotalTime, 30, '/', strDomainName, '');
		
			// accumulate load times in incrementor event - can be used in a calc metric to calc avg load times
		s.events = s.apl(s.events, 'event22', ','); 
		s.products = ';;;;event22=' + fltSecs;
		
		var intAvgLoadTime = Math.floor(intTotalTime/intTrackedPages);
		intAvgLoadTime = intAvgLoadTime-(intAvgLoadTime%intResolutionSeconds);
		s.eVar37 = (intAvgLoadTime > intMaxSeconds ?
					intMaxSeconds + 's':
					intAvgLoadTime + 's to ' + (intAvgLoadTime+intResolutionSeconds-0.1)  + 's'
					);
	}
	else	// lets find out which ones those are
		s.eVar36 = lngPageLoadTime + '|' + s.pageName ;

}

function vkiSetCookie( name, value, expiresMinutes, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	expiresMinutes = expiresMinutes * 1000 * 60;
	var expires_date = new Date( today.getTime() + (expiresMinutes) );

	document.cookie = name + "=" +escape( value ) +
	( ( expiresMinutes ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );

	strCookie = unescape(document.cookie);
	return strCookie
}

function vkiSetCookieIfNone( name, value, expiresMinutes, path, domain, secure ) {
	var strValue;
	var strPattern = ";*" + name + "=([^;]*)";
	try {
		strValue = document.cookie.match(strPattern)[1];
	}
	catch (e) {
		strValue = value;
	}
		//refresh the cookie
	strCookie = vkiSetCookie( name, strValue, expiresMinutes, path, domain, secure );

	return strValue;
}

function getDomainName(strHostName) {
	strHostName = strHostName ? strHostName : document.location.hostname;

	if(strHostName.match(/(\d+\.){3}(\d+\.)/)) return strHostName;	// ipaddress
	if(strHostName.search(/(\.)/) == -1) return strHostName;	// probably localhost
	strHostName = strHostName.match(/(?:[^.]+\.)*([^.]+\.[^.]+)/)[1];
	return  strHostName;
}
