/*
estatisticas web 
signey 28/abr/2010
*/


//*****************************************
//*****************************************
function estatWeb() {
	var win = window;
	var doc = document;
	var nav = navigator;
	var nCook = '_e_stt_'; //prefixo nome cookies
	var dCook = false; //dominio cookie
	var tUg = 60000; //atualiza estat a cada minuto...
	var urlg = ''; //ult gravado
	var hst; //host location
	var hstr; //host ref..
	var ref = '';
	var url = 'http://3wsistemas.com.br/estat/';
	var urlImg = '__utm.gif'; //compativel adblock
	var dev;
	var aj;
	var Id,Ug,Clic,Cnt,ClicI,novo=false;
	setTimeout(init,100);
	//*****************************************
	this.setId = function(i) {
		Id = i;
		cookiePut('Id',Id);
		deb('gravou id='+Id);
	}
	//*****************************************
	function gravaRet() {
		//recebe pedido codigo novo.
		if (aj.readyState!=4) {
			return;
		}
		deb('gravaRet');
		novo = false;
	}
	//*****************************************
	// usuario fechando...
	function unload(ev) {
		//objNav(ev);
		//alert('by');
		deb('by grava?');
		grava();
	}
	//*****************************************
	function grava() {
		if (!dev && !novo && ref.length==0 && ms()-Ug<tUg) {
			deb('nao grava = '+(ms()-Ug));
			return;
		}
		Ug = ms();
		var un = 'Id='+Id+'&Ug='+Ug+'&Clic='+Clic
			+'&Cnt='+Cnt+'&ClicI='+ClicI
			+'&h='+(dCook?dCook:hst)+'&Ref='+escape(ref)
			//+(novo?'&novo=1':'')
		;
		deb('grava = '+url+'?'+un);

		//cookiePut('Id',Id);
		cookiePut('Ug',Ug);
		
		if (un==urlg) {
			return;
		}
		urlg = un;
		if (false) {
			//envia via ajax...
			aj.open('GET',url+'?'+urlg); //,true);
			//aj.onreadystatechange = gravaRet;
			aj.send(this.dados);
			deb('g ajax='+url+'?'+urlg);
		} else if (!novo) {
			var im = new Image();
			//im.addEventListener('load', function(){alert('load ok');}, false)
			im.src = url+urlImg+'?'+urlg;
			doc.body.appendChild(im);
			//6 g img=https://localhost/estat/??Id=19&Ug=1273693853658&Clic=1302&Cnt=35300&ClicI=16&h=localhost&Ref=
			deb('g1 img='+im.src);
			//lert(im.src);
		} else {
			//envia/recebe via js
			var o = document.createElement('script');
			o.src = url+'?'+urlg;
			doc.body.appendChild(o);
			deb('g script='+url+'?'+urlg);
		}
		novo = false;
		
	}
	//*****************************************
	function semCook() {
	}
	//*****************************************
	function init() {
		//dev?
		dev = (''+win.location).indexOf('://localhost/')!=-1
			|| (''+win.location).indexOf('&dev=1')!=-1
		;
		url = dev?'http://localhost/estat/':url;
		//prefixo cookie
		try {
			nCook = typeof(_e_stt_nCook)?_e_stt_nCook:'_e_stt_';
		} catch (e) {}
		
		//referencia...
		hst = host(win.location);
		//dominio cookie
		if (!dev) {
			dCook = hst;
			try {
				dCook = dev?false:(typeof(_e_stt_dCook)?_e_stt_dCook:hst);
			} catch (e) {}
		}
		
		hstr = host(doc.referrer);
		if (hstr.length!=0 && hst!=hstr) {
			ref = doc.referrer;
		}
		deb('v1 domCook='+dCook+' h='+hst+' r='+hstr+' ref='+ref);
		
		
		aj = ajaxO();
		if (!nav.cookieEnabled) {
			semCook();
			return;
		}
		//fim
		if (win.attachEvent) {
			win.attachEvent('onunload', unload);
		} else {
			deb('sem attach');
			win.addEventListener('unload', unload, false);
		}
		/*objNav(navigator);
		deb('init='+win.location
			+'\n\nbr='+nav.userAgent
			+'\n\nreferrer='+doc.referrer
		);
		*/
		//tem cook
		Id =  cookieGet('Id');
		Clic = 1 + (1*cookieGet('Clic'));
		cookiePut('Clic',Clic);
		Ug = 1*cookieGet('Ug');
		Cnt = 1*cookieGet('Cnt');
		ClicI = (hstr.length==0?1:0) + 1*cookieGet('ClicI');
		if (!Id) {
			novo = true;
			Id = novoId();
			grava();
			return;
		}
		deb('ja existe Id='+Id+' Ug='+Ug+' Clic='+Clic+' Cnt='+Cnt+' ClicI='+ClicI);
		if (hstr.length==0) {
			//ta nos favoritos ou digitou dominio
			deb('Clic I');
			cookiePut('ClicI',ClicI);
		}
		grava();
	}
	//********************
	function host(tx) {
		tx = ''+tx;
		var p = tx.indexOf('://');
		if (p!=-1) {
			tx = tx.substring(p+3);
		}
		if (tx.substring(0,4)=='www.') {
			tx = tx.substring(4);
		}
		p = tx.indexOf('/');
		if (p!=-1) {
			tx = tx.substring(0,p);
		}
		return trimm(''+tx);
	}
	//********************
	function deb(tx) {
		try {
			if (dev) {
				debJ(tx);
			}
		} catch (e) {
		}
	}
	//********************
	function novoId() {
		return ''+ms();
	}
	//********************
	function ms() {
		return (new Date()).getTime();	
	}
	//********************
	function cookieGet(nome) {
		nome = nCook+nome;
		var co = document.cookie+';';
		var i = co.indexOf(nome+'=');
		var f = co.indexOf(';',i+nome.length+1);
		if (i==-1 || f<=i) {
			return null;
		} else {
			return unescape(co.substring(i+nome.length+1,f));
		}
	}
	//********************
	function cookiePut(nome,vlr,venceDias) {
		nome = nCook+nome;
		if (venceDias!=0 && vazio(venceDias)) {
			venceDias = 120;
		}
		var v = new Date();
		v.setTime(v.getTime() + 1000*60*60*24*venceDias);
		v = v.toGMTString();
		var vv = nome + '=' + vlr
			+(venceDias==0?'' : '; expires=' + v)+'; path=/'
			+(dCook?'; domain='+dCook:'')
		;
		deb('deb = '+vv);
		document.cookie = vv;
	}
	//********************
	function ajaxO() {
		var xmlhttp = false;
		if (typeof(XMLHttpRequest)!='undefined') {
			try {
					xmlhttp = new XMLHttpRequest();
			} catch (e) {
					xmlhttp = false;
			}
		} else  {
			try {
					var b = (true?"Microsoft.XMLHTTP":"Msxml2.XMLHTTP");
					xmlhttp = new ActiveXObject(b);
			} catch (e) {
					xmlhttp = false;
			}
		}
		return xmlhttp;
	}

	//**************************************
	function trimm(a,b) {
		var i,t;
		if (typeof(a)=='undefined') {
			return '';
		}
		if (typeof(b)=='undefined') {
			b = ' \n\r\t';
		}
		if (typeof(a)!='string') {
			debJ(erro('trimm não string: '+a));
			return '';
		}
		//retira do inicio
		t = a.length-1;
		if (t<0) return a;
		i = 0;
		while (i<t & b.indexOf(a.substring(i,i+1))>-1) i++;
		if (i!=0) a = a.substring(i,t+1);
		//retira do fim
		t = a.length;
		if (t<1) return a;
		i = t-1;
		while (i>-1 && b.indexOf(a.substring(i,i+1))>-1) i--;
		if (i!=t-1) a = a.substring(0,i+1);
		return a;
	}
	//*******************************//
	function vazio(a) {
		try {
			if ((a==null || typeof(a)=='undefined')) {
				return true;
			} else if (typeof(a)=='object') {
				return objLen(a)==0;
			} else {
				return (typeof(a)=='string' && trimm(a)=='');
			}
		} catch (e) {
			//lert('erro testando vazio(): '+erro(e)+' obj='+a);
			//objNav(e);
			return true;
		}
	}
}

