// 	Tracking code for Genting Poker (GentingPoker.com)
//
//	24/05/09	Andrew Banks	Initial Build

var debug = false;
var pageTracker;
var referrer;
var profile;
var searchEngine;
var keyword;
var ctcid;
var ourDomainName = 'www.gentingpoker.com';
var cookieDomainName = '.gentingpoker.com';
var ourCookieName = 'GPTracking';
var honeyCombCookieName = 'Honeycomb';
var affCookie1 = 'banner_domainclick';
var affCookie2 = 'banner_click';
var bannerDomain = 'banner.gentingpoker.com';
var yahooPPCParam = 'TODO';
var seoAffiliate = "TRGentingPSEO";
var affiliateCookieDuration = 3;

// Download URLs
var pokerDownloadURL = 'http://banner.gentingpoker.com/cgi-bin/SetupPoker.exe';

// Google Analytics Page Hit URLs
var googlePageHitPoker = "/poker-downloaded";

//	Arrays for SEO tracking
var searchEngineArray = new Array();
searchEngineArray['google.co.uk'] = 'google';
searchEngineArray['google.com'] = 'google';
searchEngineArray['yahoo.co.uk'] = 'yahoo';
searchEngineArray['yahoo.com'] = 'yahoo';
searchEngineArray['msn.co.uk'] = 'msn';
searchEngineArray['msn.com'] = 'msn';
searchEngineArray['ask.co.uk'] = 'ask';
searchEngineArray['ask.com'] = 'ask';
searchEngineArray['bing.co.uk'] = 'bing';
searchEngineArray['bing.com'] = 'bing';

var axel = Math.random()+"";
var a = axel * 10000000000000;

$(document).ready(function(){
						   
	// 	Initialise Google Analytics	and log a page hit for the
	//	current page
	pageTracker = _gat._getTracker("UA-3972389-8");
	pageTracker._initData();
	pageTracker._trackPageview();
	
	// 	Mediavest Generic Unique Tracking
	//sp_Track('2520483','genti735','01gen312',true);
	
	// 	Set the referrer variable
	referrer = document.referrer.toLowerCase();
	
	// Stop the links to casino and poker working. This allows us
	// to add a time delay and lets tracking take place.
	
	$("a[href='" + pokerDownloadURL + "']").attr({
	 	href: "javascript:;",
		className: "TrackPokerDownload"
	 });
							   
	// 	Casino and poker download link tracking
	//
	//	Functions that are called whenever the poker or casino
	//	download links are clicked.
	
	$(".TrackPokerDownload").click(function () {
		TrackDownload('downloadPoker');
	});
							   						   
	// 	Log who the searchEngine is
	DoTracking();
});

//	The main tracking function
//
//	1 - Check to see if the main cookie has been created.
//		If not this needs doing. Otherwise we know the
//		tracking has been completed.
//
//	2 - If the main cookie has just been created then we need
//		to undertake the rest of the tracking.
function DoTracking()
{
	//	Check to see if a honeycomb cookie exists
	alert('About to check if a honeycomb cookie exists');
	
	if($.cookie(honeyCombCookieName) != null)
	{
		//	The cookie does exist so read the value out of it. Also
		//	delete all other affiliate cookies.
		alert('Honeycomb cookie was found');
		ctcid = $.cookie(honeyCombCookieName);
		DeleteAffiliateCookies();
		alert('Affiliate cookies deleted');
		alert('As a Honeycomb value was found we don\'t do any more tracking detection');
	}
	else
	{
		//	The cookie does not exist so see if we have been passed
		//	a ctcid and if we have assign it to the cookie.
		alert('Honeycomb cookie was not found');
		alert('About to check for a ctcid on the URL');
		
		ctcid = GetParameterValue('ctcid',document.URL);	
		
		if(ctcid!=null)
		{
			alert('CTCID was found on the URL and will be save in a cookie for 1 year');	
			$.cookie(honeyCombCookieName, ctcid, { expires: 365 });
			DeleteAffiliateCookies();
			alert('Affiliate cookies deleted');
			alert('Honeycomb cookie saved');
			alert('As a Honeycomb value was found we don\'t do any more tracking detection');
		}
		else
		{
			alert('CTCID was not found on the URL');
			//	This is deffinitely not an existing customer so we need
			//	to work out who the affiliate is
			alert('About to check if our cookie exists');
			
			if($.cookie(ourCookieName) == null)
			{
				//	Our cookie doesn't exist so we need to create it
				alert('Our cookie doesn\'t exist so we are creating it');
				
				//	See if a Honeycomb ID exists
				var cookieValue = 'referer=' + referrer;
				
				//	Create our cookie and store the referrer info in it along
				//	with the honeycomb ID.
				$.cookie(ourCookieName, cookieValue);
				alert('Our cookie has been set');
				CalculateSearchEngine();
			}
			else
			{
				//	Tracking has already been done and we don't need to do
				//	anything
				alert('Our cookie does exist and the tracking has previously been done');
			}
		}
	}
	
	//	Embed the honeycomb tracking code if appropriate
	if(ctcid!=null)
	{
		alert('Writing out the generic honeycomb tracking code');
		// TODO
		$('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=' + document.URL + '&Referer=' + referrer + '\"/>');
	}
	else
	{
		alert('Traffic is not from Honeycomb so no need to write out the honeycomb tracking code');
	}
	
	alert('Tracking complete');
}

