// #######################################
//    GOOGLE ANALYTICS INTEGRATION v2.4
// #######################################

// If you have any questions about the analytics stuff please ask!
// Always double check the account id. We don't want to load data into the wrong clients site.

// #######################################
//              CONFIGURATION
// #######################################

// This section allows you to configure how the analytics should operate or disable it if required.

// Basic Config
var enableanalytics = 'Y';	// Set to Y to enable Analytics Tracking.
var loadgatorasp = 'Y';	// Set to Y to enable loading of campaign tracking data into RecruitASP.
var numtrackers = 1;	// Set to either 1 or 2. The number of analytics account codes you want to track against. Include entry for each in accountids array.
var accountids = new Array;	// Array specificing each of the account codes to track against. Total entries should = numtrackers.
 	accountids[0] = "UA-xxxxxxx-x";
 	accountids[1] = "UA-yyyyyyyy-y";

// Sub Domain / Muti Domain Tracking configuration (Only enable 1 option, if any)
var subdomain = 'N'; //Set to Y if tracking multiple subdomains
var domainname = 'yoursite.com'; // domain name
var multidomain = 'Y'; // Set to Y if tracking accross multiple domains

// Additional functionality
var trackgoals = 'Y';	// Set to Y to enable additional Goal Tracking URLS.
var tracksearch = 'N';	// Set to Y to enable tracking of quick search and advanced search queries.

// Config for Loading into RASP
var expirydays = 7; // Set how long in days to keep the cookie utm_* data for loading into RASP


// -----------------------------------------------
// IMPORTANT! DO NOT EDIT ANYTHING BELOW THIS LINE
// -----------------------------------------------

// #######################################
//      SET GA DATA TO LOAD IN RASP
// #######################################

if (loadgatorasp == 'Y'){
	
	// Get the value of parameter utm_source.
	var utm_source = queryString("utm_source");

	// If source parameter exists, write 5 cookies for the 5 parameters.
	// Get the Paramaters
	if (utm_source != null){
		var utm_medium = queryString("utm_medium");
		var utm_term = queryString("utm_term");
		var utm_content = queryString("utm_content");
		var utm_campaign = queryString("utm_campaign");

		// Set the Expiry Timeout for the cookies
		var expiry = new Date();
		expiry.setDate(expiry.getDate() + expirydays);
		var expiryYear = expiry.getFullYear();
		var expiryMonth = expiry.getMonth() + 1;
		var expiryDay = expiry.getDate();

		// Write the cookies
		set_cookie("utm_source", utm_source, "/", expiryYear, expiryMonth, expiryDay);
		if (utm_medium != null){		
			set_cookie("utm_medium", utm_medium, "/", expiryYear, expiryMonth, expiryDay);
		}
		if (utm_term != null){
			set_cookie("utm_term", utm_term, "/", expiryYear, expiryMonth, expiryDay);
		}
		if (utm_content != null){
			set_cookie("utm_content", utm_content, "/", expiryYear, expiryMonth, expiryDay);
		}
		if (utm_campaign != null){
			set_cookie("utm_campaign", utm_campaign, "/", expiryYear, expiryMonth, expiryDay);
		}
	}
}
// #######################################
//        MAIN ANALYTICS CALL
// #######################################

// This function is used to initiate the tracker at the top of each page
// This function needs to be called from just after to open body tag in the header and session templates of all front ends to be tracked.


// 	document.write('document.write(unescape(\'%3Cscript src="\' + gaJsHost + \'google-analytics.com/ga.js" type="text/javascript"%3E%3C/script%3E\'));');

if(enableanalytics =='Y'){
//	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
//	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

//	function startAnalytics() {
		document.write('<script type="text/javascript">');
		document.write('var pageTracker = _gat._getTracker("' + accountids[0] +'");');
		if(subdomain =='Y'){
			document.write('pageTracker._setDomainName("' + domainname + '");');
		}
		if(multidomain =='Y'){
			document.write('pageTracker._setDomainName("none");');
			document.write('pageTracker._setAllowLinker(true);');
		}	
		document.write('pageTracker._setAllowAnchor(true);');
		document.write('pageTracker._trackPageview();');
		if(numtrackers == 2){	// If using second tracker
			document.write('var pageTracker2 = _gat._getTracker("' + accountids[1] + '");');
			if(subdomain =='Y'){
				document.write('pageTracker2._setDomainName("' + domainname + '");');
			}
			if(multidomain =='Y'){
				document.write('pageTracker2._setDomainName("none");');
				document.write('pageTracker2._setAllowLinker(true);');
			}	
			document.write('pageTracker2._setAllowAnchor(true);');
			document.write('pageTracker2._trackPageview();');
				}
		document.write('</SCRIPT>');
}

