/* Configuration */
// Collector script location
var GRAP_IP_URL = "http://www.leadliaison.com/tracking_engine/grapIP.php";
var COLLECTOR_URL = "https://www.leadliaison.com/tracking_engine/trackEngine.php";
var ACTIVITY_URL = "https://www.leadliaison.com/tracking_engine/trackActivity.php";
blocked = false;
/* List of search query parameters for different engines */
var SEARCH_ENGINES = {
	a9 :"q",
	altavista :"q",
	aol :"query",
	ask :"q",
	dmoz :"search",
	google :"q",
	kanoodle :"query",
	msn :"q",
	teoma :"q",
	yahoo :"p"
};

/* GUID Generation */
function S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
			.toUpperCase();
}
function guid() {
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4()
			+ S4() + S4());
}

/* COOKIES */
var lluniqck = "lluniqck";

var llCookies = {
	init : function() {
		var allCookies = document.cookie.split('; ');
		for ( var i = 0; i < allCookies.length; i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		} else
			var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
		this[name] = value;
	},
	exist : function(name) {
		if (typeof (this[name]) == 'undefined') {
			return false;
		} else {
			return true;
		}
	},
	erase : function(name) {
		this.create(name, '', -1);
		this[name] = undefined;
	}
};
llCookies.init();

if (!llCookies.exist(lluniqck)) {
	llCookies.create(lluniqck, guid(), 3660);
}

/* Collect the data */
var data = {}

/*
 * SM - QueryString handler
 */
var QueryString = {
	init : function(qs) { // optionally pass a querystring to parse
		this.params = {};

		if (qs == null)
			qs = location.search.substring(1, location.search.length);
		if (qs.length == 0)
			return;

		// Turn <plus> back to <space>
		// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
		qs = qs.replace(/\+/g, ' ');
		var args = qs.split('&'); // parse out name/value pairs separated via
		// &

		// split out each name=value pair
		for ( var i = 0; i < args.length; i++) {
			var pair = args[i].split('=');
			var name = decodeURIComponent(pair[0]);

			var value;

			if (pair.length < 2)
				value = name;

			else if (pair.length == 2) {
				value = decodeURIComponent(pair[1]);
			} else {
				value = decodeURIComponent(pair[1]);
				for (j = 2; j < pair.length; j++)
					value += "=";

			}
			// value = (pair.length == 2)
			// ? decodeURIComponent(pair[1])
			// : name;

			this.params[name] = value;
		}
	},
	get : function(key, default_) {
		var value = this.params[key];
		return (value != null) ? value : default_;
	},
	contains : function(key) {
		var value = this.params[key];
		return (value != null);
	}
}

/* The connector id */
QueryString.init();
var llsubId_def = '0';
var llsubId = QueryString.get('llsubId', llsubId_def);
data.llsubId = llsubId;

var llstatId_def = '0';
var llstatId = QueryString.get('llstatId', llsubId_def);
data.llstatId = llstatId;

var llstatType_def = 'none';
var llstatType = QueryString.get('llstatType', llstatType_def);
data.llstatType = llstatType;

var outlookContactEmail_def = '';
var outlookContactEmail = QueryString.get('em', outlookContactEmail_def);
data.outlookContactEmail = outlookContactEmail;

var outlookContactName_def = '';
var outlookContactName = QueryString.get('cn', outlookContactName_def);
data.outlookContactName = outlookContactName;

var outlookEmailSubject_def = '';
var outlookEmailSubject = QueryString.get('sub', outlookEmailSubject_def);
data.outlookEmailSubject = outlookEmailSubject;

var outlookEmailDate_def = '';
var outlookEmailDate = QueryString.get('dt', outlookEmailDate_def);
data.outlookEmailDate = outlookEmailDate;

/* The page the user is visiting */
var tempPage = document.location.href;

// SM - have to remove the querystring parameter(s)
tempPage = tempPage.replace('&llsubId=' + llsubId, '');
tempPage = tempPage.replace('?llsubId=' + llsubId, '');

