var str = "";
var domain_name = "itrack.ru";
var x,y, oldx, oldy;
var window_w=0,window_h=0,window_x=0,window_y=0;
var counter=0, lastcounter=0;
var step = 0;			// Порог чувствительности к движению px 
var delay = 1; 		// Порог чувствительности к задержке в мс
var limit_sec = 60;		// Лимит простоя мышки в секундах
var stat_length = 15000;   // Лимит передаваемых данных (в байтах)
var record_step = 1;  	// Шаг записи
var elFocus = null;
var prevElFocus = null;
var traps = new Array();
var coordsInitiated = 0;
var counterID;

isComp = (document.body.attachEvent && encodeURIComponent) ? true : false;

if (isComp) {
   document.body.attachEvent('onmousemove', captureMove);
//   document.body.attachEvent('onmouseout', compressData);
   document.body.attachEvent('onclick', captureClick);
   document.body.attachEvent('onkeypress', captureKeyPress);
   if (navigator.appName=='Opera') { document.body.onunload=captureClose; } else { document.body.onbeforeunload=captureClose; }
   initiateTraps();
   writeHeader();

   // SCROLL INITIATE 
   var bodyls = document.body.scrollLeft;
   var bodyts = document.body.scrollTop;
   str += 'bi'+bodyls+'.'+bodyts+';';
   runCounter();
} else {
   writeHeader();
   str+="x;";
   sendData();
}

function initiateTraps() {
  for (var i in document.all) {
     var el = document.all[i];
     if (el.traceEvents) {
        var j = traps.length;
        traps[j] = new Array();
        traps[j][0] = el.id;
        traps[j][1] = new Array();
        traps[j][1] = el.traceEvents.split(",");       
        for (var k in traps[j][1]) {
	     el.attachEvent(traps[j][1][k], traceCustomEvent);
	 }
     }
  }
}



function traceCustomEvent() {
   var srcEl = event.srcElement;
   var type = event.type;
   while (!eval("srcEl.on"+type)) {
     srcEl = srcEl.parentElement;
   }
   str+='e'+srcEl.id+'='+type+';'; 
}

function writeHeader() {
   var from = document.referrer;
   var app=0;
   switch (navigator.appName) {
      case 'Opera': app = 1; break;
      case 'Netscape': app = 2; break;
      case 'Microsoft Internet Explorer': app = 3; break;
      default: break;
   }
   var appv = navigator.appVersion;
   appv = appv.substr(0,1);
   app+=','+appv;
   str+="br="+app+";";
   if (!from) { from = "bm"; }
   str+="from="+from+";";
}

function runCounter() {
   counter++;
   if (counter*record_step>limit_sec*1000) counter=0;
   var window_resized = false;
   if (str.length>stat_length) { str = ''; }

   // capturing scroll

   var bl = document.body.scrollLeft;
   var bt = document.body.scrollTop;
   var dbl = Math.abs(bodyls-bl);
   var dbt = Math.abs(bodyts-bt);

   if (dbl>step || dbt>step) {
     str += (dbl>step ? (bl-bodyls) : '')+','+(dbt>step ? (bt-bodyts): '')+';';
     var d = counter-lastcounter;
     if (d*record_step>=delay) { str+='s'+(d>1 ? d : '')+';'; }
     lastcounter = counter;
   }

   bodyls = bl;
   bodyts = bt;

   // capturing mouse move

   var dbx = Math.abs(x-oldx);
   var dby = Math.abs(y-oldy);

   if (coordsInitiated) { 
      if (dbx>step || dby>step) {
         str+= (dbx>step ? (x-oldx) : '')+"."+(dby>step ? (y-oldy) : '')+";";
         oldx = x;
         oldy = y;
         var d = counter-lastcounter;
         if (d*record_step>=delay) { str+='s'+(d>1 ? d : '')+';'; }
         lastcounter = counter;
      }
   }

   // MAXIMIZE, MINIMIZE capturing included

   // capturing window resizing
  var wnd_w = document.body.clientWidth;
  var wnd_h = document.body.clientHeight;
  if (Math.abs(window_w-wnd_w)>step || Math.abs(window_h-wnd_h)>step) {
     str += 'w'+wnd_w+'.'+wnd_h+';';
     window_resized = true;
     window_w = wnd_w;
     window_h = wnd_h;
  }

   // capturing window moving
   var wnd_x = window.screenLeft;
   var wnd_y = window.screenTop;
   if (Math.abs(window_x-wnd_x)>step || Math.abs(window_y-wnd_y)>step) {
     str += 'p'+wnd_x+'.'+wnd_y+';';
     window_x = wnd_x;
     window_y = wnd_y;
   }
   if (window_resized) str += 'w'+wnd_w+'.'+wnd_h+';';
   counterID = setTimeout("runCounter()", record_step);
}

