/*
CSS Polygons - Use CSS to create polygons.
Copyright (c) 2004 Thomas Peri, http://www.tumuski.com/

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The Software shall be used for Good, not Evil.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

onerror = function(e,u,l)
{
	alert([e,u,l]);
};


function getInt(n)
{
	n = parseFloat(n);
	return isNaN(n) ? 0 : Math.round(n);
}

/**
 * An immutable integer point in 2-D space.
 */
function IntPoint(x,y) // "extends" Point
{
	var p = new Point(getInt(x),getInt(y));
	for (var i in p)
	{
		this[i] = p[i];
	}
}

/**
 * An immutable point in 2-D space.
 */
function Point(/*int*/ x, /*int*/ y)
{
	this.x = function()
	{
		return x;
	};
	
	this.y = function()
	{
		return y;
	};
	
	this.equals = function(/*IntPoint*/ P)
	{
		return (x == P.x() && y == P.y());
	};
	
	this.angleOfLineTo = function(/*IntPoint*/ P)
	{
		return Math.atan2( P.y() - y, P.x() - x );
	};
	
	this.distanceTo = function(/*IntPoint*/ P)
	{
		var dx = P.x() - x;
		var dy = P.y() - y;
		var d = Math.sqrt(dx*dx + dy*dy);
		return Math.abs(d);
	};
	
	this.scale = function(/*number*/ scalar)
	{
		return new Point(
			scalar * x,
			scalar * y
		);
	};

	this.toString = function()
	{
		var X = Math.round(x*1000)/1000;
		var Y = Math.round(y*1000)/1000;
		return 'Point ('+X+', '+Y+')';
	};
}

function positizeRadians(r)
{
	while (r < 0)
	{
		r += 2 * Math.PI;
	}
	return r;
}

/**
 * A trapezoid.  
 * p1 and p2 must have the same y-coordinate. Same thing for p3 and p4.
 * 
 */
function TrapezoidElement(/*IntPoint objects*/ p1, p2, p3, p4, /*string*/ c)
{
	// these points are numbered after the quadrants of the 
	// cartesian coordinate plane.
	
	var d, s;
	
	var x1 = p1.x(), x2 = p2.x(), x3 = p3.x(), x4 = p4.x();
	var y1 = p1.y(), y2 = p2.y(), y3 = p3.y(), y4 = p4.y();
	
	construct();
	function construct()
	{
		d = createDiv();
		s = d.style;
		
		var magic = 1;

		if (y1 - y4 < magic || Math.max(x1 - x2,x4 - x3) < magic)
		{
			return;
		}

		if (!findTriangles()) // no vertical line can be drawn from top to bottom
		{
			var result = dividerPoints();
			d.appendChild((new TrapezoidElement(p1, p2, result.p5, result.p6, c)).div());
			d.appendChild((new TrapezoidElement(result.p6, result.p5, p3, p4, c)).div());
		}
		
	}
	
	function findTriangles()
	{
		var rightInner = (x1 < x4) ? p1 : p4;
		var leftInner = (x2 > x3) ? p2 : p3;
				
		// There can be a rectangle inscribed, spanning from top to bottom.
		if (leftInner.x() < rightInner.x())
		{
			d.appendChild((new RectangleElement(
				new IntPoint(leftInner.x(), y3),
				new IntPoint(rightInner.x(), y1),
				c
			).div()));
		}
		
		// a vertical line can be drawn from top to bottom,
		// allowing us to divide this into no more than two right
		// triangles
		if (leftInner.x() <= rightInner.x())
		{
			if (x2 < x3)
			{
				addRT(x3,y2,x3,x2,y2,y3,3);
			}
			else if (x2 > x3)
			{
				addRT(x2,y3,x2,x3,y2,y3,2);
			}

			if (x1 < x4)
			{
				addRT(x1,y4,x4,x1,y1,y4,1);
			}
			else if (x1 > x4)
			{
				addRT(x4,y1,x1,x4,y1,y4,4);
			}
			
			return true;
		}
		else
		{
			return false;
		}

		/*
		 * Draw a right triangle
		 */
		function addRT(A,B,C,D,E,F,G)
		{
			d.appendChild((new RightTriangleElement(
				new IntPoint(A,B),
				C-D,
				E-F,
				G,
				c
			).div()));
		}
		
	}
	
	/**
	 * The points that are used if the trapezoid needs 
	 * to be split into smaller trapezoids
	 */
	function dividerPoints()
	{
		var bigBottom = (x4-x3 > x1-x2);
		var rightTilt = (x2 > x4);
	
		var leftSlope = (y2-y3) / (x2-x3);
		var rightSlope = (y1-y4) / (x1-x4);
		
		if (rightTilt)
		{
			if (bigBottom)
			{
				return newPoints(x4, x3, y4, false);
			}
			else
			{
				return newPoints(x2, x1, y2, true);
			}
		}
		else
		{
			if (bigBottom)
			{
				return newPoints(x3, x4, y3, true);
			}
			else
			{
				return newPoints(x1, x2, y1, false);
			}
		}
		
		/*
		 * Come up with the points for subdividing the trapezoid.
		 */
		function newPoints(xa,xb,y,swap)
		{
			var ma = swap ? rightSlope : leftSlope;
			var mb = swap ? leftSlope : rightSlope;
		
			var x5 = xa;
			var y5 = y + ( (xa - xb) * ma );
			
			var x6 = x5 + ( (y5 - y) / mb );
			var y6 = y5;
			
			var p5 = new IntPoint(x5, y5);
			var p6 = new IntPoint(x6, y6);
			
			if (swap)
			{
				var temp = p5;
				p5 = p6;
				p6 = temp;
			}
			
			return { p5: p5, p6: p6 };
		}
	}
	
	this.div = div;
	function div()
	{
		return d;
	}

}

