/*
log.js

Sets cookie, records the start and end time of user's visit to page
saves to database via AJAX call

Created by Brad Hinchliffe, Net Dynamics January 2009 (http://www.netdnx.com)
*/

var start_time=new Date().getTime();								// Page open start time
var exit_time=new Date().getTime();									// Page exit time (initial value is page open start time)
var expires=new Date(new Date().getTime() +  (365 * 24 * 60 * 60 * 1000)).toGMTString();	// 1 Year from now
var visid="";

function getCookie(cname)
{
	if(document.cookie)
	{
		index = document.cookie.indexOf(cname);
		if (index!=-1)
		{
			cstart = (document.cookie.indexOf("=", index) + 1);
			cend = document.cookie.indexOf(";", index);
			if (cend==-1)
				cend = document.cookie.length;
			cval = document.cookie.substring(cstart, cend);
			return cval;
		}
	}
	return false;
}

function setCookie(cname,cval)
{
	document.cookie = cname +"=" + cval + ";expires="+ expires + "; path=/";
}

function pageOpen()
{
	visid=getCookie('VISID');									// Get the visitor ID from cookie
	if (!visid)												// Not set yet
	{
		visid=Math.random();									// Set new visid
		setCookie('VISID',visid);								// Store as cookie
	} 
	start_time=new Date().getTime();	  					// Page open start time
}

function pageExit()
{
	exit_time=new Date().getTime();						// Page exit time - Visitor is leaving
	uexit_time  = Math.ceil(exit_time/1000);			// Convert to Unix timestamp
	ustart_time = Math.ceil(start_time/1000);			// Convert to Unix timestamp
	page_time=uexit_time-ustart_time;								// Unix seconds on page
	storeVisitorExit(page,page_time);								// Ajax function to store visitor exit time
}


var xmlHttp=null;
function storeVisitorExit(page,page_time)
{
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	var url="store.php?ptime=" + page_time + "&page=" + page;
	xmlHttp.onreadystatechange= function()
	{
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		{
			resp=xmlHttp.responseText;							// Fire a success event if you want
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}





