// 	Tracking code for Circus Casino (circuscasino.com)
//
//	27/01/2010	Andrew Banks	Re-build to simplify tracking and add keyword level SEO tracking
//	25/02/2010	Andrew Banks	Modified to now work on CircusCasino.com istead of StanleyCasinos.com

var debug = false;
var pageTracker;
var referrer;
var profile;
var searchEngine;
var keyword;
var ctcid;
var ourDomainName = 'www.circuscasino.com';
var cookieDomainName = '.circuscasino.com';
var ourCookieName = 'CCTracking';
var honeyCombCookieName = 'Honeycomb';
var affCookie1 = 'banner_domainclick';
var affCookie2 = 'banner_click';
var bannerDomain = 'banner.circuscasino.com';
var yahooPPCParam = 'TODO';
var seoAffiliate = "TRCircusSEO";
var affiliateCookieDuration = 3;

// Download URLs
var casinoDownloadURL = 'http://banner.circuscasino.com/cgi-bin/SetupCasino.exe';
var pokerDownloadURL = 'http://banner.circuscasino.com/cgi-bin/SetupPoker.exe';
var instantCasinoURL = 'http://banner.circuscasino.com/flashcasino.php';
//var instantCasinoThickboxURL = 'http://www2.circuscasino.com/website/live/instant/instant-wrapper.html';
var instantCasinoThickboxURL = 'http://banner.circuscasino.com/flashcasino.php';

// Google Analytics Page Hit URLs
var googlePageHitCasino = "/casino-downloaded";
var googlePageHitCasinoSimplified = "/casino-simplified-downloaded";
var googlePageHitCasinoTraditional = "/casino-traditional-downloaded";
var googlePageHitPoker = "/poker-downloaded";
var googlePageHitInstantCasino = "/instant-casino-launched";

//	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-1");
	pageTracker._initData();
	pageTracker._trackPageview();
	
	// 	Mediavest Generic Unique Tracking
	mvl_Track('2515958','circu054','01gen457',true,'');
	
	// 	Set the referrer variable
	referrer = document.referrer.toLowerCase();
	
	// 	Instant Casino Launcher
	//alert('BONUS - Checking for bonus cookie');
	
	//if($.cookie('ViewedBonus') == null)
	//{
	//	alert('BONUS - Bonus cookie not found');
	//	instantCasinoThickboxURL = "http://www2.circuscasino.com/website/live/instant/instant-wrapper.html"
	//}
	
	// Stop the links to casino and poker working. This allows us
	// to add a time delay and lets DFA tracking take place.
	//
	// For instant casino we find anything that links to the
	// instant casino URL, remove the URL and add the correct
	// tracking class.
	$(".LinkDownloadCasino").attr({
	 	href: "javascript:;"
	 });
	
	$(".LinkDownloadCasinoChineseSimplified").attr({
	 	href: "javascript:;"
	 });
	
	$(".LinkDownloadCasinoChineseTraditional").attr({
	 	href: "javascript:;"
	 });

	 $(".LinkDownloadPoker").attr({
	 	href: "javascript:;"
	 });
	
	 $("a[href='" + instantCasinoURL + "']").attr({
	 	href: instantCasinoThickboxURL,
		target: "_blank",
		className: "LinkInstantCasino iframe"
	 });
	 						   
	
							   
	// 	Casino and poker download link tracking
	//
	//	Functions that are called whenever the poker or casino
	//	download links are clicked.

	$(".LinkDownloadCasino").click(function () {
		TrackDownload('downloadCasino');
	});
	
	$(".LinkDownloadCasinoChineseSimplified").click(function () {
		TrackDownload('downloadCasinoChineseSimplified');
	});
	
	$(".LinkDownloadCasinoChineseTraditional").click(function () {
		TrackDownload('downloadCasinoChineseTraditional');
	});
	
	$(".LinkDownloadPoker").click(function () {
		TrackDownload('downloadPoker');
	});
	
	$(".LinkInstantCasino").click(function () {
		TrackDownload('instantCasino');
	});
							   						   
	// 	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.
