// Attach the listener to the search box
if(window.addEventListener)
{
 window.addEventListener("load",addCookieField,true);
}
else
{
 window.attachEvent("onload",addCookieField);
}

// cookie reading script from PPK at quirksmode.org
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;
}

// pad a number to 2 digits, if it isn't already
function pad(padMe)
{
	padMe = padMe + ""; // force num to be string
	
	if(padMe.length < 2)
	{
		while(padMe.length < 2)
		{
			padMe = 0 + padMe;
		}
	}
	return padMe;
}

function addCookieField(event)
{
	//Get the data from Google Analytics and output it to a hidden field
	var cleanedCookie = "";
	var stringTokens = readCookie("__utmz");
	
	if(stringTokens)
	{
		stringTokens = stringTokens.split(".");
	
		for(i=0; i<stringTokens.length; i++)
		{
		  if(i == 2)
		  {
			cleanedCookie = cleanedCookie.concat("V=",stringTokens[i],"|");
		  }
		  else if(i == 3)
		  {
			cleanedCookie = cleanedCookie.concat("S=",stringTokens[i],"|");
		  }
		  else if(i >= 4)
		  {
			cleanedCookie = cleanedCookie.concat(stringTokens[i],".");
		  }
		}
		
		cleanedCookie = cleanedCookie.slice(0,cleanedCookie.length-1);
		cleanedCookie = cleanedCookie.replace(/\%20/g," ");
		
		var timingCookie = readCookie("__utma");
		timingCookie = timingCookie.split(".");
		
		var firstVisit = new Date();
		firstVisit.setTime(timingCookie[2]*1000);
		
		cleanedCookie = cleanedCookie.concat("|first_visit_date=",pad(firstVisit.getMonth()+1),"/",pad(firstVisit.getDate()),"/",firstVisit.getFullYear());
		cleanedCookie = cleanedCookie.concat("|first_visit_time=",pad(firstVisit.getHours()),":",pad(firstVisit.getMinutes()),":",pad(firstVisit.getSeconds()));
		
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type","hidden");
		hiddenField.setAttribute("name","ga_data");
		hiddenField.setAttribute("id","ga_data");
		hiddenField.setAttribute("value",cleanedCookie);
		
		var currentSource = document.getElementById("source");
		
		currentSource.parentNode.insertBefore(hiddenField,currentSource);
	}
}