//Constructor
var JRectangle=function(x,y,width,height)
{
	// Field
	this.x=x;
	this.y=y;
	this.width=width;
	this.height=height;
	
	// Method
	this.left=JRectangle_left;
	this.top=JRectangle_top;
	this.right=JRectangle_right;
	this.bottom=JRectangle_bottom;
	this.isEmpty=JRectangle_isEmpty;
	this.setEmpty=JRectangle_setEmpty; 
	this.intersectsWith=JRectangle_intersectsWith;
	this.normalize=JRectangle_normalize;
	this.union=JRectangle_union;
	this.containsRectangle=JRectangle_containsRectangle;
	this.containsPoint=JRectangle_containsPoint;
}

function JRectangle_left()
{ return this.x; }

function JRectangle_top()
{ return this.y; }

function JRectangle_right()
{ return this.x+this.width;}

function JRectangle_bottom()
{ return this.y+this.height;}

function JRectangle_isEmpty()
{ return (this.right()==this.left() || this.top()==this.bottom());}

function JRectangle_setEmpty() 
{ this.x=this.y=this.width=this.height=0.0;}

function JRectangle_intersectsWith(rc)
{ 
	return !( this.left()>rc.right() || this.right()<rc.left() || this.top()>rc.bottom() || this.bottom()<rc.top() );
}

function JRectangle_normalize()
{
	if(this.width<0)
	{ this.x+=this.width;this.width=-this.width;}

	if(this.height<0)
	{ this.y+=this.height;this.height=-this.height;}
}

// for fast speed
function JRectangle_union( rc1,  rc2)
{
	var x,y,right,bottom;

	x=Math.min(rc1.left(),rc2.left());
	y=Math.min(rc1.top(),rc2.top());
	right=Math.max(rc1.right(),rc2.right());
	bottom=Math.max(rc1.bottom(),rc2.bottom());
	return new JRectangle(x,y,right-x,bottom-y);
}

// assume this.x<=this.right() this.y<=this.bottom() in each rect, otherwise the result may not be correct
function JRectangle_containsRectangle( rect)
{
	return (rect.left()>=this.left() && rect.top()>=this.top() && rect.right()<=this.right() && rect.bottom()<=this.bottom());
}

function JRectangle_containsPoint(x, y)
{
	return (x >= this.left()) && (y  >= this.top()) && (x <= this.right()) && (y <= this.bottom());
}