tempPage = tempPage.replace('&llstatId=' + llstatId, '');
tempPage = tempPage.replace('?llstatId=' + llstatId, '');

tempPage = tempPage.replace('&llstatType=' + llstatType, '');
tempPage = tempPage.replace('?llstatType=' + llstatType, '');

tempPage = tempPage.replace('&em=' + outlookContactEmail, '');
tempPage = tempPage.replace('?em=' + outlookContactEmail, '');

tempPage = tempPage.replace('&cn=' + outlookContactName, '');
tempPage = tempPage.replace('?cn=' + outlookContactName, '');

tempPage = tempPage.replace('&sub=' + outlookEmailSubject, '');
tempPage = tempPage.replace('?sub=' + outlookEmailSubject, '');

tempPage = tempPage.replace('&dt=' + outlookEmailDate, '');
tempPage = tempPage.replace('?dt=' + outlookEmailDate, '');

data.page = tempPage;

/* The domain name of the site */
data.domain = getDomain(document.location.href);

/* The refering page */
data.referrer = document.referrer;

/* The search engine terms/words used to find the page */
data.searchTerm = searchTerm(data.referrer, SEARCH_ENGINES);

/* The search engine */
data.searchEngine = searchEngine(data.referrer, SEARCH_ENGINES);

/* The customers id */
data.llcustid = llcustid;

/* The unique id */
data.lluniqck = llCookies[lluniqck];

function getBrowserType() {
	var agt = navigator.userAgent.toLowerCase();
	if (agt.indexOf("msie") != -1)
		return 'IE';
	if (agt.indexOf("chrome") != -1)
		return 'Chrome';
	if (agt.indexOf("opera") != -1)
		return 'Opera';
	if (agt.indexOf("safari") != -1)
		return 'Safari';
	if (agt.indexOf("firefox") != -1)
		return 'Firefox';
	if (agt.indexOf("mozilla") != -1)
		return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0, agt.indexOf('\/'));
		} else
			return 'Netscape';
	} else if (agt.indexOf(' ') != -1)
		return navigator.userAgent.substr(0, agt.indexOf(' '));
	else
		return navigator.appName;
}
var browser_type = getBrowserType();
var browser_version = navigator.appVersion;

data.brsr_t = browser_type;
data.brsr_v = browser_version;

/* SM - image to send data */
var img;

var updatedHit;

/*
 * SM - Timer for sending browsing status SM - Timer code
 */
var secs
var timerID = null
var timerRunning = false
var delay = 1000

pinging_time_period = 15;
ping = true;
startingDate = new Date();
function updatePingingTotalPeriod() {
	thisDate = new Date();
	diff = thisDate - startingDate;
	if (diff > ((60 * 60 * 1000) + 30))
		ping = false;
	else
		window.setTimeout("updatePingingTotalPeriod()", delay * 5);
}
window.setTimeout("updatePingingTotalPeriod()", delay * 5);

function InitializeTimer() {
	/* Set the length of the timer, in seconds */
	secs = pinging_time_period;
	StopTheClock()
	StartTheTimer()
}

function StopTheClock() {
	if (timerRunning)
		clearTimeout(timerID)
	timerRunning = false
}

function StartTheTimer() {
	if (secs == 0) {
		StopTheClock();
		/*
		 * Here's where you put something useful that's supposed to happen after
		 * the allotted time.
		 */
		data.status = "Browsing";
		if (!blocked && ping > 0)
			sendData(data, ACTIVITY_URL);
	} else {
		self.status = secs
		secs = secs - 1
		timerRunning = true
		timerID = self.setTimeout("StartTheTimer()", delay)
	}
}
/* SM - End of timer code */