function captureClose() {
   str+='x;';
   sendData();
}


function compressData() {
   var ar = new Array();
   ar = str.split(";");
   var p = null;
   var pc = 0;
   var k=0;
   while (k<ar.length) {
     if (p) {
       if (p==ar[k]) { 
        ar[k] = '';
        pc++; 
       } else {
        if (pc>2) { ar[k-1]='*'+pc; }
	  p = null; pc=0; 
       }
     }
     if (!p) {
       if (ar[k] == ar[parseInt(k)+1]) {
         p = ar[k];
         ar[parseInt(k)+1] = '';
         pc = 2;
         k++;
       }   
     }
     k++;
   }
   str = '';
   for (var k in ar) {
     if (ar[k]) { str += ar[k]+';'; }
   }
   return 1;
}

function sendData() {
   if (isComp) {
    sendRequest('/tracker/writestat.php',  'tuid='+encodeURIComponent(tracker_uid)+'&url='+encodeURIComponent(thisurl)+'&history='+encodeURIComponent(str), 'POST');
   } else {
    sendRequest('/tracker/writestat.php?tuid='+tracker_uid+'&url='+thisurl+'&history='+str,'', 'GET');      
   }
   clearTimeout(counterID);
   if (isComp) {
    document.body.detachEvent('onmousemove', captureMove);
    document.body.detachEvent('onclick', captureClick);
    document.body.detachEvent('onkeypress', captureKeyPress);
   }   
}

function captureClick() {
  compressData();
  var srcEl = event.srcElement;
  if (srcEl.tagName == 'INPUT' && srcEl.type.toUpperCase() == 'SUBMIT') { 
    while (srcEl.tagName != "FORM" && srcEl.tagName != 'BODY') {
      srcEl = srcEl.parentElement;
    }
    if (srcEl.tagName == "FORM") {
       str+="f"; str+=srcEl.action+";";      
//       sendData(); 
    }
  } else {
    while (srcEl.tagName != "A" && srcEl.tagName != 'BODY') {
      srcEl = srcEl.parentElement;
    }
    if (srcEl.tagName == "A") { 
     // ПРОВЕРКА НА ПРИНАДЛЕЖНОСТЬ К ДОМЕНУ
     if ((srcEl.href.indexOf('http') == -1 || srcEl.href.indexOf(domain_name)>=0) && srcEl.href.indexOf('@')==-1) {
       str+="c"; str+="u"+srcEl.href+";";      
//       sendData(); 
     } else {
       str+="c"; str+="o"+srcEl.href+";";
     }
    } else {
       str+="c;";
    }
  }
  return true;
}

function captureKeyPress() {
   prevElFocus = elFocus;
   var srcEl = event.srcElement;
   elFocus = srcEl;
   if (elFocus.tagName == 'INPUT' || elFocus.tagName == 'TEXTAREA') { 
      if (elFocus != prevElFocus) { str+='fi'+elFocus.id+';'; elFocus.attachEvent('onblur', captureBlur); }
      str+='k'+event.keyCode+';'; 
      var d = counter-lastcounter;
      if (d*record_step>=delay) { str+='s'+(d>1 ? d : '')+';'; }
      lastcounter = counter;
   }
}

function captureBlur() {
   str+='q;';
   elFocus.detachEvent('onblur', captureBlur);
}

function captureMove() { 
   x = event.x;
   y = event.y;
   var srcEl = event.srcElement;
   while (srcEl.tagName != 'BODY') {
      if (srcEl.style.position == 'relative') {
       x+=srcEl.offsetLeft;
       y+=srcEl.offsetTop;
     }
   srcEl = srcEl.offsetParent;
   }
   if (!coordsInitiated) { 
      str+= "i"+x+"."+y+";"; 
      oldx = x;
      oldy = y;
      coordsInitiated = 1; 
   }
}