//if (window.addEventListener) {window.addEventListener('load', startAnalytics, false);}
//Else if (window.attachEvent) {window.attachEvent('onload', startAnalytics);}

//}


// #######################################
//        GOAL TRACKING FUNCTIONS
// #######################################

// This function tracks a fake page to record someone viewing a job.
// This function needs to be called at the start of: User Template Management > Search Templates > Details Body Template
function TrackViewJob()
{
	if(enableanalytics =='Y' && trackgoals =='Y'){
		pageTracker._trackPageview('/funnel/viewjob');
		if(numtrackers == 2){ // If using second tracker
  		pageTracker2._trackPageview('/funnel/viewjob');
		}	
	}
}
	
// This function tracks a fake page to record someone opening/viewing the application form.
// This function needs to be called at the start of: User Template Management > Search Templates > Details Body Template
function TrackViewAppForm()
{
	if(enableanalytics =='Y' && trackgoals=='Y'){
		//var pageTracker = _gat._getTracker(accountids[0]);
		pageTracker._trackPageview('/funnel/apply');
		// Loop to support multiple tracking codes if required
		if(numtrackers == 2){	// If using second tracker
  		//var pageTracker2 = _gat._getTracker(accountids[1]);
  		pageTracker2._trackPageview('/funnel/apply');
		}
	}
}

// This function tracks a fake page to record a succesful application being submitted.
// This function needs to be immediately before the return true statement in the Application Form validation.
// This may be in: User Template Management > User Application Manager Templates > Application Template OR in a validation.js file.
function TrackSuccessApp()
{
	if(enableanalytics =='Y' && trackgoals=='Y'){
		pageTracker._trackPageview('/funnel/success');

		// This bit of code fakes an e-commerce transaction.
		var timeObj = new Date;
		var unixTimeMs = timeObj.getTime();
		var unixTime = parseInt(unixTimeMs / 1000);
		var orderID = pageTracker._visitCode() + '-' + unixTime;
		pageTracker._addTrans(
		orderID, // required
		"", // Affiliation or store name
		"", // Total
		"", // Tax
		"", // Shipping
		"", // City
		"", // Country
		"" );

		pageTracker._addItem(
		orderID, // required - item number
		"", // SKU Code
		"", //Product Name
		"", //Category or Variation
		"1", // required - Unit Price
		"1" //required  - Quantity
		);

		pageTracker._trackTrans();
		
		if(numtrackers == 2){	// If using second tracker
			pageTracker2._trackPageview('/funnel/success');
			var orderID = pageTracker2._visitCode() + '-' + unixTime;
			pageTracker2._addTrans(
			orderID, // required
			"", // Affiliation or store name
			"", // Total
			"", // Tax
			"", // Shipping
			"", // City
			"", // Country
			"" );

			pageTracker2._addItem(
			orderID, // required - item number
			"", // SKU Code
			"", //Product Name
			"", //Category or Variation
			"1", // required - Unit Price
			"1" //required  - Quantity
			);

			pageTracker2._trackTrans();
		}
	}
}



// #######################################
//           SUPPORTING FUNCTIONS
// #######################################

// Functions to support loading into RASP.

// Returns the querystring value for the specified parameter name or null if it does not exist.
function queryString(parameter)
{
	var param_value = false;
	var query = unescape(window.location.hash.substring(1)); // use after the hash
	var params = query.split('&'); // split URL parameters

	for (i=0; i < params.length; i++)
	{
		param_name = params[i].substring(0,params[i].indexOf('='));

		if (param_name == parameter)
		{
			param_value = params[i].substring(params[i].indexOf('=') + 1)
		}
	}

	if (param_value)
	{
		return param_value;
	}
	else
	{
		return null;
	}
}

// Sets a session length cookie for the specified name/value pair ie. with no expiry date.
function set_session_cookie (name, value, path)
{
	set_cookie(name, value, path, null, null, null, null, null);
}

// Sets a cookie for the specified name/value pair, path, expiry date, domain, and secure.
function set_cookie(name, value, path, exp_y, exp_m, exp_d, domain, secure)
{
	// Assume URL is already escaped so don't escape the value.
	var cookie_string = name + "=" + value;

	if (exp_y)
	{
		var expires = new Date(exp_y, exp_m, exp_d);
		cookie_string += "; expires=" + expires.toGMTString();
  }

	if (path)
		cookie_string += "; path=" + escape(path) + ";";

  if (domain)
		cookie_string += "; domain=" + escape(domain);
  
	if (secure)
		cookie_string += "; secure";
  
	document.cookie = cookie_string;
}

// Retrieves the cookie value for the specified cookie name.
function getCookie(cookieName)
{
	var results = document.cookie.match(cookieName + '=(.*?)(;|$)');

	if (results)
		return unescape(results[1]);
	else
		return null;
}