var O_e_sTt_ = new estatWeb();


/*

Objeto: [object Navigator]
24 (limite 200) (Todos=24) (string=13) (object=3) (boolean=2) (function=6)
Chave:
string userAgent: Mozilla/5.0 (X11; U; Linux i686; pt-BR; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
string vendor:
string platform: Linux i686
string appCodeName: Mozilla
string appName: Netscape
string appVersion: 5.0 (X11; pt-BR)
string language: pt-BR
object mimeTypes: [object MimeTypeArray]
string oscpu: Linux i686
string vendorSub:
string product: Gecko
string productSub: 20100401
object plugins: [object PluginArray]
string securityPolicy:
boolean cookieEnabled: true
boolean onLine: true
string buildID: 20100401074458
function javaEnabled: function javaEnabled() { [native cod...(+44)
function taintEnabled: function taintEnabled() { [native co...(+45)
function preference: function preference() { [native code...(+43)
object geolocation: [object GeoGeolocation]
function registerContentHandler: function registerContentHandler() { ...(+55)
function registerProtocolHandler: function registerProtocolHandler() { ...(+56)
function mozIsLocallyAvailable: function mozIsLocallyAvailable() { [...(+54)
FIM...


Objeto: [object XMLHttpRequest]
29 (limite 200) (Todos=29) (function=12) (object=9) (number=2) (string=3) (boolean=3)
Chave:
function addEventListener: function addEventListener() { [nativ...(+49)
function dispatchEvent: function dispatchEvent() { [native c...(+46)
function removeEventListener: function removeEventListener() { [na...(+52)
function open: function open() { [native code] }
object onreadystatechange: [xpconnect wrapped nsIDOMEventListener]
function send: function send() { [native code] }
number readyState: 4
string responseText:
string channel: ?erro:Error: Permissão negada a <http://localhost> para ler a propriedade XMLHttpRequest.channel
object responseXML: null
number status: 0
string statusText: OK
function abort: function abort() { [native code] }
function getAllResponseHeaders: function getAllResponseHeaders() { [...(+54)
function getResponseHeader: function getResponseHeader() { [nati...(+50)
function sendAsBinary: function sendAsBinary() { [native co...(+45)
function setRequestHeader: function setRequestHeader() { [nativ...(+49)
function overrideMimeType: function overrideMimeType() { [nativ...(+49)
boolean multipart: false
boolean mozBackgroundRequest: false
boolean withCredentials: false
object upload: [object XMLHttpRequestUpload]
object onuploadprogress: null
object onabort: null
object onerror: null
object onload: null
object onloadstart: null
object onprogress: null
function getInterface: function getInterface() { [native co...(+45)

*/






