// ==UserScript==
// @name           Use My Amazon Affiliate Code
// @namespace      http://www.lmnopc.com/greasemonkey/
// @description    Puts your own Amazon affiliate ID in Amazon links
// @include        http://*
// @include        https://*
// ==/UserScript==

/*

ThomW ~ www.lmnopc.com
11-27-2007

I rewrote the entire script and just kept one thing --
at_amazon and the check to make sure we're not there.
So thanks to Johan Sundström for that.  If you want
his version of this script for some unknown reason, you
can find it at http://www.lysator.liu.se/~jhs/userscript

This script had HUGE problems on pages with a ton of links,
so I modified it to use an XPath so we could work with an
array of just the links to Amazon on the page instead of
every link on the page.

Runtimes on the latestchatty thread on Shacknews went from
a ridiculous 900ms down to a very tolerable 19ms.


2008-12-15 : Thanks to help from the most excellent MisterPhoton I corrected the problem where it added a bunch of tags instead of just one

*/

	var benchmarkTimer = null; var scriptStartTime = getTime(); function getTime() { benchmarkTimer = new Date(); return benchmarkTimer.getTime(); }

	const affiliate = '11-13-71-20';
	const at_amazon = /(.*\.)?amazon\.(com|[a-z]{2}(\.[a-z]{2})?)$/i;

	// Don't run when at amazon
	if( location.hostname.match( at_amazon ) )
	{
		return;
	}

	// Do XPath to find all the links to amazon on the page
	var items = document.evaluate("//a[contains(@href, 'amazon.')]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

	mainloop: for (l = null, i = 0; l = items.snapshotItem(i); i++)
	{
		// Look for other associates ids and strip them out and replace them with my own
		var found = false;
		var arr = l.pathname.split('/');
		for (var n = 0; n < arr.length; n++)
		{
			// If affiliate id is found, replace it with mine, reassemble the string and continue
			if (arr[n].substr(-3) == '-20')
			{
				arr[n] = affiliate;
				l.pathname = arr.join('/') + l.search;
				continue mainloop;
			}
		}

		// If there's no querystring, just append the affiliate id and continue the main loop
		if (!l.search)
		{
			l.pathname += '?tag=' + affiliate;
			continue mainloop;
		}

		// Search querystring for tag=
		else
		{
			tmp = l.search;

			// chop off the leading ?
			if (tmp.substr(0,1) == '?')
			{
				tmp = tmp.substr(1);
			}

			// split the variables into pairs
			var pairs = tmp.split('&');
			for (n = 0; n < pairs.length; n++)
			{
				var v = pairs[n].split('=');

				// Look for tag
				if (v[0] == 'tag')
				{
					// Found!  Replace with affiliate value
					v[1] = affiliate;

					// Join his pair back together
					pairs[n] = v.join('=');

					// Set search
					l.search = '?' + pairs.join('&');

					// Continue the main loop
					continue mainloop;
				}
			}

			// If we hit this point, append affiliate using tag=
			l.search += '&tag=' + affiliate;
		}
	}

	GM_log((getTime() - scriptStartTime) + 'ms');

