/** Polygon calculations **/

function Polygon()
{
    return {
	points : new Array(),
	bounds : { left: 0, top: 0, right: 0, bottom: 0},
	hasBounds : false,
	handle : "",
	setHandle : function(h) {
	    this.handle = h;
	},
	addPoint : function(x,y) {
	    this.points[ this.points.length ] = { x: x, y: y };
	},
	calculateBounds : function() {
	    if( this.hasBounds ) return this.bounds;

	    var   minX, maxX, minY, maxY;

	    minX = minY = Number.MAX_VALUE;
	    maxX = maxY = Number.MIN_VALUE;

	    for( var j = 0; j < this.points.length; j ++ ) {
		if( this.points[j].x < minX )
		    minX = this.points[j].x;
		if( this.points[j].x > maxX )
		    maxX = this.points[j].x;
		if( this.points[j].y < minY )
		    minY = this.points[j].y;
		if( this.points[j].y > maxY )
		    maxY = this.points[j].y;
	    }

	    this.bounds.left = minX;
	    this.bounds.top = minY;
	    this.bounds.right = maxX;
	    this.bounds.bottom = maxY;

	    this.hasBounds = true;

	    return this.bounds;
	},
	isPtInBounds : function(point)
	{
	    var bounds = this.calculateBounds();

	    if( (point.x > bounds.left) && (point.x < bounds.right) &&
		(point.y > bounds.top) && (point.y < bounds.bottom) )
		return true;

	    return false;
	},
	isPtInPolygon : function(point)
	{
	    if( !this.isPtInBounds( point ) ) return false;

	    var right = this.bounds.right;
	    var point2 = {
		x: right + 50,
		y: point.y
	    }

	    var intersections = 0;

	    for( var j = 0; j < this.points.length - 1; j ++ ) {
		if( this.isInt( point, point2, this.points[j], this.points[j+1] ) > 0 )
		    intersections ++;
	    }

	    if( this.isInt( point, point2, this.points[this.points.length-1], this.points[0] ) )
		intersections ++;

	    return (intersections & 0x01) ? true : false;
	},
	counterClockWise : function(point1, point2, point3)
	{
	    var check = ( ((point2.x - point1.x) * (point3.y - point1.y)) - 
			  ((point3.x - point1.x) * (point2.y - point1.y)) );

	    if( check > 0 ) return 1;
	    else if( check < 0 ) return -1;

	    return 0;
	},
	isInt : function(point1, point2, point3, point4) {
	    var try1 = this.counterClockWise( point1, point2, point3 );
	    var try2 = this.counterClockWise( point1, point2, point4 );

	    if( try1 != try2 ) {
		try1 = this.counterClockWise( point3, point4, point1 );
		try2 = this.counterClockWise( point3, point4, point2 );

		if( try1 != try2 ) return true;
	    }

	    return false;
	}
    };
}
