﻿function Graphics(canvas)
{
	this.canvas = canvas;
	this.cache = new Array;
	this.shapes = new Object;
	this.nObject = 0;

	// defaults
	this.penColor = "black";
	this.zIndex = 0;

	// methods
	var me = this;

	this.createPlotElement = function(x,y,w,h) 
	{
		// detect canvas
		if ( !me.oCanvas )
		{
			if ( (me.canvas == undefined) || (me.canvas == "") ) 
				me.oCanvas = document.body;
			else 
				me.oCanvas = document.getElementById(me.canvas);
		}

		// retrieve DIV
		var oDiv;
		if ( me.cache.length )
			oDiv = me.cache.pop();
		else 
		{
			oDiv = document.createElement('div');
			me.oCanvas.appendChild(oDiv);

			oDiv.style.position = "absolute";
			oDiv.style.margin = "0px";
			oDiv.style.padding = "0px";
			oDiv.style.overflow = "hidden";
			oDiv.style.border = "0px";
		}

		// set attributes
		oDiv.style.zIndex = me.zIndex;
		oDiv.style.backgroundColor = me.penColor;
		
		oDiv.style.left = x + "px";
		oDiv.style.top = y + "px";
		oDiv.style.width = w + "px";
		oDiv.style.height = h + "px";

		oDiv.style.visibility = "visible";
		
		return oDiv;
	}

	this.releasePlotElement = function(oDiv)
	{
		oDiv.style.visibility = "hidden";
		me.cache.push(oDiv);
	}

	this.addShape = function(shape)
	{
		shape.oGraphics = me;
		shape.graphicsID = me.nObject;
		me.shapes[me.nObject] = shape;
		me.nObject++;
		shape.draw();
		return shape;
	}

	this.removeShape = function(shape)
	{
		if ( (shape instanceof Object) && 
			(shape.oGraphics == me) && 
			(me.shapes[shape.graphicsID] == shape) )
		{
			shape.undraw();
			me.shapes[shape.graphicsID] = undefined;
			shape.oGraphics = undefined;
		}
	}

	this.clear = function()
	{
		for ( var i in me.shapes )
			me.removeShape(me.shapes[i]);
	}

	//=============================================================================
	// Line
	this.drawLine = function(x1,y1,x2,y2,width,dotted)
	{
		return me.addShape(new Line(x1,y1,x2,y2,width,dotted))
	}
}

function Line(x1,y1,x2,y2,width,dotted)
{
	this.x1 = x1;
	this.y1 = y1;
	this.x2 = x2;
	this.y2 = y2;
	this.width = width;
	this.dotted = dotted;
	var me = this;

	this.draw = function()
	{
		me.plots = new Array;

		var dx = me.x2 - me.x1;
		var dy = me.y2 - me.y1;
		var x = me.x1;
		var y = me.y1;

		var n = Math.max(Math.abs(dx),Math.abs(dy));
		dx = dx / n;
		dy = dy / n;
		for ( i = 0; i <= n; i++ )
		{
			if ( i % 5 == 0 || !me.dotted) {
				me.plots.push(me.oGraphics.createPlotElement(Math.round(x),Math.round(y),me.width,me.width));
			}

			x += dx;
			y += dy;
		}
	}
	this.undraw = function()
	{
	    if (me.plots != undefined)
	    {
    		while ( me.plots.length )
	    		me.oGraphics.releasePlotElement(me.plots.pop());
    		me.plots = undefined;
   		}
	}
}
