/****************************************************
Author: Brian J Clifton, fix by Lary Stucker-http://freshclicks.net, June 2008
Url: http://www.advanced-web-metrics.com
This script is free to use as long as this info is left in

Script for tracking the first and last referrer of a visitor

All scripts presented have been tested and validated by the author and are believed to be correct
as of the date of publication or posting. The Google Analytics software on which they depend is
subject to change, however; and therefore no warranty is expressed or implied that they will
work as described in the future. Always check the most current Google Analytics documentation.

****************************************************/

function _uGC(l,n,s) {
	// used to obtain a value form a string of key=value pairs
	if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
	var i,i2,i3,c="-";
	i=l.indexOf(n);
	i3=n.indexOf("=")+1;
	if (i > -1) {
		i2=l.indexOf(s,i); if (i2 < 0) { i2=l.length; }
		c=l.substring((i+i3),i2);
	}
	return c;
}

function checkFirst(){
	// check if this is a first time visitor
	newVisitor = 0;
	var myCookie = "" + document.cookie + ";";
	var searchName = "__utma=";
	var startOfCookie = myCookie.indexOf(searchName);
	if (startOfCookie == -1) { // i.e. first time visitor
		newVisitor = 1;
	}
}

function grabReferrer(){
	// grab campaign and referrer info from the _utmz cookie
	if (newVisitor) {
		var z = _uGC(document.cookie, "__utmz=", ";");
		urchin_source = _uGC(z,"utmcsr=", "|");
		urchin_medium = _uGC(z,"utmcmd=", "|");
		urchin_term = _uGC(z,"utmctr=", "|");
		urchin_content = _uGC(z,"utmcct=", "|");
		urchin_campaign = _uGC(z,"utmccn=", "|");
		
		if (urchin_term != undefined) {
			var urchin_combined = urchin_source + "/" + urchin_medium + " - " + urchin_term;
		} else {
			var urchin_combined = urchin_source + "/" + urchin_medium;
		}
		
		var gclid = _uGC(z,"utmgclid=","|");
		if (gclid) {
			urchin_source = "google";
			urchin_medium = "cpc";
		}
		
		
		pageTracker._setVar(urchin_combined);
	}
}
