// --------------------------------------------------------------------
// 
// --------------------------------------------------------------------

function TP_EventTracking(ConvID, ConvAmt, TPEventId, TPEventURL, TPReferrer,TPType,TPCampaign, TPKeyword, TPCreative, TPMatch,TPPath,TPDomain,TPTestId,TPPlmnt,TPAdPos)
{
    var Referrer = TPReferrer;

	// Do not record hits for cahced pages that start with file://)
	if (Referrer.substr(1, 8) == "file://")
	{
		return false;
	}

	var URL = TPEventURL;
	var EntryUrl = TPEventURL;
	var PageTitle = document.title;
    var Resolution = screen.width+'x'+screen.height;
    var Browser = navigator.appName;
	var CampaignID = null;
	var SearchTerm = null;
	var CreativeID = null;
	var AdgroupId = null;
	var MatchType = null;
	var FirstHit = null;
	var CookieCreatedDate = null;
	var CookieId = null;
	var EventId = TPEventId;
	var ctTestID = TPTestId;
	var ctPlmnt = TPPlmnt;
	var ctAdPos = TPAdPos;


    if ((ConvID == "ConversionId") || (isEmpty(ConvID)))
    {
        ConvID= "";
    }
    

    //extract url Paramaters from Querystring
	var querystring = "";	
    try{
	    querystring = document.location.search;
	}
	catch(querystring){
	    querystring ="";
	}

    if(querystring){
       if(querystring.length > 0){
           CampaignID = TPCampaign;
           SearchTerm = TPKeyword;
           CreativeID = TPCreative;
           MatchType = TPMatch;
           ctTestID =TPTestId;
           ctPlmnt = TPPlmnt;
           ctAdPos = TPAdPos;
       }
    }
	//Get Cookie values
	var CampaignCookie = new CookieObject("CT_CID");
	var KeytermCookie = new CookieObject("CT_KWD");
	var ReferrerCookie = new CookieObject("CT_REF");
	var CreativeCookie = new CookieObject("CT_AD");
	var MatchTypeCookie = new CookieObject("CT_MATCH");
	var AssistCampaignCookie = new CookieObject("CT_Assist_CID");
	var AssistKeytermCookie = new CookieObject("CT_Assist_KWD");
	var AssistMatchCookie = new CookieObject("CT_Assist_MATCH");
	var AssistCreativeCookie = new CookieObject("CT_Assist_AD");

	var EntryUrlCookie = new CookieObject("CT_ENTRYURL");

	var CreatedDateCookie = new CookieObject("CT_CrtDate");
	var UIDCookie = new CookieObject("CT_UID");

	var TestIdCookie = new CookieObject("CT_TestId");
	var PlacementCookie = new CookieObject("CT_Plmnt");
	var AdPosCookie = new CookieObject("CT_AdPos");

	var	AssistKwd = KeytermCookie.GetValue();
	var AssistCampaign    = CampaignCookie.GetValue();	
	var	AssistMatch = MatchTypeCookie.GetValue();
	var AssistCreative    = CreativeCookie.GetValue();	

	var CookieDataString = CampaignCookie.GetValue() + KeytermCookie.GetValue() + CreativeCookie.GetValue();
	if (isEmpty(SearchTerm) || SearchTerm == "undefined") {
	    SearchTerm="";
	}
	if (isEmpty(CreativeID) || CreativeID == "undefined") {
	    CreativeID="";
	}
	if (isEmpty(CampaignID) || CampaignID == "undefined") {
	    CampaignID="";
	}
	var QueryDataString = CampaignID + SearchTerm + CreativeID;

	if (isEmpty(MatchType) || MatchType == "undefined")
	{
	    MatchType = "";
	}
	
	if(!isEmpty(CampaignID) && (CookieDataString != QueryDataString))
	{	
		FirstHit = true; 
	}
	else
	{
		var CookieValueCampaign = CampaignCookie.GetValue();	
		var CookieValueTerm     = KeytermCookie.GetValue();
		var CookieValueCreative = CreativeCookie.GetValue();
		var CookieValueMatchType = MatchTypeCookie.GetValue();
		var CookieTestIdValue = TestIdCookie.GetValue();
		var CookiePlacementValue = PlacementCookie.GetValue();
		var CookieAdPosValue = AdPosCookie.GetValue();
        
        				
		if (isEmpty(CookieValueCampaign))
		{
			CampaignID = "DIRECT";
			SearchTerm = "";
			CreativeID = "";
			MatchType = "";
			FirstHit = true;
		}
		else
		{		
			CampaignID = CookieValueCampaign;
			SearchTerm = CookieValueTerm;
			CreativeID = CookieValueCreative;
			MatchType = CookieValueMatchType;
			Referrer = ReferrerCookie.GetValue();
			AssistKwd  = CookieValueTerm;
			AssistCampaign = CookieValueCampaign;
			AssistMatch = CookieValueMatchType;
			AssistCreative = CookieValueCreative;
			ctTestID = CookieTestIdValue;
			ctPlmnt = CookiePlacementValue;
			ctAdPos = CookieAdPosValue;
			
			FirstHit = false;
		}	
	}

    //Setup Cookie variables
	var DefaultCookieExp = 1440; //60 days

	var CookieDomain = TPDomain;
	var ClientDomain = document.domain;
	if (isEmpty(CookieDomain)) {
	    CookieDomain = ClientDomain;
	}


	var CookiePath = TPPath;
	var ExpDate = new Date();
	ExpDate.setHours(ExpDate.getHours() + DefaultCookieExp);	
		
	
	//Set the Assist Keyword and Campaign 
	if ((AssistKwd != SearchTerm) && (!isEmpty(AssistKwd))  && (!isEmpty(SearchTerm)) )
	{
	  AssistCampaignCookie.SetValue(AssistCampaign, ExpDate, false, CookiePath, CookieDomain);
	   AssistKeytermCookie.SetValue(AssistKwd, ExpDate, false, CookiePath, CookieDomain);
	   AssistMatchCookie.SetValue(AssistMatch, ExpDate, false, CookiePath, CookieDomain);
	   AssistCreativeCookie.SetValue(AssistCreative, ExpDate, false, CookiePath, CookieDomain);
	}
	else
	{
		AssistCampaign = AssistCampaignCookie.GetValue();
		AssistKwd = AssistKeytermCookie.GetValue();
		AssistMatch = AssistMatchCookie.GetValue();
		AssistCreative = AssistCreativeCookie.GetValue();
	}

	  //set the cookies values
	CampaignCookie.SetValue(CampaignID, ExpDate, false, CookiePath, CookieDomain);
	KeytermCookie.SetValue(SearchTerm, ExpDate, false, CookiePath, CookieDomain);
	CreativeCookie.SetValue(CreativeID, ExpDate, false, CookiePath, CookieDomain);
	MatchTypeCookie.SetValue(MatchType, ExpDate, false, CookiePath, CookieDomain);
	ReferrerCookie.SetValue(Referrer, ExpDate, false, CookiePath, CookieDomain);

	TestIdCookie.SetValue(ctTestID, ExpDate, false, CookiePath, CookieDomain);
	PlacementCookie.SetValue(ctPlmnt, ExpDate, false, CookiePath, CookieDomain);
	AdPosCookie.SetValue(ctAdPos, ExpDate, false, CookiePath, CookieDomain);
	
	if (CampaignID == "DIRECT")
	{
		CampaignID = null;
	}
		
	if (Referrer == "")
	     Referrer ="Blank Referrer";
	
	if(FirstHit == true){
	    EntryUrlCookie.SetValue(EntryUrl, ExpDate, false, CookiePath, CookieDomain);	
	}	
    var entryURL = EntryUrlCookie.GetValue();

    //If Cookie doesnt exist than set ID and Date
    if ((FirstHit == true) && (isEmpty(CookieDataString))) {
        var CurrentDate = new Date();
        CreatedDateCookie.SetValue((CurrentDate.getMonth() + 1 + "/" + CurrentDate.getDate() + "/" + CurrentDate.getFullYear() + " " + CurrentDate.getHours() + ":" + CurrentDate.getMinutes() + ":" + CurrentDate.getSeconds()), ExpDate, false, CookiePath, CookieDomain);
        UIDCookie.SetValue(escape(GetRandom(Referrer + PageTitle + CurrentDate.getMilliseconds())), ExpDate, false, CookiePath, CookieDomain)

    }

    CookieCreatedDate = CreatedDateCookie.GetValue();
    CookieId = UIDCookie.GetValue();
	
	
	var TrackURL = "//hits.convergetrack.com/default.aspx";
//    var TrackURL = "default.aspx";	
					
    //combine all tracking info into a query string
	var TrackParams =
		"?ckid=" + escape(EventId) + "&caid=" + escape(CampaignID) + "&kwd=" + escape(SearchTerm) + "&amount=" + escape(String(ConvAmt)) + "&CType=" + escape("1") +
		"&cvid=" + escape(ConvID) +"&referrer=" + escape(Referrer) +"&rnd=" + escape(GetRandom(PageTitle)) +	"&firsthit=" + escape(String(FirstHit)) +
		"&js=" + "true" + "&adid=" + escape(CreativeID) + "&eventurl=" + escape(URL) + "&entryURL=" + escape(entryURL) + "&CDate=" + escape(CookieCreatedDate) + "&CID=" + escape(CookieId) +
		"&mt=" + escape(MatchType)  +  "&testid=" + escape(ctTestID) +  "&ctplc=" + escape(ctPlmnt) + "&ctpos=" + escape(ctAdPos) + "&aCmp=" + escape(AssistCampaign) + "&aKwd=" + escape(AssistKwd) + "&aMT=" + escape(AssistMatch) + "&aAd=" + escape(AssistCreative) + "&title=" + escape(PageTitle) + "&res=" + escape(Resolution) + "&adgrp=" +  "&bws=" + escape(Browser); 
				               


		if (document.images) {
		    var img = new Image();
		    img.src = TrackURL + TrackParams;
		}
		else {
		    document.write('<img src="' + TrackURL + TrackParams + '" width="1" height="1">');
		} 


}

function CookieObject(cookiename)
{
	this.Cookiename = cookiename;
	
	this.SetValue = function(value, expires, secure, path, domain)
	{
		if (path == null)
			path="/";
			
		document.cookie = escape(this.Cookiename) + "=" 
			+ escape(value)
			+ ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) 
			+ ((path == null) ? "" : ("; path=" + path)) 
			+ ((domain == null) ? "" : ("; domain=" + domain)) 
			+ ((secure == true) ? "; secure" : "");
	}

	this.GetValue = function() 
	{
		var str = escape(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 str = document.cookie.indexOf (";", lastpos);  
	
		if (str == -1)
			str = document.cookie.length; 
	
		return unescape(document.cookie.substring(lastpos, str));
	}	
}

function GetParamFromUrl (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.unescape(arr[i].split("=")[1]); 
		}
		
		return null;		
}

function isEmpty(strVal)
{
	return (strVal == null || strVal == 'null' || strVal == '');
}

function GetRandom(str)
{
	var buster;
	buster = new Date().valueOf() + Math.random() * 500;
	return buster;
}

