/****************************************************
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.

****************************************************/
// Grabbed an excerpt from Clifton's script ... and then sprinkling the checkNewVisitor() and grabReferrer() 
// calls anywhere in our code where we make our pageTracker calls. - Eggers, 1:30am May 13, 2009
// http://www.advanced-web-metrics.com/scripts/first-and-last-referrer.txt
// http://www.google.com/support/forum/p/Google+Analytics/thread?tid=0e672a6afb56558c&hl=en

	function checkNewVisitor(){
	   // 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=", "|");
		  var gclid = _uGC(z,"utmgclid=","|");
		  if (gclid != "-") {
			 urchin_source = "google";
			 urchin_medium = "cpc";
		  }
		  var urchin_combined = urchin_source + " - " + urchin_medium + " - " + urchin_term;
		  //pageTracker._setVar(urchin_combined);
		  superSetVar(unescape(urchin_combined));
	   }

	}
//////////////////////////////////////////////////////////////////////////
// End of Clifton's code excerpt
//////////////////////////////////////////////////////////////////////////



	



//////////////////////////////////////////////////////////////////////////
// http://www.lunametrics.com/blog/2008/04/17/stuff-more-than-one-value-in-gas-user-defined-segment/
// "standard" read cookie function  (copied from Prusak's gwo_write.js)	

	
	function urldecode( str ) {
	    // http://kevin.vanzonneveld.net
	    // +   original by: Philip Peterson
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +      input by: AJ
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: Brett Zamir (http://brettz9.blogspot.com)
	    // +      input by: travc
	    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
	    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: Lars Fischer
	    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
	    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
	    // *     returns 1: 'Kevin van Zonneveld!'
	    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
	    // *     returns 2: 'http://kevin.vanzonneveld.net/'
	    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
	    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
	    
	    var histogram = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
	    
	    var replacer = function(search, replace, str) {
	        var tmp_arr = [];
	        tmp_arr = str.split(search);
	        return tmp_arr.join(replace);
	    };
	    
	    // The histogram is identical to the one in urlencode.
	    histogram["'"]   = '%27';
	    histogram['(']   = '%28';
	    histogram[')']   = '%29';
	    histogram['*']   = '%2A';
	    histogram['~']   = '%7E';
	    histogram['!']   = '%21';
	    histogram['%20'] = '+';
	    histogram['\u00DC'] = '%DC';
	    histogram['\u00FC'] = '%FC';
	    histogram['\u00C4'] = '%D4';
	    histogram['\u00E4'] = '%E4';
	    histogram['\u00D6'] = '%D6';
	    histogram['\u00F6'] = '%F6';
	    histogram['\u00DF'] = '%DF'; 
	    histogram['\u20AC'] = '%80';
	    histogram['\u0081'] = '%81';
	    histogram['\u201A'] = '%82';
	    histogram['\u0192'] = '%83';
	    histogram['\u201E'] = '%84';
	    histogram['\u2026'] = '%85';
	    histogram['\u2020'] = '%86';
	    histogram['\u2021'] = '%87';
	    histogram['\u02C6'] = '%88';
	    histogram['\u2030'] = '%89';
	    histogram['\u0160'] = '%8A';
	    histogram['\u2039'] = '%8B';
	    histogram['\u0152'] = '%8C';
	    histogram['\u008D'] = '%8D';
	    histogram['\u017D'] = '%8E';
	    histogram['\u008F'] = '%8F';
	    histogram['\u0090'] = '%90';
	    histogram['\u2018'] = '%91';
	    histogram['\u2019'] = '%92';
	    histogram['\u201C'] = '%93';
	    histogram['\u201D'] = '%94';
	    histogram['\u2022'] = '%95';
	    histogram['\u2013'] = '%96';
	    histogram['\u2014'] = '%97';
	    histogram['\u02DC'] = '%98';
	    histogram['\u2122'] = '%99';
	    histogram['\u0161'] = '%9A';
	    histogram['\u203A'] = '%9B';
	    histogram['\u0153'] = '%9C';
	    histogram['\u009D'] = '%9D';
	    histogram['\u017E'] = '%9E';
	    histogram['\u0178'] = '%9F';
	 
	    for (unicodeStr in histogram) {
	        hexEscStr = histogram[unicodeStr]; // Switch order when decoding
	        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
	    }
	    
	    // End with decodeURIComponent, which most resembles PHP's encoding functions
	    ret = decodeURIComponent(ret);
	 
	    return ret;
	}	

	
	
	
function read_cookie(cookie_name) {
  var my_cookie=""+document.cookie;
  var ind=my_cookie.indexOf(cookie_name);
  if (ind==-1 || cookie_name=="") return "";
  var ind1=my_cookie.indexOf(';',ind);
  if (ind1==-1) ind1=my_cookie.length; 
  return unescape(my_cookie.substring(ind+cookie_name.length+1,ind1));
}

function superSetVar(appendValue) {
  var getVar = read_cookie('__utmv');								// read the __utmv cookie
  hasValue = getVar.indexOf(appendValue);							// does the cookie already have the value we want to append?
  if ( hasValue == -1 ) {											// if the new value is not already in the cookie
    removePrefix = /^.*\.(.*)/.exec(getVar);						// __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
    if (removePrefix && removePrefix[1]) {
      newVar = removePrefix[1] + appendValue;						// append the value
    }else{
      newVar = appendValue;											// this will execute if the cookie was not already set.
    }
      if (gaCode == null) { alert('Please set "gaCode" variable in parent source.'); }
      var superSetVarTracker = _gat._getTracker(gaCode);			// set up a tracker to call _setVar from
      superSetVarTracker._initData();  
      superSetVarTracker._setVar(newVar);							// call _setVar with the new value
  }
}

function unSetVar(removeValue){
  var getVar = read_cookie('__utmv');         // read the __utmv cookie
  hasValue = getVar.indexOf(removeValue);     // does the cookie have the value we want to remove?
  if ( hasValue != -1 ) {                     // if the value is in the cookie then . . .  otherwise, there is nothing further to do.
    removePrefix = /^.*\.(.*)/.exec(getVar);  // __utmv cookie has the format 12345678.cookieValue - remove the ## prefix
    if (removePrefix && removePrefix[1]) {    // if we remove the prefix then. . .
      //
      var re = removeValue + '[^/]*';
      re = new RegExp(re,'g');
      newVar = removePrefix[1].replace(re,""); // newVar = removePrefix[1] MINUS removeValue
      //
      var superSetVarTracker = _gat._getTracker(gaCode);  // set up a tracker to call _setVar from
      superSetVarTracker._initData();  
      superSetVarTracker._setVar(newVar);                   // call _setVar with the new value
    }
    
  }
}



///////////////////////////////////////////////////////////////////////////
// Pulled from ga.js ...
function _uGC(l,n,s) {
	 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;
}

// http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLDecode (encodedString) {
	var output = encodedString;
	var binVal, thisString;
	var myregexp = /(%[^%]{2})/;
	while ((match = myregexp.exec(output)) != null
			&& match.length > 1
			&& match[1] != '') {
		binVal = parseInt(match[1].substr(1),16);
		thisString = String.fromCharCode(binVal);
		output = output.replace(match[1], thisString);
	}
  return output;
}
function URLEncode (clearString) {
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString[x] == ' ')
				output += '+';
			else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}



