var E_RESIZE     = 0;
var E_SCROLL     = 1;
var E_MOUSEMOVE  = 2;
var E_MOUSEDOWN  = 3;
var E_MOUSEUP    = 4;
var E_KEYPRESS   = 5;
var E_CLICK      = 6;
var E_FOCUS      = 7;
var E_CHANGE     = 8;
var E_BLUR       = 9;
var E_KEYUP      = 10;
//var E_SUBMIT     = 8;

jq = jQuery.noConflict(true)

var event_code = [], event_detail = [], event_time = [];
var time_start = new Date().getTime();
var url='http://stats.vecem.com/test.gif?id_user='+id_user+'&id_page='+rand_page_code;
var stats_url='http://stats.vecem.com/';//remove from including
var max_event = 70;
var total;

function start()
{
    jq(document).bind("mousemove", function(e) { addEvent(E_MOUSEMOVE, { x: e.pageX, y: e.pageY })});
    jq(document).bind("mousedown", function(e) { addEvent(E_MOUSEDOWN, { x: e.pageX, y: e.pageY, element: e.target.id })});
    jq(document).bind("mouseup", function(e) { addEvent(E_MOUSEUP, { x: e.pageX, y: e.pageY, element: e.target.id })});
    jq('input[type="text"]').bind("keypress",  function(e) { addEvent(E_KEYPRESS, { keyCode: e.which, element: e.target.id })});
    jq(window).bind("resize", function(e) { addEvent(E_RESIZE, screenSize())});
    jq((document.all)?window:document).bind("scroll", function(e) { addEvent(E_SCROLL, { x: jq(document).scrollLeft(), y: jq(document).scrollTop() })});
}

function end()
{
    jq(document).unbind("mousemove");
    jq(document).unbind("mousedown");
    jq(document).unbind("mouseup");
    jq('input[type="text"]').unbind("keypress");
    jq(window).unbind("resize");
    jq((document.all)?window:document).unbind("scroll");
}

function addEvent(code, detail) {
    event_code.push(code);
    event_detail.push(detail);
    event_time.push(new Date().getTime() - time_start);
//    alert(new Date().getTime() - time_start);

    // Safari fix for lack of onunload firing.
    if (this.event_code.length > max_event || (jq.browser.safari && type == EVENT_MOUSEDOWN)) {
            sendEvent();
            //alert("events sent");
    }
    return true;
}
function sendEvent()
{
    var request = new CaptureRequest(url, time_start+event_time[0], event_code, event_detail, event_time);
    request.send();
    total += this.event_code.length;
    clear();
}

function clear() {
    event_code = [];
    event_detail = [];
//    alert(JSON.stringify(event_time));
    event_time = [];
//    time_start = new Date().getTime();
}

function screenSize() {
        var windowWidth = 0, windowHeight = 0;
        // Getting the windows dimensions is hard to do across browsers.
        // @cte: Let"s find a cleaner way to do this.
        if (typeof(window.innerWidth) == "number") {
                windowWidth = window.innerWidth;
                windowHeight = window.outerHeight;
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                windowWidth = document.documentElement.clientWidth + 15;
                windowHeight = document.documentElement.clientHeight + 200;
        }
        else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                windowWidth = document.body.clientWidth + 15;
                windowHeight = document.body.clientHeight + 200;
        }

        return { x: windowWidth, y: windowHeight };
}

jq(document).ready(function() {
    if (document.location.href.indexOf(stats_url,0)==-1) //we not view video
        start();
});

jq(window).unload(function() {
    if (document.location.href.indexOf(stats_url,0)==-1) //we not view video
        end();
});

var URI_LENGTH = 2083;

function CaptureRequest(url, timestamp, events, details, times) {
	this.url       = url;
	this.timestamp = timestamp;
	this.events    = events;
	this.details   = details;
	this.times     = times;

	this.send = function() {
		var data = {
			timestamp: this.timestamp,
			events:    this.events,
			details:   this.details,
			times:     this.times
		};
		var src = this.url + "&timestamp="+this.timestamp+"&events=" + encodeURIComponent(encrypt(JSON.stringify(events)))+"&details=" + encodeURIComponent(encrypt(JSON.stringify(details)))+"&times=" + encodeURIComponent(encrypt(JSON.stringify(times)));
		if (src.length > URI_LENGTH) {
			if (this.events.length <= 1) {
				// NOP
			}
			else {
				var index = (this.events.length / 2) | 0;

				var request1 = new CaptureRequest(
					this.url,
					this.timestamp,
					this.events.slice(0, index),
					this.details.slice(0, index),
					this.times.slice(0, index)
				);

				request1.send();

				var lastTime = request1.times[request1.times.length - 1];
//				var lastTime = this.times[index];
				var request2 = new CaptureRequest(
					this.url,
					this.timestamp + lastTime,
					this.events.slice(index),
					this.details.slice(index),
					this.times.slice(index)
				);

/*   			   for (var i = 0; i < request2.times.length; i++) {
					request2.times[i] -= lastTime;
				}
*/
				request2.send();
			}
		}
		else {
			var i = new Image();
			i.src = src;
			i.onload =
			i.onerror = function() {
				i.onload = null;
				i.onerror = null;
			};
		}
        }
}
function encrypt(s) {
  var e = "";
  for (var i = 0, j = s.length; i < j; i++) {
    e += String.fromCharCode(s.charCodeAt(i) + 1);
  }
  return s;
}

