/*
Title:   Google Analytics exact Adwords keyword tracker
Author:  Jani-Matti Hätinen <jani-matti.hatinen@iki.fi>
URL:     http://www.tulos.fi/en/exact-adwords-keywords-google-analytics/
Version: 1.0
Updated: 2008/08/20

This work is licensed under the Creative Commons Attribution-Share Alike 3.0
license. The license summary and exact license terms are available at:
http://creativecommons.org/licenses/by-sa/3.0/

This script takes the full search string used to get to your site through an
Adwords click and adds it to the User defined variable of Google Analytics.
With this script you can track and analyse the entire search strings which
show your Adwords ads and their respective performance.

The script converts the search string to lower case and can handle UTF-8
characters.

Some ideas/implementation details for this script originated from Michael
Harrison's Google Analytics Keyword Sleuth script.

This script could also be combined with an advanced Google Analytics filter in
order to utilise some other Google Analytics variable. This is useful in case you
already use User defined to track something else (such as customer groups). More
specific instructions on how to do that might be included in a later version.

This script works only with ga.js, not the earlier urchin.js. To use this script,
include this file in your page right after the code that fetches the ga.js file
from Google servers. Below is a sample implementation:
-------------------------------------------------
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script src="http://www.yourdomain.com/exact_adwords_keywords.js" type="text/javascript"></script>

<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._trackPageview();
</script>
-------------------------------------------------
*/

if (typeof(_gat)=="object") {
  var keywordTracker = _gat._getTracker("UA-1");
  keywordTracker._initData();

  if (document.location.search.match("gclid")||document.location.search.match("cpc")) {
    var eak_search_query = document.referrer.match(/(\?|&)(q|p|query)=([^&]*)/);
    if (eak_search_query) {
      var eak_keywords = decodeURIComponent(eak_search_query[3]);

      // Convert all characters to lower case
      eak_keywords = eak_keywords.toLowerCase();

      // Replace + with space and clear extra whitespace at both ends of the
      // search string
      eak_keywords = eak_keywords.replace(/\+/g,' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');

      // Set the User defined variable
      keywordTracker._setVar(eak_keywords);
    }
  }
}
