var canvas = document.getElementById("canvas");
var overlay = document.getElementById("overlay");
var ctx = canvas.getContext("2d");
var ctxo = overlay.getContext("2d");

var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

var isDown = false;

var startX;
var startY;

var prevStartX = 0;
var prevStartY = 0;
var prevWidth  = 0;
var prevHeight = 0;

ctx.canvas.width = img.width;
ctxo.canvas.width= img.width;
ctx.canvas.height = img.height;
ctxo.canvas.height = img.height;

ctxo.drawImage(img, 0, 0);

// style the context
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctxo.strokeStyle = "red";
ctxo.lineWidth = 3;

// Draw a box from existing x:y coordinates
function drawBox(x, y, w, h) {


    if(w / img.width < 0.2){
        ctxo.strokeRect(x, y, w, h);
    }
}


function handleMouseDown(e) {
    e.preventDefault();
    e.stopPropagation();

    // save the starting x/y of the rectangle
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);

    // set a flag indicating the drag has begun
    isDown = true;
}

function handleMouseUp(e) {
    e.preventDefault();
    e.stopPropagation();

    // the drag is over, clear the dragging flag
    isDown = false;
    ctxo.strokeRect(prevStartX, prevStartY, prevWidth, prevHeight);
}

function handleMouseOut(e) {
    e.preventDefault();
    e.stopPropagation();

    // the drag is over, clear the dragging flag
    isDown = false;
}

function handleMouseMove(e) {
    e.preventDefault();
    e.stopPropagation();

    // if we're not dragging, just return
    if (!isDown) {
        return;
    }

    // get the current mouse position
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    var width = mouseX - startX;
    var height = mouseY - startY;

		// clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // draw a new rect from the start position 
    // to the current mouse position
    ctx.strokeRect(startX, startY, width, height);
    
		prevStartX = startX;
		prevStartY = startY;

		prevWidth  = width;
		prevHeight = height;
}

// remove current boxes
function clearCanvas(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctxo.clearRect(0, 0, canvas.width, canvas.height);
    ctxo.drawImage(img, 0, 0);
}
