var x;
var y;
var timer;
var scale = 1.0;
var lastFired = new Date().getTime();

function touchStartEventHandler(e) {
    x = e.touches[0].clientX;
    y = e.touches[0].clientY;
}

function touchMoveEventHandler(e) {
    clearTimeout(timer);
    
    var now = new Date().getTime();
    if (now < lastFired + 200) {
        timer = setTimeout(function() {
            touchMoveEventHandler(e);
        }, lastFired - now + 100);
        return;
    }
    
    var new_x = e.touches[0].clientX;
    var new_y = e.touches[0].clientY;
    var d_x = (new_x - x) / scale;
    var d_y = (new_y - y) / scale;
    x = new_x;
    y = new_y;
    
    var request = new XMLHttpRequest();
    request.open("POST", "/mouse_move", true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    console.log("dx=" + d_x + "&dy=" + d_y);
    request.send("dx=" + d_x + "&dy=" + d_y);
    
    lastFired = now;
    e.stopPropagation();
    e.preventDefault();
}

function tapEventHandler(e) {
    var request = new XMLHttpRequest();
    request.open("POST", "/mouse_tap", true);
    request.send();
}

function keyEventHandler(e) {
    e.preventDefault();
    
    var clickedButton = e.target;
    var command = clickedButton.innerHTML ;
    
    var request = new XMLHttpRequest();
    request.open("POST", "/button_press", true);
    request.send(command);
}

addEventListener("DOMContentLoaded", function() {    
    // Set grid and key buttons to send to server without refresh
    var buttons = document.querySelectorAll(".grid-button, .grid-key");
    for (var ii=0, ll=buttons.length; ii<ll; ii++) {
        var btn = buttons[ii];
        btn.addEventListener("click", keyEventHandler);
    }
    
    var trackpad = document.querySelector(".track-button");
    if (trackpad != null) {
        trackpad.addEventListener("touchstart", touchStartEventHandler, true);
        trackpad.addEventListener("touchmove", touchMoveEventHandler, true);
        trackpad.addEventListener("click", tapEventHandler, true);
    }
    
    
}, true);
