var id = 0;
function compareColors(color1, color2) {
	if (color1.substr(0,3) == "rgb")
	{
		var rgb = color1.substr(4,color1.length-5).split(",");
		color1 = "#"+decToHex(rgb[0],2)+decToHex(rgb[1],2)+decToHex(rgb[2],2);
	}
	if (color2.substr(0,3) == "rgb")
	{
		var rgb = color2.substr(4,color2.length-5).split(",");
		color2 = "#"+decToHex(rgb[0],2)+decToHex(rgb[1],2)+decToHex(rgb[2],2);
	}
	if (color1.toLowerCase() == color2.toLowerCase()) {
		return true;
	}
	return false;
}

function addPixelNormal(top, left, color, parent) {
	var d = document.createElement("div");
	id++;
	d.style.width = "4px";
	d.style.height = "4px";
	d.style.backgroundColor = color;
	d.style.position = "absolute";
	d.style.left = left;
	d.style.top = top;
	d.id = id;
	if (parent == undefined) {
		parent = document.getElementById("body");
	}
	parent.appendChild(d);
	return d;
}

function addPixelRunLengthOptimized(top, left, color, parent) {
	var lp = document.getElementById(id);
	if (lp)
	{
		lpw = parseInt(lp.style.width);
		lpr = parseInt(lp.style.left) + lpw;
		if (lp && compareColors(lp.style.backgroundColor, color) &&
		lpr == parseInt(left))
		{
			lpw += 4;
			lp.style.width = lpw + "px";
			return lp;
		}
	}
	return addPixelNormal(top, left, color, parent);
}

addPixel = addPixelNormal;

function enableRLO() {
	addPixel = addPixelRunLengthOptimized;
}

function disableRLO() {
	addPixel = addPixelNormal;
}

function renderGraphics(gfx, top, left, colors, parent) {
	var c = '';
	for(j = 0; j < gfx.length; j++)
	{
		for(i = 0; i < gfx[j].length; i++)
		{
			c = colors[gfx[j].substr(i,1)];
			if (c != undefined)
			{
				addPixel(top + (j << 2), left + (i << 2), c, parent);
			}
		}
	}
}
