var ScratchBoard = {
	drawing: false,
	position: {x: 0, y: 0}
};

ScratchBoard.init = function ()
{
	ScratchBoard.context = $('scratchboard').getContext('2d');
	ScratchBoard.context.lineWidth = 3;
	
	ScratchBoard.color('foreground');
};

ScratchBoard.clear = function ()
{
	ScratchBoard.context.beginPath();
	ScratchBoard.context.clearRect(0, 0, $('scratchboard').getWidth(), $('scratchboard').getHeight());
	ScratchBoard.context.closePath();
};

ScratchBoard.color = function (col)
{
	ScratchBoard.context.lineWidth = 3;
	
	if (col == 'foreground')
	{
		col = '#666';
	}
	else if (col == 'background')
	{
		col = $('scratchboard').getStyle('backgroundColor');
		ScratchBoard.context.lineWidth = 6;
	}
	
	ScratchBoard.context.strokeStyle = col;
};

ScratchBoard.mousepos = function(e)
{
	return {
		x: Event.pointerX(e) - ScratchBoard.positionX,
		y: Event.pointerY(e) - ScratchBoard.positionY
	};
};

ScratchBoard.mousemove = function (e)
{
	if (!ScratchBoard.drawing)
		return;
	
	var position = ScratchBoard.mousepos(e);

	ScratchBoard.context.save();
	ScratchBoard.context.beginPath();
	ScratchBoard.context.lineCap = "round";
	ScratchBoard.context.moveTo(ScratchBoard.position.x, ScratchBoard.position.y);
	ScratchBoard.context.lineTo(position.x, position. y);
	ScratchBoard.context.stroke();	
	ScratchBoard.context.closePath();
	ScratchBoard.context.restore();
		
	ScratchBoard.position = position;
};

ScratchBoard.mousedown = function (e)
{
	if (e.button == 0)
	{
		ScratchBoard.drawing = true;

		ScratchBoard.positionX = Position.cumulativeOffset($('scratchboard'))[0];
		ScratchBoard.positionY = Position.cumulativeOffset($('scratchboard'))[1];
		ScratchBoard.position = ScratchBoard.mousepos(e);
	}
};

ScratchBoard.mouseup = function (e)
{
	ScratchBoard.drawing = false;
};
