
//call function f for each of the element in a
function each(a,f) { for (var i=0,l=a.length; i<l; i++) f(a[i]); }
    
//v{x,y}
function normsqr(v)
{
	return v.x*v.x+v.y*v.y;
}

//v{x,y}
var norm = function(v)
{
	return Math.sqrt(v.x*v.x+v.y*v.y);
}

//v{x,y}
function normalize(v)
{
	var n=norm(v);
	if(n===0){ console.log("normalize: vector length is 0") }
	return {x:v.x/n, y:v.y/n};
}

//p{x,y}, q{x,y}
function dot(p,q)
{
	return p.x*q.x+p.y*q.y; 
}

//p{x,y}, q{x,y}
function cross(p,q)
{
	var tmp=p.x*q.y-p.y*q.x;
	return {x:0,y:0,z:tmp};
}

//p{x,y}, q{x,y}
function add(p,q)
{
	return {x:p.x+q.x,y:p.y+q.y};
}

//p{x,y}, q{x,y}
function subtract(p,q)
{
	return {x:p.x-q.x,y:p.y-q.y};
}

//check if three points p{x,y}, q{x,y}, r{x,y} make a left turn
function leftTurn(p,q,r)
{
	var v1=subtract(q,p);
	var v2=subtract(r,q);	
	var c=cross(v1,v2);
	return c.z>0;
}

//circle{x,y,r}, p{x,y}
function insideCircle(circle,p)
{
	var v=subtract(circle,p);
	if( normsqr(v)<= (circle.radius*circle.radius) ) return true;
	return false;
}

//rotate a point around the world orign by degree "d"
//p{x,y}
function rotate(p,d)
{
	var rad=d*Math.PI/180;
	var cos=Math.cos(rad);
	var sin=Math.sin(rad);	
	return {x: cos*p.x-sin*p.y, y: sin*p.x+cos*p.y};
}

//box{x,y,w,h,angle}, p{x,y}
function insideBox(box,p)
{
	var w2=box.width/2;
	var h2=box.height/2;	
	
	//4 corners
	var c1=rotate({x:-w2,y:-h2}, box.angle);
	var c2=rotate({x:w2,y:-h2}, box.angle);
	var c3=rotate({x:w2,y:h2}, box.angle);
	var c4=rotate({x:-w2,y:h2}, box.angle);
	
	//new translated point				
	var np={x:p.x-box.x-w2,y:p.y-box.y-h2};
	
	//check is np is inside the box
	if(leftTurn(c1,c2,np)==false) return false;
	if(leftTurn(c2,c3,np)==false) return false;
	if(leftTurn(c3,c4,np)==false) return false;
	if(leftTurn(c4,c1,np)==false) return false;
	
	return true;			
}



