// Set this to false to prevent automatically calling __wq_fr_handleRefererRedirect()
// with no arguments, so it can be called either at a later time, or with arguments,
// or both.
var __wq_fr_autoHandleRefererRedirect;

// If this is set to a non-empty string, it becomes the URL that the first redirect
// goes to (the redirect when the cookie is set).
// It should NOT contain any request parameters (they will be stripped any way).
// This can also be a either relative path (as in <page-name>) or a site-relative
// path (as in /<path-to-dir>/<page-name>).
// WARNING: This MUST be in the same domain as the original page, otherwise the
// redirect will break because of the inability to read the cookie.
var __wq_fr_redirURL;

// If this is set to a non-empty string, it becomes the prefix that is prepended to
// the /cplc.php or /ec.php URI, so that these can be on a different domain, for example.
var __wq_fr__clickLoggerPrefix;

function __wq_fr_getQueryVariable(name) {
	var vars = window.location.search.substring(1).split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (decodeURIComponent(pair[0]) == name) {
			return (pair.length >= 2) ? decodeURIComponent(pair[1].replace('+', ' ')) : '';
		}
	}
	return null;
}

function __wq_fr_getCookie(name) {
	if (document.cookie.length > 0) {
		c_start=document.cookie.indexOf(name + '=');
		if (c_start!=-1) {
			c_start=c_start + name.length+1;
			c_end=document.cookie.indexOf(';',c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return decodeURIComponent(document.cookie.substring(c_start,c_end));
		}
	}
	return null;
}

function __wq_fr_setCookie(name, value, expirationDays) {
	if (expirationDays == null) {
		expirationDays = 0;
	} else {
		expirationDays = Number(expirationDays);
	}
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+((expirationDays > 0) ? expirationDays : 0));
	document.cookie =
		name+'='+encodeURIComponent(value)+';path=/'+
		((expirationDays == 0) ? '' : ';expires='+exdate.toGMTString());
}

