// Name of the server page
var collectorPage = "tr/scroll_collector.php";
var setupPage = "tr/visit_setup.php";

// Setup the system when the document has finished loading
function setup_tracking() {
    // Last position sent
    var lastPosition = 0;
    var lastTime = new Date().getTime();
    
    // Set the visit ID
    var visitID = 0;
    if(getCookie("visitID")) {
        visitID = getCookie("visitID");
    }
    else {
        // Setup a new visitor in the database and get the id
        getText(setupPage, function(data) {
            visitID = parseInt(data);
            document.cookie = "visitID=" + visitID;
        });
    }

    // Atach the event to monitor page scrolls
    window.onscroll = function() { 
        // Wait until the scrollbar is stable
        window.setTimeout(function() {
            // Don't send the same position twice
            var curScroll = getVerticalScroll();
            if(lastPosition != curScroll) {
                // Get the current date, time and duration
                var date = new Date();
                var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                var duration = date.getTime() - lastTime;
                lastTime = date.getTime();
                date = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
                
                // Send the data to the server
                sendObject(collectorPage, {visit_id: visitID, scroll: curScroll, date: date, time: time, duration: duration });
                
                // Update the last position
                lastPosition = curScroll;
            }
        },0);
    } 
}


/*
 * This function provides a cross platform way of obtaining the position of the vertical scroll bar.
 */
function getVerticalScroll() {
    if(window.pageYOffset) return window.pageYOffset;
    if(document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop;
    if(document.body.scrollTop) return document.body.scrollTop;
    return 0;
}

/* 
 * This function gets the current value of the named cookie.
 */
function getCookie(name) {
    // Get all cookies
    var cookies = document.cookie;
    // Get the start of the named cookie
    var pos = cookies.indexOf(name+"=");
    // If the name exists
    if(pos != -1) {
        // Get the start of the value
        var start = pos + name.length+1;
        // Get the end of the value
        var end = cookies.indexOf(";", start);
        if(end == -1) end = cookies.length;
        // Extract the value and return it
        return cookies.substring(start, end);
    }
}

/*
 * This function sends the input object to the input url.
 * The object is serialised by spliting its properties into name/value pairs.
 */
function sendObject(url, obj) {
    var req = HTTP.newRequest();
    
    url += "?";
    
    for(var prop in obj) {
        url += "&" + prop + "=" + obj[prop];
    }
    
    /*
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(url));
    document.body.appendChild(p);
     */
    req.open("GET", url);
    req.send(null);
}

/*
 * This function gets the text at the given url.  
 * Once the text has been retrieved the callback function is run.
 */
function getText(url, callback) {
    var req = HTTP.newRequest();
    req.onreadystatechange = function() {
        if(req.readyState == 4 && req.status == 200) callback(req.responseText);
    }
    req.open("GET", url);
    req.send(null);
}

var HTTP = {};
// This is a list of XMLHttpRequest creation factory functions to try
HTTP._factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];

// When we find a factory that works, store it here
HTTP._factory = null;

// Create and return a new XMLHttpRequest object.
// 
// The first time we're called, try the list of factory functions until
// we find one that returns a nonnull value and does not throw an
// exception.  Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
    if (HTTP._factory != null) return HTTP._factory();
    
    for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if (request != null) {
                HTTP._factory = factory;
                return request;
            }
        }
        catch(e) {
            continue;
        }
    }
    
    // If we get here, none of the factory candidates succeeded,
    // so throw an exception now and for all future calls.
    HTTP._factory = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    HTTP._factory(); // Throw an error
}

setup_tracking();
