// ====================================================================
// SendROI Tracking Script v. 2.2
// (C)2004 SendTraffic and the Traffic Group
// http://sendtraffic.com/
// unauthorized duplication in any form will be prosecuted
// ====================================================================	
function SENDROI_TrackHit(CheckpointID, ConversionAmount, ConversionID, CookiePath, CookieDomain, CookieExpHours)
{
	var TrackURL = "//track.sendtraffic.com/track.aspx";
	
	var CookieHours = 1080; //45 days	
	if (!isNaN(CookieExpHours))
	{
		var CookieHours = CookieExpHours;
	}

	var Referrer = document.referrer;
	var URL = document.URL;
	var PageTitle = document.title;
	var CampaignID;
	var SearchTerm;
	var CreativeID;
	var FirstHit;


	var ClientCookieCampaign = new CCookie("SENDROI20CID");
	var ClientCookieTerm = new CCookie("SENDROI20KWD");
	var ClientCookieReferer = new CCookie("SENDROI20REF");
	var ClientCookieCreative = new CCookie("SENDROI20AD");
	var ClientCookieAsstCampaign = new CCookie("SENDROI20AsstCID");
	var ClientCookieAsstTerm = new CCookie("SENDROI20AsstKWD");
			

	var	AssistKwd = ClientCookieTerm.GetValue();
	var AssistCampaign    = ClientCookieCampaign.GetValue();	


	var pi = new PageInfo();	

	var ExpDate = new Date();
	ExpDate.setHours(ExpDate.getHours() + CookieHours);	
		
	// check if referrer is from the local system (from cache)
	if (startsWith(Referrer, "file://"))
	{
		return false;
	}

    //extract campaign ID and search term
	var querystring = document.location.search;

	CampaignID = pi.GetQuerystringParam(querystring, "sendroicid");
	SearchTerm = pi.GetQuerystringParam(querystring, "sendroikwd");
	CreativeID = pi.GetQuerystringParam(querystring, "sendroiad");
	



	
	if (isEmpty(CreativeID))
	{
	    CreativeID = "";
	}

    //If campaign and keyword are empty check the parent frame URL.
	var ParentQuerystring = window.top.location.search;
	if (isEmpty(CampaignID) && !isEmpty(pi.GetQuerystringParam(ParentQuerystring, "sendroicid")))
	{
		querystring = ParentQuerystring;
		CampaignID = pi.GetQuerystringParam(ParentQuerystring, "sendroicid");
	}
	if (isEmpty(SearchTerm) && !isEmpty(pi.GetQuerystringParam(ParentQuerystring, "sendroikwd")))
	{
		querystring = ParentQuerystring;
		SearchTerm = pi.GetQuerystringParam(ParentQuerystring, "sendroikwd");
	}	
	if (isEmpty(CreativeID) && !isEmpty(pi.GetQuerystringParam(ParentQuerystring, "sendroiad")))
	{
		querystring = ParentQuerystring;
		CreativeID = pi.GetQuerystringParam(ParentQuerystring, "sendroiad");
	}	

	var CookieDataString = ClientCookieCampaign.GetValue() + ClientCookieTerm.GetValue() + ClientCookieCreative.GetValue();
	var QueryDataString = CampaignID + SearchTerm + CreativeID;
	
	if(!isEmpty(CampaignID) && (CookieDataString != QueryDataString))
	{	
		FirstHit = true; // new visitor only if campaignID present and campaign data not the same as the cookies
	}
	else
	{
		var CookieValueCampaign = ClientCookieCampaign.GetValue();	
		var CookieValueTerm     = ClientCookieTerm.GetValue();
		var CookieValueCreative = ClientCookieCreative.GetValue();

		if (isEmpty(CookieValueCampaign))
		{
			CampaignID = "DIRECT";
			SearchTerm = "";
			CreativeID = "";
			FirstHit = true;
		}
		else
		{		
			CampaignID = CookieValueCampaign;
			SearchTerm = CookieValueTerm;
			CreativeID = CookieValueCreative;
			Referrer = ClientCookieReferer.GetValue();
			AssistKwd  = CookieValueTerm;
			AssistCampaign = CookieValueCampaign;
			FirstHit = false;
		}
	}
	
	//Set the Assist Keyword and Campaign if the Cookie value for the Search term is not empty
	//and the Cookie value differs from the querystring value for the search term
	if ((AssistKwd != SearchTerm) && (!isEmpty(AssistKwd))  && (!isEmpty(SearchTerm)) )
	{
	  ClientCookieAsstCampaign.SetValue(AssistCampaign, ExpDate, false, CookiePath, CookieDomain);
	   ClientCookieAsstTerm.SetValue(AssistKwd, ExpDate, false, CookiePath, CookieDomain);
	}
	else
	{
		AssistCampaign = ClientCookieAsstCampaign.GetValue();
		AssistKwd = ClientCookieAsstTerm.GetValue();
	}
	

	
	    //set the cookies to the current values	
	ClientCookieCampaign.SetValue(CampaignID, ExpDate, false, CookiePath, CookieDomain);
	ClientCookieTerm.SetValue(SearchTerm, ExpDate, false, CookiePath, CookieDomain);
	ClientCookieCreative.SetValue(CreativeID, ExpDate, false, CookiePath, CookieDomain);
	ClientCookieReferer.SetValue(Referrer, ExpDate, false, CookiePath, CookieDomain);

	
	if (CampaignID == "DIRECT")
	{
		CampaignID = null;
	}
	
    //make conversion amount numeric if it is not
	ConversionAmount = parseFloat(ConversionAmount);

	if (String(ConversionAmount).length > 0 && isNaN(ConversionAmount))
	{
		ConversionAmount = 0;
	}

    //Ignore ConversionId if paramter name is not removed
	if (ConversionID == '[ConversionID]')
	{
		ConversionID = '';
	}
			
    //compound all tracking info into a query string
	var TrackingInfo =
		pi.QueryParameter("?ckid", CheckpointID) +	
		pi.QueryParameter("&caid", CampaignID) +		
		pi.QueryParameter("&kwd", SearchTerm) +
		pi.QueryParameter("&amount", String(ConversionAmount)) +
		pi.QueryParameter("&cvid", ConversionID) +
		pi.QueryParameter("&referrer", Referrer) +
		pi.QueryParameter("&cachebuster", GetBuster(CheckpointID)) +
		pi.QueryParameter("&firsthit", String(FirstHit)) + 
		pi.QueryParameter("&js", "true") + 
		pi.QueryParameter("&utm_content", CreativeID) +
		pi.QueryParameter("&uv1", AssistKwd) + 
		pi.QueryParameter("&uv2", AssistCampaign) +
		pi.QueryParameter("&url", URL) +
		pi.QueryParameter("&title", PageTitle);

    //output the tracking info to an image object	
	if (document.images)
	{
		var img = new Image();
		img.src = TrackURL + TrackingInfo;
	} 		
	else
	{	
		document.write('<img src="' + TrackURL + TrackingInfo + '" width="1" height="1">');
	} 
	
}

