/****************************************************
     Author: Brian J Clifton
     Url: http://www.advanced-web-metrics.com
     This script is copyright Brian Clifton and is NOT free to use without a license.
     
     DESCRIPTION: Script for tracking the number of search results clicked on per visitor's
	search i.e. visitors conducts search, clicks on 3 results. User Defined varaible (setVar) = 3.
	Visitors then conducts another search, clicks on no results. setVar is reset (0) for new 
	search and not incremented as no search results are clicked on.

	setVar expires after 1 hour - can be adjusted.
****************************************************/
// Last updated Aug-2009. 

var result = 0;
function readCookie() {
// read cookie info
	var myCookie = " " + document.cookie + ";";
	var searchName = " __searchCount=";
	var cookieVal = 0;
	var startOfCookie = myCookie.indexOf(searchName)
	var endOfCookie;

	if (startOfCookie != -1) {
		startOfCookie += searchName.length; 				// skip past cookie name
		endOfCookie = myCookie.indexOf(";", startOfCookie);	
		cookieVal = parseInt(unescape(myCookie.substring(startOfCookie,endOfCookie)));
		if (!isNaN(cookieVal)) {
		    result += cookieVal;
		}
        }
	return result;
}

function Set_searchCount() {
// read cookie __searchCount and increment for each search clickthrough
	readCookie()
	if(result == ""){result = 1}else{result++;}
	document.cookie = "__searchCount="+escape(result)+";path=/";
}

function Clear_searchCount(){
// reset if visitor conducts new search
	var ThreeDays = 3 * 24 * 60 * 60 * 1000;
	var expDate = new Date();
	expDate.setTime (expDate.getTime() - ThreeDays);
	document.cookie = "__searchCount=0; path=/";
}

function _uDomain() {
// returns hash of domain
	var d=document.domain;
	if (d.substring(0,4)=="www.") {
		d=d.substring(4,d.length);
	}
	d=d.toLowerCase(); 
	return _uHash(d);
}

function _uHash(d) {
// hash function
	if (!d || d=="") return 1;
	var h=0,g=0;
	for (var i=d.length-1;i>=0;i--) {
		var c=parseInt(d.charCodeAt(i));
		h=((h << 6) & 0xfffffff) + c + (c << 14);
		if ((g=h & 0xfe00000)!=0) h=(h ^ (g >> 21));
	}
	return h;
}

function Set_utmSetVar(){
// read __searchCount and write back to utmv cookie with expiry of 1 hour
	readCookie();
	//pageTracker._setVar(result); // old ga.js method deprecated

	//new async method
	_gaq.push(['_setVar','COOKIE_NAME']);

	date = new Date();
	date.setTime(date.getTime() + 1*60*60*1000);
	document.cookie = "__utmv="+_uDomain()+"."+escape(result)+";path=/; expires="+date.toGMTString()+";"
}