//
//	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 'downloadCasino':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=http://'+ourDomainName+googlePageHitCasino+'&Referer=' + referrer + '\"/>');
	  	break;
		case 'downloadCasinoChineseSimplified':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=http://'+ourDomainName+googlePageHitCasinoSimplified+'&Referer=' + referrer + '\"/>');
		break;
		case 'downloadCasinoChineseTraditional':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=http://'+ourDomainName+googlePageHitCasinoTraditional+'&Referer=' + referrer + '\"/>');
		break;
	case 'downloadPoker':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=http://'+ourDomainName+googlePageHitPoker+'&Referer=' + referrer + '\"/>');
	  	break;
	case 'instantCasino':
		  $('body').append('<img width=\"1\" height=\"1\" src=\"http://www.honeycomb-software.net/Customers/save_Stanley.asp?CustomerCode=Stanley&CtcID=' + ctcid + '&p=http://'+ourDomainName+googlePageHitInstantCasino+'&Referer=' + referrer + '\"/>');
	  	break;
	}	
}


//	Tracks a google page hit
function TrackGoogleConversion(downloadType)
{
	switch (downloadType)
	{
	case 'downloadCasino':
	  pageTracker._trackPageview(googlePageHitCasino);
	  break;
	case 'downloadCasinoChineseSimplified':
	  pageTracker._trackPageview(googlePageHitCasinoSimplified);
	  break;
	case 'downloadCasinoChineseTraditional':
	  pageTracker._trackPageview(googlePageHitCasinoTraditional);
	  break;
	case 'downloadPoker':
	  pageTracker._trackPageview(googlePageHitPoker);
	  break;
	case 'instantCasino':
	  pageTracker._trackPageview(googlePageHitInstantCasino);
	  break;
	}	
}


//	Redirects to the appropriate software
function DownloadProduct(downloadType)
{
	switch (downloadType)
	{
		case 'downloadCasino':
	  	  document.location.href = casinoDownloadURL;
		  break;
		case 'downloadCasinoChineseSimplified':
	  	  document.location.href = casinoDownloadURL;
		  break;
		case 'downloadCasinoChineseTraditional':
	  	  document.location.href = casinoDownloadURL;
		  break;
		case 'downloadPoker':
		  document.location.href = pokerDownloadURL;
		  break;
		case 'instantCasino':
			//var linkHTML = "<a style='display: none' ID='dummyClick' href='" + instantCasinoThickboxURL + "' class='LinkInstantCasino iframe'>Dummy Link</a>";
			//$(linkHTML).appendTo("body");
			//$("#dummyClick").fancybox({
			//	 'frameWidth':700,
			//	 'frameHeight':575,
			//	 'overlayShow': true,
			//	 'overlayOpacity' : 0.5,
			//	 'hideOnContentClick': false,
			//	 'confirmClose': true
			//});
			//$("#dummyClick").click();
			break;
	}	
}

//	Logs a DART PPC Conversion
function TrackPPCConversion(downloadType)
{
	switch (downloadType)
	{
		case 'downloadCasino':
			mvl_Track('2515958','circu054','03dow633',false,'English');		  
			break;
		case 'downloadCasinoChineseSimplified':
			mvl_Track('2515958','circu054','03dow633',false,'Chinese+Simplified');		  
			break;
		case 'downloadCasinoChineseTraditional':
			mvl_Track('2515958','circu054','03dow633',false,'Chinese+Traditional');		  
			break;
		case 'downloadPoker':
			mvl_Track('2515958','circu054','04dow554',false,'');	
			break;
		case 'instantCasino':
			mvl_Track('2515958','circu054','02ins965',false,'');		
			break;
	}
}


// 	Mediavest Tracking Code
function mvl_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 mvl_Guid(){var d=mvl_GC("__utma");if(d==""){return""}var b=d.split(".");if(b.count<2){return""}return b[1]}function mvl_Track(e,f,j,g,d){var m=Math.random()+"";var l=m*10000000000000;var k="";var i="";if(g){k="ord=1;num="+l}else{k="ord="+l;i="u2="+d+";"}var h=document.createElement("iframe");h.src=window.location.protocol+"//fls.uk.doubleclick.net/activityi;src="+e+";type="+f+";cat="+j+";u1="+mvl_Guid()+";"+i+k+"?";h.width="1";h.frameBorder="0";h.height="1";h.allowTransparency=true;document.body.appendChild(h)};


// 	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;