// This script will append the user id to the end of each affiliate script on the page.

// Check to see if any cookies exist on the users system - if they do check for the user id cookie
if (document.cookie.length>0) {

	// The name of the cookie that contains the user id
	var uidCookieName = "cookid";

	uidCookie = getCookie(uidCookieName);
  	if (uidCookie != null) {

		// Get an array of all 'a' elements on the page
		var pageLinks =document.getElementsByTagName('a');
		
		// Loop through each element in the returned array
		for (var i=0; i<pageLinks.length; i++) {
			
			/* Check each link to see if it's an affiliate one and if it is append the user
			id in the correct way for the affiliate */
			
			// Regular expression for *TradeDoubler*
			var RegExpTradeDoubler = /^(http:\/\/)\S*(\.tradedoubler.com\/click)\S*/;
			
			// Regular expression for *SilverTap*
			var RegExpSilverTap = /^(https:\/\/)\S*(\.silvertap.com\/Tracking)\S*/;
			
			// Regular expression for *OMG*
			var RegExpOmg = /^(http:\/\/track.omguk.com\/)\S*/;
			
			var currentLink = pageLinks[i];
		
			if (currentLink.href.search(RegExpTradeDoubler) != -1) {
				currentLink.href += "epi(" + uidCookie + ")";
			}
			
			if (currentLink.href.search(RegExpSilverTap) != -1) {
				currentLink.href += "&subid=" + uidCookie;
			}
			
			if (currentLink.href.search(RegExpOmg) != -1) {
				currentLink.href += "&UID=" + uidCookie;
			}
			
		}
		
	}
	
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


