//Used on initial page load to record webstat data.

var session_id;
$(document).ready(function(){
		
	webstat("");
	});
$(window).unload(function(){
	webstat_unload();
	
})

function webstat(InboundJSON)
{
	var d = document;var l = d.location;var n = navigator;var s_id;var p_id;var ReturnObject = {};
	//first import json object containing important server side stuff
	if(InboundJSON != "")
	{
		var InboundObject = JSON.parse(InboundJSON);
		if(InboundObject['session_id'] != "")
		{
			ReturnObject['s_id'] = InboundObject['session_id'];
			s_id = InboundObject['session_id']; 		
		}
		
		if(InboundObject['pass_through'] != "")//data to go back with request
		{
			ReturnObject['pass_through'] = InboundObject['pass_through'];
		}
	}	
	//then check and / or set perstat_id cookie
	if($.cookie('per_id') && $.cookie('per_id') != "false")
	{
		p_id = $.cookie('per_id').toString();
	}
	else
	{
		if(n.cookieEnabled != true)
		{
			p_id = "false";	
		}
		else
		{
			var ra=Math.floor(Math.random()*1000000);
			var d = new Date();
			p_id = (ra * d.getTime()).toString();
		}
	}
	
	//work out the domain and set cookie to .<domain>
	var mat = l.host.replace(new RegExp(/^www\./i),".");
	$.cookie('per_id', p_id, { expires: 150, domain: mat});

	if (d.referrer && d.referrer!="")
	{
		ReturnObject['referer'] = d.referrer;
	}
	ReturnObject['current_url'] = l.href;
	ReturnObject['screen_width'] = screen.width;
	ReturnObject['screen_height'] = screen.height;
	ReturnObject['ua'] = n.userAgent;	
	ReturnObject['p_id'] = p_id;
		
	//send to server
	//var obj = JSON.stringify(ReturnObject)
	$.ajax({
	type : "POST", 
	cache : false,
	url : '/stat_request/stat_log',
	//data : {"json" : obj}, 
	data : ReturnObject, 
	success : function(d){
		session_id = d;}});	
	return false;
}

function webstat_unload()
{
	$.ajax({
	type : "POST", 
	cache : false,
	url : '/stat_request/stat_unload_log',
	data : {"s_id" : session_id}
	});
}
