// Author: Sergi Diaz Planas
/*
    All client scripting is managed from here, from event handler bindings to the logic
    regarding the comunication with server.
*/

var referenceIsSet = false;
//var video  = null;
//var canvas = null;


// Draw a collection of colored rectangles into the given canvas. THe expected
// input for the rectangles is a collection of rectangles.
function drawRects(canvas, color) 
{
    var ctx = canvas.getContext("2d");

    ctx.strokeStyle = color;
    ctx.rect(doc_x, doc_y, doc_w, doc_h);
    ctx.rect(pho_x, pho_y, pho_w, pho_h);
    ctx.rect(dni_x, dni_y, dni_w, dni_h);
    ctx.rect(nms_x, nms_y, nms_w, nms_h);
    ctx.rect(snm_x, snm_y, snm_w, snm_h);
    ctx.stroke();
}

// Handle timer update on video element
function onVideoUpdate(referenceIsSet) 
{
    var video = document.getElementById("video");
    var canvas = document.getElementById("canvas");
    var frame  = captureFrame(video, 1); 

    // Send a message in between a specific ammount of frames
    frameCounter = frameCounter + 1; 
    if (frameCounter == framesInBetween) 
    {   
        frameCounter = 0; 
        // If we have not yet set a reference into this session, send a reference candidate    
        if (referenceIsSet)
        {
            sendForValidation(serverUrl, frame);
        }  
        else
        {
            sendReference(serverUrl, frame, canvas);
        }   
    } 
}

// Clear the given canvas item 
function clearCanvas(canvas)
{
    var ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// Fill the form with data received from server
function setForm(dni, name, surname)
{
    var txtName = document.getElementById("txtName");
    var txtDni  = document.getElementById("txtDni");
    var txtSurname = document.getElementById("txtSurname");

    // txtDni.value = dni;
    // txtName.value = name;
    // txtSurname.value = surname; 
    txtDni.value = dni;
    txtName.value = "SERGI";
    txtSurname.value = "DIAZ I PLANAS"; 
}