///////////////////////////////////////////////////////////////////////////
// http://www.epikone.com/blog/2007/10/29/integrating-google-analytics-with-a-crm/
function populateHiddenFields(f) {
	//alert('Welcome!');
	var v 	= 	unescape(_uGC(document.cookie, '__utmv=', ';'));
	var z 	= 	_uGC(document.cookie, '__utmz=', ';');
	//var source		= _uGC(v, 'ref=', '|');
	var source		= URLDecode(_uGC(z, 'utmcsr=', '|'));
	var request		= URLDecode(_uGC(v, 'req=', '|'));
	var medium		= URLDecode(_uGC(z, 'utmcmd=', '|')); 
	var keywords	= URLDecode(_uGC(z, 'utmctr=', '|')); 
	var content		= URLDecode(_uGC(z, 'utmcct=', '|')); 
	var campaign	= URLDecode(_uGC(z, 'utmccn=', '|')); 
	var gclid		= URLDecode(_uGC(z, 'utmgclid=', '|'));
	var csegment	= "";
	if (gclid !="-") { 
	      source = 'google'; 
	      medium = 'cpc'; 
	}
	
	// Populate our hidden form fields ...
	f.source.value = source;
    f.request.value = request;
    f.medium.value = medium; 
    f.keywords.value = keywords; 
    f.content.value = content; 
    f.campaign.value = campaign;
    f.segment.value = csegment;
    //alert('Welcome!');
    return true; 
} 


function commentedOut() {
	// Get the __utmz cookie value. This is the cookies that 
	// stores all campaign information. 
	// 
	var z = _uGC(document.cookie, '__utmz=', ';'); 
	// 
	// The cookie has a number of name-value pairs. 
	// Each identifies an aspect of the campaign. 
	// 
	// utmcsr  = campaign source 
	// utmcmd  = campaign medium 
	// utmctr  = campaign term (keyword) 
	// utmcct  = campaign content (used for A/B testing) 
	// utmccn  = campaign name 
	// utmgclid = unique identifier used when AdWords auto tagging is enabled 
	// 
	// This is very basic code. It separates the campaign-tracking cookie 
	// and populates a variable with each piece of campaign info. 
	// 
	var source		= _uGC(z, 'utmcsr=', '|'); 
	var medium		= _uGC(z, 'utmcmd=', '|'); 
	var keywords	= _uGC(z, 'utmctr=', '|'); 
	var content		= _uGC(z, 'utmcct=', '|'); 
	var campaign	= _uGC(z, 'utmccn=', '|'); 
	var gclid		= _uGC(z, 'utmgclid=', '|');
	
	var referrer	= document.referrer;
	var request		= document.location; if (request == null) { request = ''; }
	
	superSetVar(unescape('ref='+referrer+'|'+'req='+request+'|'));
	
	
	// The gclid is ONLY present when auto tagging has been enabled. 
	// All other variables, except the term variable, will be '(not set)'. 
	// Because the gclid is only present for Google AdWords we can 
	// populate some other variables that would normally 
	// be left blank. 
	// 
	if (gclid !="-") { 
	      source = 'google'; 
	      medium = 'cpc'; 
	} 
	// Data from the custom segmentation cookie can also be passed 
	// back to your server via a hidden form field 
	var csegment = _uGC(document.cookie, '__utmv=', ';'); 
	if (csegment != '-') { 
	      var csegmentex = /[1-9]*?\.(.*)/;
	      csegment    = csegment.match(csegmentex); 
	      csegment    = csegment[1]; 
	} else { 
	      csegment = ''; 
	} 
} 
// Commented out all of this stuff by making it a fake function.
