currentPageId = -1;
globalXmlHttp = null;

// ustawia ciasteczko name = value
function setCookie(name, value) {
    var date = new Date();
    date.setTime(date.getTime()+(365*24*60*60*1000));
    cookieString = '' + name + '=' + value + '; expires=' + date.toGMTString() + '; path=/';
    document.cookie = cookieString;
}

// zwraca ciasteczko o podanej nazwie
function getCookie(name) {
	var piece = document.cookie.split(';');
	for(var i=0;i < piece.length;i++) {
		var ch = piece[i];
		while (ch.charAt(0)==' ') ch = ch.substring(1,ch.length);
		if (ch.indexOf(name+"=") == 0) return ch.substring(name.length+1,ch.length);
	}
	return null;
}


// sprawdza czy istnieje ciasteczko o podanej nazwie
function isCookieSet(name) {
    if(getCookie(name) == null) {
        return false;
    }
    return true;
}

// zwraca obiekt xmlHttp
function getXmlHttp(){
    var xmlHttp;
    try { // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e){ // Internet Explorer
        try{
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                alert("W Twojej przeglądarce nie można używać AJAXa!");
                return false;
            }
        }
    }
    return xmlHttp;
}

// tworzy w bazie nowe id użytkownika i zwraca je
function getNewUserId() {
    xmlHttp = getXmlHttp();
    xmlHttp.open("GET","id.php?action=getnewuserid", false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

// zwraca page_id - page to jekaby element składowy sesji - każda strona na którą
// było zrobione wejście. Przeskok A -> B -> A spowoduje, że drugi raz A
// będzie miało inne page_id
function getPageId() {
    xmlHttp = getXmlHttp();
    xmlHttp.open("GET","id.php?action=getpageid&path=" + escape(document.location), false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

// sprawdza czy już jesteśmy w sesji
function isSessionStarted() {
    xmlHttp = getXmlHttp();
    xmlHttp.open("GET","id.php?action=issessionstarted", false);
    xmlHttp.send(null);
    
    if(xmlHttp.responseText == 1) {
        return true;
    }
    
    return false;
}

function getPluginsString() {
    tmp = "";
    for(i=0;i<navigator.plugins.length;i++) {
        tmp += navigator.plugins[i].name + ";";
    }
    return tmp;
}

function getWindowHeight() {
    return window.innerHeight != null ? window.innerHeight : document.body.clientHeight;
}

function getWindowWidth() {
    return window.innerWidth != null ? window.innerWidth : document.body.clientWidth;
}

// rozpoczyna nową sesje i zwraca userid
function startSession() {
    getString = "&ua=" + navigator.appName +
                "&uv=" + navigator.appVersion +
                "&pf=" + navigator.platform +
                "&pl=" + getPluginsString() +
                "&la=" + navigator.language +
                "&sw=" + screen.width +
                "&sh=" + screen.height +
                "&ww=" + getWindowWidth() +
                "&wh=" + getWindowHeight();

    xmlHttp = getXmlHttp();
    xmlHttp.open("GET","id.php?action=startsession" + getString, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

function startSessionU($userId) {
    getString = "&ua=" + navigator.appName +
                "&uv=" + navigator.appVersion +
                "&pf=" + navigator.platform +
                "&pl=" + getPluginsString() +
                "&la=" + navigator.language +
                "&sw=" + screen.width +
                "&sh=" + screen.height +
                "&ww=" + getWindowWidth() +
                "&wh=" + getWindowHeight();

    xmlHttp = getXmlHttp();
    xmlHttp.open("GET","id.php?action=startsessionu&ui=" + $userId + getString, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

// zwraca pozycje X elementu od lewej krawedzi okna
function getElementX(element) {
    left = 0;
    if(element.offsetParent) {
        while(true) {
          left += element.offsetLeft;
          if(!element.offsetParent) {
                break;
          }
          element = element.offsetParent;
        }
    }
    else if(element.x) {
        left += element.x;
    }

    return left;
}

function initialize() {
    if(!isSessionStarted()) {
        if(isCookieSet('userid') && getCookie('userid') != "") {
            $ciacho = startSessionU(getCookie('userid'));
            setCookie('userid', $ciacho);
        } else {
            $ciacho = startSession();
            setCookie('userid', $ciacho);
        }
    }
    
    currentPageId = getPageId();
    globalXmlHttp = getXmlHttp();
}

function attachScript(rootElementId) {
    document.onmousemove = writeMousePosition;
    rootElement = document.body;
    initialize();
}

// zapobiega wysylaniu danych gdy np zatrząsł się kursor
ACCURACY = 5;

rootElement = document.body;

// przechowuja pozycje kursora względem początku strony
mouseX = 0;
mouseY = 0;

// przechowują kierunek w ktorym ostatnio poruszal sie kursor -/+ <-/->
directionX = 0;
directionY = 0;

// pozycja kursora myszy w poprzedniej iteracji
previousMouseX = 0;
previousMouseY = 0;

// poprzedni kierunek kursora
previousDirectionX = 0;
previousDirectionY = 0;

// punkt w ktorym ostatnio zmienil się kierunek
previousPointX = 0;
previousPointY = 0;

function writeMousePosition(myEvent) {

    // tylko dla firefoxa
    if(navigator.userAgent.indexOf("Firefox", 0) != -1) {
        event = myEvent;
    }

    previousMouseX = mouseX;
    mouseX = event.clientX + document.body.scrollLeft;

    previousMouseY = mouseY;
    mouseY = event.clientY + document.body.scrollTop;

    if(mouseX - previousMouseX != 0) {
        previousDirectionX = directionX;
        directionX = mouseX - previousMouseX;
    }

    if(mouseY - previousMouseY) {
        previousDirectionY = directionY;
        directionY = mouseY - previousMouseY;
    }

    addPoint();
}

function getCollectString(pageId, activityType, normalizedX, y) {
    return  "collect.php?" +
            "pid=" + pageId +
            "&act=" + activityType +
            "&nx=" + normalizedX +
            "&y=" + y;
}

function addPoint() {
    if((previousDirectionX * directionX < 0 || previousDirectionY * directionY < 0)
       && Math.abs(previousPointX-mouseX) > ACCURACY && Math.abs(previousPointY-mouseY) > ACCURACY) {
        previousPointX = mouseX;
        previousPointY = mouseY;

        normalizedMouseX = (mouseX - getElementX(rootElement))/(rootElement.offsetWidth*1.0);
        globalXmlHttp.open("GET",getCollectString(currentPageId, 0, normalizedMouseX, mouseY), true);
        globalXmlHttp.send(null);
    }
}


