window.FillGraph = function(canvasID, colors) {
	return this.init(canvasID, colors);
}

FillGraph.objectMap = new Array();
FillGraph.setupCanvas = function() {
	var canvases = document.getElementsByTagName("canvas");
	for(var i=0;i<canvases.length;i++) {
		var className = canvases[i].className;
		if(className.toLowerCase() == "fillgraph") {
			var colors = canvases[i].getAttribute("color").split(",");
			var cid = canvases[i].getAttribute("id");
			FillGraph.objectMap[cid] = new FillGraph(cid, colors);
		}
	}
}

FillGraph.prototype = {
	init: function(canvasID, colors) {
		this.cid = canvasID;
		this.colors = colors;
		return this;
	},

	draw: function(context2D, values, width, height, coefficient) {
		with(context2D) {
			strokeStyle = "lightgrey";
			for(var i=0;i<values.length-1 && values.length > 1;i++) {
				var chvals = values[i];
				var lineX1 = 20*i;
				var lineX2 = (20*(i+1));
				var lineY1 = 0;
				var lineY2 = 0;
				for(var j=0;j<chvals.length;j++) {
					fillStyle = this.colors[j];
					beginPath();
					moveTo(lineX1, 418-lineY1);

					var val = new Number(chvals[j]);
					val = val > 500 ? 500*coefficient : val*coefficient;
					lineY1 += val;
					val = new Number(values[i+1][j]);
					val = val > 500 ? 50*coefficient : val*coefficient;
					lineY2 += val;

					lineTo(lineX1,418-lineY1);
					lineTo(lineX2,418-lineY2);
					lineTo(lineX2,418-(lineY2-val));
					closePath();
					stroke();
					fill();
				}
			}
		}
	},

	update: function(values, width, height, coefficient) {
		var context2D = document.getElementById(this.cid).getContext('2d');
		context2D.save();
		context2D.clearRect(0, 0, width, height);
		this.draw(context2D, values, width, height, coefficient);
		context2D.restore();
	}
}
