
var socket;

window.onload = function () {
    
    if (!window.WebSocket) {
        console.debug('Your browser does not support web sockets!');
        return;
    }



    // Initialize a new web socket.
    socket = new WebSocket("ws://localhost:8181/KinectHtml5");

    // Connection established.
    socket.onopen = function () {
        console.debug("Connection successful.");
    };

    // Connection closed.
    socket.onclose = function () {
        console.debug("Connection closed.");
    }

    // Receive data FROM the server!

    socket.onmessage = function (event) {
        if (typeof event.data === "string") {

            // 1. Get the data in JSON format.
            var jsonObject = JSON.parse(event.data);
            if (jsonObject.name == "active_hand") {
                var joint = jsonObject.hand;
                handPos(joint.x, joint.y);
            }
            else if (jsonObject.name == "RIGHT" || jsonObject.name == "LRIGHT") {
                next();
            }
            else if (jsonObject.name == "LEFT" || jsonObject.name == "RLEFT") {
                prior();
            }
            else if (jsonObject.name == "GRIP")
            {
                grip();
            }
            else if (jsonObject.name == "RELEASE")
            {
                release();
            }
            else if (jsonObject.name == "NewUser")
            {
                newUser();
            }
            else if (jsonObject.name == "NoUser")
            {
                if(context != null)
                    context.clearRect(0, 0, canvas.width, canvas.height);
                noUser();
            }
            else if (jsonObject.name == "ChangedHandNone") {
                changeHandNone();
            }
            else if (jsonObject.name == "ChangedHandRight") {
                changeHandRight();
            }
            else if (jsonObject.name == "ChangedHandLeft") {
                changeHandLeft();
            }
            else if (jsonObject.name == "UpdateApp") {
                
                updateApp();
            }
            else if (jsonObject.name == "AppUpdated") {
                appUpdated();
            }
            else if (jsonObject.name == "Arduino") {
                msgFromArduino(jsonObject.value);
            }
            else {
                // 1. Get the data in JSON format.
                var jsonObject = JSON.parse(event.data);
                getSkeletons(jsonObject);

            }
            
        }
    };
   

};

function sendToArduino(msg)
{
    socket.send(msg);
}