/* SM - function to update the browsing status */
function updateHit() {
	if (document.activeElement == null) {
		/* SM - body did not load yet */
		var temp = setTimeout("updateHit()", 500);
		updatedHit = 0;
		return;
	} else {
		if ((updatedHit == 0) || (typeof updatedHit == "undefined")) {
			updatedHit = 1;
			data.status = "Hit";
			/* The page title the user is visiting */
			if (document.title == "") {
				data.pageTitle = document.location.href;
			} else {
				data.pageTitle = document.title;
			}
			if (!blocked)
				sendData(data, COLLECTOR_URL);
			InitializeTimer();
		}
	}
}

function updateStatus(status) {
	data.status = status;
	if (!blocked)
		sendData(data, COLLECTOR_URL);
}

/* This function extracts the search engine from a referal string */
function searchEngine(referrer, searchEngines) {
	/* Determine the search engine */
	var engine = "";
	for (sEngine in searchEngines) {
		if (referrer.indexOf(sEngine) > -1) {
			engine = sEngine;
			break;
		}
	}

	return engine;
}

/* This function extracts the search term from a referal string */
function searchTerm(referrer, searchEngines) {
	/* Determine the search engine */
	var engine = searchEngine(referrer, searchEngines);

	/* If no engine - no term */
	if (engine == "") {
		return "";
	}

	/* Extrach the parameter */
	var paramIndex = referrer.indexOf("&" + searchEngines[engine] + "=");
	if (paramIndex == -1) {
		paramIndex = referrer.indexOf("?" + searchEngines[engine] + "=");
	}

	/* If no param - no term */
	if (paramIndex == -1 || (paramIndex + 3) >= referrer.length) {
		return "";
	}

	/* Get the term */

	var term = referrer.substring(paramIndex + 3);

	var nextParamPos = term.indexOf("&");

	if (nextParamPos > -1) {
		term = term.substring(0, nextParamPos);
	}

	return unescape(term);
}

/* This function extracts the domain name from a url */
function getDomain(url) {
	/* Remove the http bit */
	if (url.indexOf("http://") > -1) {
		url = url.substring(7);
	}

	/* Remove the www bit */
	if (url.indexOf("www.") > -1) {
		url = url.substring(4);
	}

	/* Remove the document path */
	if (url.indexOf("/") > -1) {
		url = url.substring(0, url.indexOf("/"));
	}

	return url;
}

/*
 * SM - Commented start and end time to replace with new code logic
 */
/*
 * Page timer window.onload = function() { /* Time page finished loading var
 * startTime = new Date().getTime(); /* Send time data.start = startTime/1000
 * sendData(data, COLLECTOR_URL); }
 * 
 * window.onunload = function() { /* Time page exited var endTime = new
 * Date().getTime(); /* Send time data.end = endTime/1000 sendData(data,
 * COLLECTOR_URL); }
 */

/*
 * This function encodes the input object into a query string and sends it to
 * the input location
 */
function sendData(data, location) {

	/* Encode the parameters */
	var queryString = "";
	for (prop in data) {
		queryString += "&" + escape(prop) + "=" + escape(data[prop]);
	}
	queryString = queryString.substring(1);
	/* SM - Added to prevent loading cached files */
	queryString = queryString + "&rand=" + Math.random()
	/* Create the image */
	img = new Image();
	img.onload = checkIfBlocked;
	/* Send the request */
	img.src = location + "?" + queryString;
	/* img.onload = checkifloaded ; */
	InitializeTimer();
}

function checkIfBlocked() {
	var imageWidth = img.width;
	if (imageWidth == 1)
		blocked = true;
	else if (imageWidth == 2)
		grapIP();
	else if (imageWidth == 3) {
		pinging_time_period = 5;
		InitializeTimer();
	}
}
function grapIP() {
	/* Create the image */
	IPimg = new Image();
	IPimg.onload = ResendRequest;
	/* Send the request */
	IPimg.src = GRAP_IP_URL + "?rand=" + Math.random();
}
function ResendRequest() {
	sendData(data, COLLECTOR_URL);
	InitializeTimer();
}

function checkifloaded() {
	loaded = img.width;
	if (loaded) {
		data.visitor = loaded;
		return true;
	} else {
		return false;
	}
}

/* Send "Hit" flag */
updateHit();
