/*
	Functions for use with Share-a-sale ande Paypal IPN
	Include this script at the BOTTOM of all pages in the site
	expecting affiliate links.
*/

// This is all we need to do everything
// The argument should match the tracking
// gap set in Share-a-sale account
checkSAS(60);
setFormSAS();

/********************************************************************/
// Nothing to see here.....

// Check for ssaid in URL query string. Save to cookies if found
function checkSAS(nGap) {
	if (window.location.search) {
		var aCookie = document.cookie.split(/;/);
		var aSearch = window.location.search.substr(1).split(/&/);
		var aVar;

		for (var i in aSearch) {
			aVar = aSearch[i].split(/=/);
			if (aVar[0].toLowerCase() == 'ssaid') {
				setCookie('ssaid', aVar[1], nGap);
			}
		}
	}
}

// If ssaid variable is found in cookies and there is a paypal form
// on the page with a 'custom' hidden field - update the custom value
// with 'ssaid=<value>'
function setFormSAS() {
	var aCookie = document.cookie.split(/;/);
	var aVar, cKey, oForm, oCust;
	
	for (var i in aCookie) {
		cKey = aCookie[i].substring(1,6);
		if ( cKey == 'ssaid' ) {
			for (var j=0; j<document.forms.length; j++) {
				oForm = document.forms[j];
				if ( (oCust = findElement(oForm, 'custom')) && findElement(oForm, 'business') && oForm.action.toLowerCase().indexOf("paypal") >= 0 ) {
					oCust.value = aCookie[i];
				}
			}
		}
	}
}

function findElement(oForm, cName) {
	var o;
	for (var i=0; i<oForm.elements.length; i++) {
		o = oForm.elements[i];
		if ( o.name && o.name.toLowerCase() == cName.toLowerCase() )
			return o;
	}
}

function setCookie(cookieName, cookieValue, nDays) {
	var cCookie = cookieName + "=" + escape(cookieValue);
	var cExpire = "";

	if ( (nDays != null) && (nDays > 0) ) {
		var dToday = new Date();
		
		cExpire = new Date();
		cExpire.setTime(dToday.getTime() + 3600000*24*nDays);
		cExpire = ";expires=" + cExpire.toGMTString();
	}
	document.cookie = cCookie + cExpire;
}