/**
 * A convex Polygon.  Its behavior is like that of a rubber band 
 * stretched around the outside of a group of pegs.  The order in 
 * which the Points (pegs) are given doesn't matter, and any Points 
 * that would cause the Polygon to be convex are ignored.
 */
function PolygonElement(/*IntPoint[]*/ points, color)
{
	var d, s;
	var bottomRight, lefts, rights;

	construct();
	function construct()
	{
		d = createDiv();
		s = d.style;
		
		setBottomRight();
		orderPoints();
		takeSides();
		buildTraps();
	}
	
	this.isValid = isValid;
	function isValid()
	{
		return points.length > 4;
	}
	
	function setBottomRight()
	{
		// set up the points in order of y-coordinate
		points.sort(
			function(a,b)
			{
				return a.y() - b.y();
			}
		);
		
		// pick one of the points as a possible right-most
		bottomRight = points[0];
		
		// loop through the rest
		for (var i = 1; i < points.length; i++)
		{
			if (bottomRight.y() == points[i].y())
			{
				if (bottomRight.x() < points[i].x())
				{
					bottomRight = points[i];
				}
			}
			else
			{
				break;
			}
		}
	}
	
	function takeSides()
	{
		rights = new Array();
		lefts = new Array();
		
		var i = 0;
		
		do
		{
			rights[rights.length] = points[i];
			i++;
		}
		while (points[i].y() > points[i-1].y());
		
		// if it ended with the y-coordinate decreasing, back up one
		if (points[i].y() < points[i-1].y())
		{
			i--;
		}
		
		do
		{
			lefts[lefts.length] = points[i];
			i++;
		}
		while (points[i].y() < points[i-1].y());
		
		lefts.reverse();
		
	}
	
	
	function buildTraps()
	{
		var p1, p2, p3, p4; // for trapezoid
		var x, y, dx, dy, w;

		var i = 0;
		do
		{
			p1 = rights[i+1];
			p2 = lefts[i+1];
			p3 = lefts[i];
			p4 = rights[i];
			
			// insert a point on the right
			if (p2.y() < p1.y())
			{
				dx = p1.x() - p4.x();
				dy = p1.y() - p4.y();
				w = dx / dy;
				y = p2.y() - p3.y();
				x = y * w;
				p1 = new IntPoint(p4.x() + x, p4.y() + y); 
				rights.splice(i+1, 0, p1);
			}
			else if (p2.y() > p1.y())
			{
				dx = p2.x() - p3.x();
				dy = p2.y() - p3.y();
				w = dx / dy;
				y = p1.y() - p4.y();
				x = y * w;
				p2 = new IntPoint(p3.x() + x, p3.y() + y); 
				lefts.splice(i+1, 0, p2);
			}

			d.appendChild((new TrapezoidElement(
				p1, p2, p3, p4, color)).div());
			
			i++;
			
		} while (i < rights.length - 1);
		
	}
	
	/**
	 * "Stretch the rubber band" around all the Points, discarding the
	 * ones on the interior and the redundant ones on straight lines.
	 */
	function orderPoints()
	{
		var outside = new Array();
		outside[0] = bottomRight;
	
		var next = bottomRight;
		var angle = 0;
		var result;
		
		do // trace around the perimeter
		{
			result = findNext(next, angle);
			next = result.next;
			
			// filter out redundant points on straight lines
			if (result.angle == angle)
			{
				// if the angle hasn't changed, 
				// overwrite the previous point with the latest one.
				outside[outside.length-1] = next;
			}
			else
			{
				// if it has, update the angle, and tack on another point.
				angle = result.angle;
				outside[outside.length] = next;
			}
		}
		while (next.y() != bottomRight.y()); // until we're back where we started

		points = outside;
		
		// add another reference to the first Point onto the end
		points[points.length] = points[0];
	}
	
	// get the next point the rubber-band would hit
	function findNext(point, angleOfLastLine)
	{
		var next, angle, testAngle;
		
		
		// Iterate through all points.
		for (var i = 0; i < points.length; i++)
		{
			// Grab a potential candidate point for next-dom.
			testPoint = points[i];
			
			// Skip over points that are the same 
			// as the point we're coming from.
			if (!point.equals(testPoint))
			{
			
				// If we've stashed one as the best candidate for next-dom,
				// compare it with the one we're currently testing.
				if (next)
				{
					// Grab the angle between the point we're coming from
					// and the point we're testing
					
					testAngle = positizeRadians(
						point.angleOfLineTo(testPoint) - angleOfLastLine);

					// If it's less than that of the point believed to be
					// the best candidate, then replace that point and its 
					// angle with the one we're testing.
					if (testAngle < angle)
					{
						angle = testAngle;
						next = testPoint;
					}
				}
				// If we haven't stashed one yet, stash the one we're testing.
				else
				{
					next = testPoint;
					angle = positizeRadians(
						point.angleOfLineTo(next) - angleOfLastLine);
				}
			}
		}
		
		return { next: next, angle: angle + angleOfLastLine };
	}

	this.div = div;
	function div()
	{
		return d;
	}

}

