/*
Name: Google Analytics Keyword Sleuth
Author: Michael Harrison
Created: 4/14/2007
Description: If a visitor arrives from a search engine, grab their exact search query and store it in the User-Defined variable using the __utmSetVar function. Modify your existing Google Analytics call to be:

<script src="http://www.roirevolution.com/ga_keyword.js" type="text/javascript"></script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
_uacct = "UA-XXXXX-X";
urchinTracker();
sleuth();
</script>

~~~~~~
Last modified by Shawn Purtell on 06/26/2009
*/

function noPercent(x)
{
	x = unescape(x);
	return x.replace(/\+/g," ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function sleuth()
{
	if(document.location.search.indexOf("gclid")!=-1||document.location.search.indexOf("cpc")!=-1) {	
		var supercookie = 'cpc - ';
		var userdef = 'undefined';
		var stopfunction = false;
		var cpcregexp = new RegExp(/cpc/);
		ref = document.referrer;
		re = /(\?|&)(q|p|query|encquery|qt|terms|rdata|qs|wd|text|szukaj|k|searchExpr|search_for|string|search_query|searchfor)=([^&]+)/;
		searchq = re.exec(ref);
		
		if(document.cookie.indexOf('__utmv') != -1){
			userdef = readCookie('__utmv');
			if(cpcregexp.exec(userdef)){
				stopfunction = true;
			}
		}
		if(searchq && stopfunction == false) {
			searchq[3] = noPercent(searchq[3]);
			supercookie += searchq[3];
			__utmSetVar(supercookie);
		}
		else if(stopfunction == false){
			supercookie = supercookie + 'Paid Referral:' + document.referrer;
			__utmSetVar(supercookie);
		}
	}
}
