var pos_xy = {"x": 0, "y": 0};
var brush_path = [];

function hideBrush()
{
	document.getElementById('pic_canvas').style.display = "none";
}

function showBrush()
{
	document.getElementById('pic_canvas').style.display = "block";
}

function brush()
{
	if(current_pic == ''){
		alert('Please upload a picture first.');
    	}
	else{
	
		document.getElementById('pic_canvas').style.display = "block";
		init_brush();
		clearBrush();
	}
}

function clearBrush()
{
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=clear_brush', true);
	req.send( { 'current_pic' : current_pic } );
	
	canvas = document.getElementById('pic_canvas');
	ctx = canvas.getContext('2d');
	ctx.beginPath();
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.closePath();
    
	ctx.globalAlpha = 0.0;
	ctx.fillStyle = "#000000";
	ctx.beginPath();
    ctx.fillRect(0,0,canvas.width,canvas.height);
    ctx.closePath();
    ctx.fill();
    
    ctx.globalAlpha = 1;
}

function sendPath()
{
	size = document.getElementById('brush_size').value;
	color = document.getElementById('brush_color').value;
	// Create new JsHttpRequest object.
	var req = new JsHttpRequest();
	// Prepare request object (automatically choose GET or POST).
	req.open(null, '/index.php?rm=brush', true);
	// Send data to backend.
	req.send( { 'brush_path': brush_path, 'brush_size': size, 'brush_color': color, 'file' : pic_history[current_history], 'current_pic' : current_pic } );
	
	pos_xy = {"x": 0, "y": 0};
	brush_path = [];
}

function init_brush()
{
	document.getElementById('pic_canvas').onmousedown = function () {
		var oPosition = get_event_position1(e);
		pos_x = oPosition.x;
		pos_y = oPosition.y;
		document.getElementById('pic_canvas').onmousemove = onMouseMove;
		document.getElementById('pic_canvas').onmouseup = function () { 
			sendPath();
			document.getElementById('pic_canvas').onmousemove = function () { };
		};
	}
}

function onMouseMove(e)
{
	var oPosition = get_event_position1(e);
	var pic_pos = get_object_position(window.document.getElementById('select_pic'));
	to = {"x": (oPosition.x-pic_pos.x), "y": (oPosition.y-pic_pos.y)};
	brush_path.push(to);
	if (pos_xy.x == 0 && pos_xy.y == 0) {
		from = to;
	} else {
		from = {"x": pos_xy.x, "y": pos_xy.y}
	}
	drawPencil(from, to, document.getElementById('pic_canvas').getContext('2d'))
	if (brush_path.length > 100) {
		sendPath();
		brush_path.push(to);
	}
	pos_xy = to;
}

function drawPencil(pntFrom, pntTo, ctx) {
	ctx.strokeStyle = document.getElementById('brush_color').value;
	ctx.lineWidth = document.getElementById('brush_size').value;
    ctx.save();
    ctx.beginPath();
    ctx.lineCap = "round";
    ctx.moveTo(pntFrom.x,pntFrom.y);
    ctx.lineTo(pntTo.x,pntTo.y);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
}