function CartesianPlaneElement(/*int*/ w, /*int*/ h, /*string*/ color)
{
	var container, origin;
	
	construct();
	function construct()
	{
		var s;
	
		// The container for the whole thing
		container = document.createElement('div');
			s = container.style;
			s.position = 'relative';
			s.top = '0px';
			s.left = '0px';
			s.width = w+'px';
			s.height = h+'px';
			s.overflow = 'hidden'
		
		// Place a transparent border directly over the canvas,
		// so that if the browser can't do transparent borders,
		// the whole (messed-up) canvas becomes obscured.
		var bugblocker = document.createElement('div');
			s = bugblocker.style;
			s.fontSize = '0px';
			s.width = w+'px';
			s.height = '0px';
			s.position = 'absolute';
			s.top = '0px';
			s.left = '0px';
			s.borderBottom = h+'px solid transparent';
			s.zIndex = '1';
		
		// The canvas, with background color
		var canvas = document.createElement('div');
			s = canvas.style;
			s.background = color;
			s.width = w+'px';
			s.height = h+'px';
			s.position = 'absolute';
			s.top = '0px';
			s.left = '0px';
			s.zIndex = '0';

		// A point for containing the elements in the plane,
		// to be placed at the center of the canvas so that all 
		// points are relative to the center.
		origin = document.createElement('div');
			s = origin.style;
			s.fontSize = '0px;'
			s.width = '0px';
			s.height = '0px';
			s.position = 'absolute';
			s.left = '50%';
			s.top = '50%';
		
		container.appendChild(bugblocker);
		container.appendChild(canvas);
			canvas.appendChild(origin);
	}
	
	this.addElement = addElement;
	function addElement(e)
	{
		origin.appendChild(e.div());
	}
	
	this.removeElement = removeElement;
	function removeElement(e)
	{
		var d = e.div();
		if (d.parentNode == origin)
		{
			origin.removeChild(d);
		}
	}
	
	this.div = div;
	function div()
	{
		return container;
	}
}

function RectangleElement(/*IntPoint*/ p1, /*IntPoint*/ p2, /*string*/ c)
{
	var d, s;
	
	construct();
	function construct()
	{
		var top    = Math.max(p1.y(), p2.y());
		var bottom = Math.min(p1.y(), p2.y());
		var left   = Math.min(p1.x(), p2.x());
		var right  = Math.max(p1.x(), p2.x());
		
		var height = top - bottom;
		var width  = right - left;
		
		d = document.createElement('div');
		s = d.style;
		s.fontSize = '0px;'
		s.position = 'absolute';
		s.width = width+'px';
		s.height = height+'px';
		s.top = (-top)+'px';
		s.left = (left)+'px';
		
		s.background = c;
//		s.background = randomColor();
	}
	
	this.div = div;
	function div()
	{
		return d;
	}
}