//	Work out the search engine and keyword used
function CalculateSearchEngine()
{
	// Only work out the search engine if no tracking parameters are passed
	
	if(GetParameterValue('gclid',document.URL) == null &&  GetParameterValue('utm_medium',document.URL) == null)
	{
		//Loop through the search engines
		for (var i in searchEngineArray) 
		{
			alert('Checking for referrer ' + i);
			
			if (referrer.indexOf(i) != -1) 
			{
				alert('Search Engine was matched as ' + searchEngineArray[i]);
				searchEngine = searchEngineArray[i];
				break;
			}
			else
			{
				alert('Referrer was not a search engine');
			}
		}
		
		alert('Checking to see if a search engine was set');
		
		if(searchEngine)
		{
			alert(searchEngine + ' was the search engine');
			
			keyword = GetParameterValue("q",referrer).replace("+"," ");
			
			alert("Keyword was " + keyword);
			
			var affCookieValue;
			affCookieValue = seoAffiliate + ',*,' + searchEngine + ',*,Keyword:' + keyword;
			$.cookie(affCookie1, affCookieValue, {domain: cookieDomainName, expires: affiliateCookieDuration});
			$.cookie(affCookie2, affCookieValue, {domain: cookieDomainName, expires: affiliateCookieDuration});
			alert('Affiliate cookies have been set');
		}
		else
		{
			alert('No search engine was found');
		}
	}
}

//	Gets a given parameter from the URL querystring
function GetParameterValue(parameterName, url)
{
	url = url.toLowerCase();
	
	var start = url.indexOf(parameterName + '=');
	if (start == -1)
	{
		return(null);
	}
	start += parameterName.length + 1;
	
	var end = url.indexOf('&',start);
	if (end == -1) 
	{
		end = url.length;
	}
	
	var toReturn = url.substring(start,end);
	return(toReturn);
}

//	Deletes all affiliate cookies
function DeleteAffiliateCookies()
{
	$.cookie(affCookie1, null);
	$.cookie(affCookie2, null);
}

//	Calls all tracking scripts to log a casino download.
//
//	The casinoType parameter expects on of three values
//	1 - english - English Download Casino
//	2 - simplified - Simplified Chinese Casino
//	3 - traditional - Traditional Chinese Casino
//
//	1 - Log a Google hit
//	2 - Log a PPC conversions
//	3 - Log a Honeycomb page hit
//	4 - Redirect to the installer
function TrackDownload(downloadType)
{	
	alert("Track Download or Instant Link Clicked");
	alert("We are tracking : " & downloadType);
	

	TrackGoogleConversion(downloadType);
	TrackPPCConversion(downloadType);
	
	alert("ctcid is " + ctcid);
	
	if(ctcid)
	{
		TrackHoneycombConversion(downloadType);
	}
	
	timer = setTimeout("DownloadProduct('" + downloadType + "')",500); // half a second
}


//	Tracks a Honeycomb Page Hit
//	TODO - These need proper URLs in
function TrackHoneycombConversion(downloadType)
{
	switch (downloadType)
	{
		
	case 'downloadPoker':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Genting&CtcID=' + ctcid + '&p=http://'+ourDomainName+'/casino-downloaded&Referer=' + referrer + '\"/>');
	  	break;
	}	
}


//	Tracks a google page hit
function TrackGoogleConversion(downloadType)
{
	switch (downloadType)
	{
	case 'downloadPoker':
	  pageTracker._trackPageview(googlePageHitPoker);
	  break;
	}	
}


//	Redirects to the appropriate software
function DownloadProduct(downloadType)
{
	switch (downloadType)
	{
		case 'downloadPoker':
		  document.location.href = pokerDownloadURL;
		  break;
	}	
}

//	Logs a DART PPC Conversion
function TrackPPCConversion(downloadType)
{
	switch (downloadType)
	{
		case 'downloadPoker':
			break;
	}
}


// 	Flash Button Handler
//
//	Flash buttons call this function which in turn simply
//	calls the 
function getSoftware(software)
{
	switch (software)
	{
	case 'poker':
	  TrackDownload('downloadPoker');
	  break;
	}
}

// 	Mediavest Tracking Code
function sp_GC(b){var d=document.cookie.indexOf(b+"=");if(d!=-1){var c=d+b.length+1;var a=document.cookie.indexOf(";",c);if(a==-1){a=document.cookie.length}return document.cookie.substring(c,a)}return""}function sp_Guid(){var d=sp_GC("__utma");if(d==""){return""}var b=d.split(".");if(b.count<2){return""}return b[1]}function sp_Track(j,i,d,g){var h=Math.random()+"";var f=h*10000000000000;var c="";if(g){c="ord=1;num="+f}else{c="ord="+f}var e=document.createElement("iframe");e.src=window.location.protocol+"//fls.uk.doubleclick.net/activityi;src="+j+";type="+i+";cat="+d+";u1="+sp_Guid()+";"+c+"?";e.width="1";e.frameBorder="0";e.height="1";e.allowTransparency=true;document.body.appendChild(e)};


// 	Custom debugging code			   
window.alert = new Function ("myAlert()");

myAlert = function(s) 
{
	if(debug)
	{
		var ta = document.getElementById('debug');
		if (!ta) 
		{
			var ta = document.createElement('textarea');
			ta.id = 'debug';
			ta.rows = 8; 
			ta.cols = 80;
			document.body.appendChild(ta);
		}
		ta.value += s+'\n';
	}
};
window.alert = myAlert;
