/*
 * Date:          Jun 17 2009
 *
 * Written by:    Ecomerce Intelligence.  www.ecomiq.com
 *
 * Purpose:       This script is meant to replace the 2nd part of the Google Analtyics tracking code.  It auto-detects the correct cookie domain
 *		  based on the URL in the browser's location window. 
 *
 */


// List of all base domain names, we should look at.  If the current URL is one of these domains
// or a subdomain of one of these, we will use the domain listed in here as the cookie domain.
// If the current URL is not one of these domains, we will use the current URL hostname as the cookie domain.
var cookieDomains = new Array( 'pennytalk.com', 'pennytalk.co.uk', 'pennytalk.ca');
var cookieDomain 	= getCookieDomain();

// Call page tracker code with proper (dynamic) cookie domain.

try{
	var pageTracker = _gat._getTracker("UA-8645489-1");
	pageTracker._setDomainName(cookieDomain);
	pageTracker._setAllowLinker(true);
	pageTracker._setAllowHash(false);
	pageTracker._trackPageview();
} catch(err) {}



/******************************************/
/************** Functions *****************/
/******************************************/

// Accepts: Nothing
// Takes current domain name from the javascript object window.location.host 
// and returns the proper cookie domain from the array cookieDomains.  
// If it doesn't find the proper domain in the array, 
// it returns the value from window.location.host.
function getCookieDomain( ){

	var thisDomainName = window.location.host;

	for (var cDom in cookieDomains){
		if ( testThisDomain( thisDomainName, cookieDomains[cDom] ) ){
			return cookieDomains[cDom];
		}
	}

	// If we've gotten this far and haven't found a cookie domain, 
	// then just return the passed in thisDomainName.
	return thisDomainName;
}

// Accepts: testDomain , controlDomain
// Returns: true | false
// This function checks to see if testDomain is equal to the controlDomain
// or a subdomain of it.  If it is one of the two it returns true, else false.
// This should be called with the current domain ( from window.location ) as the testDomain, 
// and one of domains in the global array  cookieDomains as the controlDomain. 
function testThisDomain( testDomain, controlDomain ){
	
	// If the testDomain is shorter in length then in can't be 
	// equal to or a subdomain of the controlDomain.
	if ( parseInt( testDomain.length ) < parseInt( controlDomain.length ) ){
		return false;
	}else if ( parseInt( testDomain.length ) == parseInt( controlDomain.length ) ){
		// If testDomain and controlDomain are the same size then do a simple comparison.
		if ( testDomain == controlDomain ){
			return true;
		}
	}

	// See if testDomain is a subdomain of controlDomain.
	var bPos = parseInt( testDomain.length ) - parseInt( controlDomain.length );
	if ( ( testDomain.substring( bPos ) == controlDomain ) && ( testDomain.substring( parseInt( bPos - 1), bPos ) ==  '.' ) ){
		return true;
	}else{
		return false;
	}

}