function createDiv()
{
	var div = document.createElement('div');
	var s = div.style;
	s.fontSize = '0px;'
	s.position = 'absolute';
	s.height = '0px';
	s.width = '0px';
	s.left = '0px';
	s.top = '0px';
	
	return div;
}

function RightTriangleElement(/*IntPoint*/ p, /*int*/ w, /*int*/ h, /*int*/ q, /*string*/ c)
{
	var d, s;
	
	construct();
	function construct()
	{
		d = createDiv();
		s = d.style;
		
		var overlap = 0; // this was a fairly decent way of fixing the gaps
		var x = p.x();
		var y = -p.y();
		var steep = (h > w);
		
		if (steep)
		{
			s.width = overlap+"px";
		}
		else
		{
			s.height = overlap+"px";
		}
		
		switch (q)
		{
			case 1:
				overlap = 0; // only use overlap on "bottom" slants
				if (steep)
				{
					s.borderBottom = h+"px solid "+c;
					s.borderRight = w+"px solid transparent";
					s.top = (y-h)+"px";
					s.left = (x)+"px";
				}
				else
				{
					s.borderLeft = w+"px solid "+c;
					s.borderTop = h+"px solid transparent";
					s.top = (y-h-overlap)+"px";
					s.left = (x)+"px";
				}
				break;
				
			case 2:
				overlap = 0; // only use overlap on "bottom" slants
				if (steep)
				{
					s.borderBottom = h+"px solid "+c;
					s.borderLeft = w+"px solid transparent";
					s.top = (y-h)+"px";
					s.left = (x-w-overlap)+"px";
				}
				else
				{
					s.borderRight = w+"px solid "+c;
					s.borderTop = h+"px solid transparent";
					s.top = (y-h-overlap)+"px";
					s.left = (x-w)+"px";
				}
				break;
				
			case 3:
				if (steep)
				{
					s.borderTop = h+"px solid "+c;
					s.borderLeft = w+"px solid transparent";
					s.top = (y)+"px";
					s.left = (x-w-overlap)+"px";
				}
				else
				{
					s.borderRight = w+"px solid "+c;
					s.borderBottom = h+"px solid transparent";
					s.top = (y)+"px";
					s.left = (x-w)+"px";
				}
				break;
			
			case 4:
				if (steep)
				{
					s.borderTop = h+"px solid "+c;
					s.borderRight = w+"px solid transparent";
					s.top = (y)+"px";
					s.left = (x)+"px";
				}
				else
				{
					s.borderLeft = w+"px solid "+c;
					s.borderBottom = h+"px solid transparent";
					s.top = (y)+"px";
					s.left = (x)+"px";
				}
				break;
		}
	}

	this.div = div;
	function div()
	{
		return d;
	}
}

function randomColor()
{
	var c = "0123456789abcdef";
	var s = "#";
	s += c.charAt(Math.floor(Math.random()*16));
	s += c.charAt(Math.floor(Math.random()*16));
	s += c.charAt(Math.floor(Math.random()*16));
	return s;
}

var cp, poly;

function Regular(sides,length)
{
	var dist = length * Math.sqrt(2);
	var interval = 2 * Math.PI / sides;
	var angle = 0;
	
	var poly;
	
	var d = null;
	
	rotate(0);
	
	this.rotate = rotate;
	function rotate(radians)
	{
		angle += radians;
		
		var p = new Array();
		var x, y, a;
		for (var i = 0; i < sides; i++)
		{
			a = angle + i * interval;
			x = Math.cos(a) * dist;
			y = Math.sin(a) * dist;
			
			
			p[i] = new IntPoint(x,y);
		}
		
		d = (new PolygonElement(p,'red')).div();
	}
	
	this.div = div;
	function div()
	{
		return d;
	}
}

function write(s)
{
	document.body.appendChild(document.createTextNode(s));
	document.body.appendChild(document.createElement('br'));
}

function PointElement(/*Point*/ p, /*number*/ size, /*string*/ color)
{
	var rectangle;
	
	construct();
	function construct()
	{
		var half = size / 2;
		var x = p.x();
		var y = p.y();
		rectangle = new RectangleElement(
			new IntPoint(x-half,y-half),
			new IntPoint(x+half,y+half),
			color
		);
	}
	this.div = rectangle.div;
}