//COOKIE OBJECT
function CCookie(cookiename)
{
	this.Cookiename = cookiename;
	
	this.SetValue = function(value, expires, secure, path, domain)
	{
		if (path == null)
			path="/";
		
		var pi = new PageInfo();
	
		document.cookie = pi.URLEncode(this.Cookiename) + "=" 
			+ pi.URLEncode(value)
			+ ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) 
			+ ((path == null) ? "" : ("; path=" + path)) 
			+ ((domain == null) ? "" : ("; domain=" + domain)) 
			+ ((secure == true) ? "; secure" : "");
	}

	this.GetValue = function() 
	{
		var pi = new PageInfo();
		var str = pi.URLEncode(cookiename) + "=";
		
		var strlen = str.length;
		var cookielen = document.cookie.length; 
		var i = 0;
		var j;
		
							
		while (i < cookielen)
		{ 			
			j = i + strlen;
	
			if (document.cookie.substring(i, j) == str) 
				return getCookieVal(j);
			
			i = document.cookie.indexOf(" ", i) + 1;
			
			if (i == 0) break;
		} 
		
		return '';
	}	
	
	function getCookieVal(lastpos)
	{   
		var pi = new PageInfo();
		var str = document.cookie.indexOf (";", lastpos);  
	
		if (str == -1)
			str = document.cookie.length; 
	
		return pi.URLDecode(document.cookie.substring(lastpos, str));
	}	
}

//PAGEINFO OBJECT
function PageInfo()
{
	this.GetQuerystringParam = function(querystring, name) 
	{
		var i;
		var arr = querystring.substr(1).split("&");
		
		for (i = 0; i < arr.length; i++)
		{
			if (arr[i].indexOf(name + "=") == 0)
				return this.URLDecode(arr[i].split("=")[1]); 
		}
		
		return null;
	}
	
	this.IsRepeatedReferrer = function()
	{
		return (document.referrer == GetLastReferrer());
	}	

	this.GetLastReferrer = function()
	{
		var c = new CCookie("SENDROI_REF");
		var s = c.GetValue();
		return s;
	}
	
	this.QueryParameter = function(name, value)
	{
		if (!isEmpty(value))
			return name + "=" + this.URLEncode(value);
		else
			return "";
	}
	
// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
// ====================================================================	
	
	this.URLEncode = function(plaintext)
	{
		var SAFECHARS = "0123456789" +					// Numeric
						"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
						"abcdefghijklmnopqrstuvwxyz" +
						"-_.!~*'()";					// RFC2396 Mark characters
		var HEX = "0123456789ABCDEF";
		
		var encoded = "";
		for (var i = 0; i < plaintext.length; i++ ) {
			var ch = plaintext.charAt(i);
			if (ch == " ") {
				encoded += "+";				// x-www-urlencoded, rather than %20
			} else if (SAFECHARS.indexOf(ch) != -1) {
				encoded += ch;
			} else {
				var charCode = ch.charCodeAt(0);
				if (charCode > 255) {
					encoded += "+";
				} else {
					encoded += "%";
					encoded += HEX.charAt((charCode >> 4) & 0xF);
					encoded += HEX.charAt(charCode & 0xF);
				}
			}
		} // for

		return encoded;
	};

	this.URLDecode = function(encoded)
	{
		var HEXCHARS = "0123456789ABCDEFabcdef"; 
		var plaintext = "";
		var i = 0;
		while (i < encoded.length) {
			var ch = encoded.charAt(i);
			if (ch == "+") {
				plaintext += " ";
				i++;
			} else if (ch == "%") {
					if (i < (encoded.length-2) 
							&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
							&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
						plaintext += unescape( encoded.substr(i,3) );
						i += 3;
					} else {
						plaintext += "%[ERROR]";
						i++;
					}
				} else {
				plaintext += ch;
				i++;
				}
			} // while
		return plaintext;
	}
}

function isEmpty(strVal)
{
	return (strVal == null || strVal == 'null' || strVal == '');
}

function startsWith(strSource, strMatch)
{
	if (strMatch == null || strSource == null) {
		return false;
	}
	
	if (strMatch.length > strSource.length){
		return false;
	}
	
	if (strSource.substring(0, strMatch.length) == strMatch){
		return true;
	}
	
	return false;
}

function GetBuster(str)
{
	var buster = str.replace(new RegExp("-", "g"), "");
	buster += new Date().valueOf() + Math.random() * 10000;
	return buster.substring(0,50);
}