
//
// controlPointView.js
//

function controlPointView()
{
	this.controlPointHeld = null;
	this.controlPointNearest = null;
	this.controlPoints = [ ];
}

// TBH we can actual add/remove them from the array directly!!!
controlPointView.prototype.add = function(x, y, obj, callback)
{
	// or "new" control point with link the prototype??
	// the callback is to an actual object... hmmm...
	// could create an _actual_ object for this... 
	return this.controlPoints.push({x:x, y:y, obj:obj, callback:callback});
}

// respond to mouse/finger up/down and move messages...

controlPointView.prototype.search = function(x,y)
{
	var cps = this.controlPoints;

	var md = Number.POSITIVE_INFINITY;
	var mcp = null;

	for (cp in cps)
	{
		var xd = Math.abs(cps[cp].x - x);
		var yd = Math.abs(cps[cp].y - y);

		var d = xd * xd;
		d += yd *= yd;

		if (d < md)
		{
			md = d;
			mcp = cps[cp];
		}
	}

	return { controlPoint:mcp, distance:md };
}

controlPointView.prototype.down = function(x,y)
{
	var cpSearch = this.search(x,y);
	
	if (cpSearch.distance < 120)
	{
		this.controlPointHeld = cpSearch.controlPoint;
	}
	
	this.controlPointNearest = cpSearch.controlPoint;
	
	return cpSearch.controlPoint;
}

controlPointView.prototype.up = function(x,y)
{
	return this.controlPointHeld = null;
}

controlPointView.prototype.move = function(x,y)
{
	if (this.controlPointHeld != null)
	{
		// fake snap to grid demo innit...		
//		x -= (x + 5) % 10;
//		y -= (y + 5) % 10;
		x -= x % 10;
		y -= y % 10;

		this.controlPointHeld.x = x;
		this.controlPointHeld.y = y;
		
		this.controlPointHeld.callback(x, y, this.controlPointHeld.obj);
	}
	
	return this.controlPointHeld;
}

//
// which control points? need to search somehow... but how???
//
controlPointView.prototype.addCL = function(cp1,cp2)
{
	// err.. that'll do eh?
	cp1.controlLine = cp2;
}


controlPointView.prototype.draw = function(ctx)
{
	var cps = this.controlPoints;

	ctx.save();

		ctx.strokeStyle = '#f99';
		ctx.lineWidth = 2;

		for (var cp in cps)
		{
			if (typeof(cps[cp].controlLine) != 'undefined')
			{
				drawControlLine(ctx, cps[cp]);
			}
		}

	ctx.restore();
	ctx.save();

		ctx.translate(-3,-3);

		for (var cp in cps)
		{
			drawControlPoint(ctx, cps[cp], '#f88');
		}
	
	ctx.restore();
}

function drawControlPoint(ctx, cp, color)
{
	ctx.fillStyle = '#666';
	ctx.fillRect(cp.x,cp.y,7,7);
	ctx.fillStyle = color;
	ctx.fillRect(cp.x+1,cp.y+1,5,5);
}

function drawControlLine(ctx,cp)
{
	ctx.beginPath();
		ctx.moveTo(cp.x, cp.y);
		ctx.lineTo(cp.controlLine.x, cp.controlLine.y);
	ctx.stroke();
}

