/**
* Strip the affiliate source ID out of the URL query string and return the value.
* The id for the recipient must be in the query string as "source" and the query
* string must use standard name value pair structures.
*/
function getAffiliateId(){
	var affiliateId = -1;
	var aQueryStringFull = window.location.search;
	var aQueryStringClean = aQueryStringFull.slice(1, aQueryStringFull.length);
	var aQueryStringArray = aQueryStringClean.split("&");         

	// Loop through all query string parameters and find the affiliate Id
	for(index=0; index<aQueryStringArray.length; index++)
	{
		aVarArray = aQueryStringArray[index].split("=");

		if(aVarArray[0]=="utm_source")
		{
			affiliateId = aVarArray[1];
		}
                else if(aVarArray[0]=="source"){
			if(aVarArray[1]=="aw"){
				affiliateId = 'AW2453';
			}			
		}				
	} 

	return affiliateId;
}

/**
* Create a cookie to hold the affiliate tracking data for future use within this browser session.
* The cookie will be called "affiliateTrackingCookie".
*/
function createAffiliateCookie()
{
	var affiliateId = -1;

	// Load the value of the cookie from the current page
	affiliateId = getAffiliateId();

	// Put the cookie into the current domain (the site must use the cookie from the same domain as it is created)
	if(affiliateId!=-1)
	{
		var affiliateDays = new Date();
		affiliateDays.setDate(affiliateDays.getDate() + 45);
		
		document.cookie = "affiliateTrackingCookie=" + escape(affiliateId) + "; expires=" + affiliateDays.toGMTString();
	}
}

/**
* Get the value of the cookie from the browser
*
* @return	string	affiliate sourec ID from cookie or -1
*/
function getAffiliateTrackingCookie()
{
	var affiliateCookieName = "affiliateTrackingCookie";
	var affiliateStart = document.cookie.indexOf(affiliateCookieName + "=");
	var affiliateCookieVal = -1;

	if(affiliateStart!=-1)
	{
		// Get the value of the cookie (affiliateId)
		var affiliateLen = affiliateStart + affiliateCookieName.length + 1;
		var affiliateEnd = document.cookie.indexOf(";", affiliateLen);
	
		if(affiliateEnd==-1)
		{	
			affiliateEnd = document.cookie.length;
		}
		affiliateCookieVal = unescape(document.cookie.substring(affiliateLen, affiliateEnd));
	}

	return affiliateCookieVal;
}