// Arguments to this function are optional.
// If arguments are passed, they are the names of the request
// parameters which are to be included in the referer URL.
// Note: The referer URL cannot include the "wq_fr_clk" request parameter,
// as that would cause an infinite redirect loop.
function __wq_fr_handleRefererRedirect() {
	var wq_fr_clk = __wq_fr_getQueryVariable('wq_fr_clk');
	if ( (wq_fr_clk != null) && (wq_fr_clk != '') && (parseInt(wq_fr_clk) != 0) ) {
		// First step: we get a wq_fr_clk request parameter which is set to non-zero.
		// We set a cookie named wq_fr_clkparams which has all of the request parameters
		// that were passed in on this request.
		// Then we remove all request parameters except for "q" (the query string)
		// or any request parameters that are named in the arguments passed to this
		// function, and redirect to ourselves.
		// We also set a cookie named wq_fr_referer which has the original URL from which
		// we redirect. We'll use this cookie to set the "referer" request parameter when
		// redirecting to the click logger script.
		__wq_fr_setCookie(
			'wq_fr_clkparams',
			window.location.search.substring(1),
			0							// expires when browser is closed
		);
		__wq_fr_setCookie(
			'wq_fr_referer',
			( (typeof(document) != 'undefined') && (typeof(document.referrer) != 'undefined') ) ?
				document.referrer : '',
			0							// expires when browser is closed
		);
		// Get the redirect URL and strip all request parameters off of it.
		var redirURL;
		if (   (typeof(__wq_fr_redirURL) != 'undefined')
			&& (__wq_fr_redirURL != null)
			&& (__wq_fr_redirURL != '')   ) {
			redirURL = __wq_fr_redirURL;
		} else {
			redirURL = window.location.href;
		}
		if (redirURL.indexOf('?') >= 0) redirURL = redirURL.substring(0, redirURL.indexOf('?'));
		// Put back only the query parameters which we want to preserve in the referer URL.
		var sep = '?';
		var vars = window.location.search.substring(1).split('&');
		var namesSoFar = [];
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split('=');
			var name = decodeURIComponent(pair[0]);
			if (name != 'wq_fr_clk') {
				// Never put the same parameter on twice.
				var isDup = false;
				for (var nm in namesSoFar) {
					if (namesSoFar[nm] == name) {
						isDup = true;
						break;
					}
				}
				if (isDup) continue;
				namesSoFar[namesSoFar.length] = name;
				// Tack this parameter onto the URL, as needed.
				if (arguments.length > 0) {
					for (var j = 0; j < arguments.length; j++) {
						if (name == arguments[j]) {
							redirURL += sep+pair[0]+'='+pair[1];
							if (sep == '?') sep = '&';
							break;
						}
					}
				} else if (name == 'q') {
					redirURL += sep+pair[0]+'='+pair[1];
					if (sep == '?') sep = '&';
				}
			}
		}
		// Redirect to the URL we want to use for the referer URL.
		window.location.href = redirURL;
	} else {
		// Second step: we receive the wq_fr_clkparams cookie which we set in the previous step.
		// Extract the parameters from the cookie, unset the cookie, and do a JavaScript
		// redirect to cplc.php (or ec.php if the ec param is present and non-zero) with
		// the parameters tacked onto the URL.
		// The redirect is done in JavaScript, so it looks as if we came from this page
		// (because of the referer being set by the JavaScript redirect), with only the
		// "q" request parameter set.
		var clickParams = __wq_fr_getCookie('wq_fr_clkparams');
		__wq_fr_setCookie('wq_fr_clkparams', '', -1);	// expired yesterday
		if ( (clickParams != null) && (clickParams != '') ) {

			var ec = 0;
			var vars = clickParams.split('&');
			var qs = '', sep = '';
			var namesSoFar = [];
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split('=');
				var name = decodeURIComponent(pair[0]);
				// Never put the same parameter on twice.
				var isDup = false;
				for (var nm in namesSoFar) {
					if (namesSoFar[nm] == name) {
						isDup = true;
						break;
					}
				}
				if (isDup) continue;
				namesSoFar[namesSoFar.length] = name;
				// Interpret or tack this parameter on, as needed.
				if (name == 'ec') {
					ec = parseInt(decodeURIComponent(pair[1]));
				} else if (name == 'referer') {
					// Don't allow the 'referer' parameter to be taked on here;
					// we'll get it from the cookie below.
				} else if ( (name.length < 6) || (name.substring(0, 6) != 'wq_fr_') ) {
					qs += sep+pair[0]+'='+pair[1];
					if (sep == '') sep = '&';
				}
			}
			var clickURL;
			if (ec != 0) {
				clickURL = '/ec.php?feedredir=1';
				sep = '&';
			} else {
				clickURL = '/cplc.php';
				sep = '?';
			}

			// Prepend prefix to click logger URL if needed.
			if (   (typeof(__wq_fr__clickLoggerPrefix) != 'undefined')
				&& (__wq_fr__clickLoggerPrefix != null)
				&& (__wq_fr__clickLoggerPrefix != '')   ) {
				var __tmp__ = __wq_fr__clickLoggerPrefix;
				while ( (__tmp__.length > 0) && (__tmp__.substr(-1) == '/') ) {
					__tmp__ = __tmp__.substr(0, __tmp__.length-1);
				}
				clickURL = __tmp__ + clickURL;
			}

			// Append remaining parameters to click logger URL.
			if (qs != '') {
				clickURL += sep+qs;
				sep = '&';
			}
			var referer = __wq_fr_getCookie('wq_fr_referer');
			__wq_fr_setCookie('wq_fr_referer', '', -1);	// expired yesterday
			if ( (referer != null) && (referer != '') ) {

				clickURL += sep+'referer='+encodeURIComponent(referer);
				sep = '&';
			}

			// Do redirection.
			if (document.all) {
				if (!document.body) {
					document.appendChild(document.createElement('body'));
				}
				document.body.innerHTML =
					'<a id="cl" href="'+clickURL+'" style="visibility: hidden">-</a>';
				document.getElementById('cl').click();
			} else {
				window.location.href = clickURL;
			}
		}
	}
}

if (   (typeof(__wq_fr_autoHandleRefererRedirect) == 'undefined')
	|| (__wq_fr_autoHandleRefererRedirect)   ) {
	__wq_fr_handleRefererRedirect();
}
