/*
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 Michael Harrison on 04/23/2007
*/

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 getRef()
{
    ref = document.referrer;
    re = /(\?|&)(q|p)=([^&]*)/;
    searchq = re.exec(ref);
    if(searchq) {
        __utmSetVar(searchq[3]);
    }
}

function sleuth()
{
    if (document.cookie.indexOf("__utmz=") != -1)
    {
        z = readCookie('__utmz');
        za = z.split('|');
        t = za[0].split('.');
        za[0] = t[t.length - 1];
        for (i = 0; i < za.length; i++)
        {   
            t2 = za[i].split('=');
            if (t2[0] == 'utmgclid' || t2[1] == 'cpc' || t2[1] == 'ppc')    {
                getRef();
            }
        }
    }
}