// Use a table to simulate a frame buffer for drawing in Javascript. 
// by David Turover, October 2008.


function colorString(r,g,b){
	return "rgb(" +r+ "," +g+ "," +b+ ")"; 
}

function bufTable(x,y, color /*optional result of colorString*/){
	if(!color){ color = colorString(255,255,255); }
	this.numCols = parseInt(x); 
	this.numRows = parseInt(y); 
	this.length = x * y;

	this.data = document.createElement("table");
	this.data.setAttribute("class", "bufTable");

	this.data.border = 0; 
	this.data.cellPadding = 0; 
	this.data.cellSpacing = 0; 

	// initialize the buftable
	for(var j = 0; j < this.numRows; j++){
		var tr = document.createElement("tr");
		for(var i = 0; i < this.numCols; i++){
			// TODO: Check for failure to create elements.
			var px = document.createElement("td");
			px.width = 1; 
			px.height = 1; 
			//px.style.backgroundColor = "rgb(255,255,255)";
			px.style.backgroundColor = color;

 			// With these, 25s to create, 2.5s to append to table.
 			// Using CSS, 18s to create, 16s to append. 
			//px.style.margin = "0px"; 
			//px.style.padding = "0px"; 
			tr.appendChild(px); 
		}
		this.data.appendChild(tr); 
	}

	this.getPixel = function(x,y){
		var numTrs = y;
		// TODO: More sanity checking in case a createElement failed .
		var tr = this.data.firstChild;
		for(var j = 0; j < y; j++){
			tr = tr.nextSibling; 
		}
		var td = tr.firstChild;
		for(var i = 0; i < x; i++){
			td = td.nextSibling; 
		}
		return td;
	}

	this.setPixel = function(x,y,r,g,b){
		var pxPtr = this.getPixel(x,y); 
		//pxPtr.style.backgroundColor = "rgb(" +r+ "," +g+ "," +b+ ")"; 
		if(r.toString().match(/^rgb/)){
			// r is a color string. 
			pxPtr.style.backgroundColor = r;
		} else { 
			// Deprecated "r,g,b" mathod. 
			pxPtr.style.backgroundColor = colorString(r,g,b); 
		}
	}


	
	// Draw a square border as inefficiently as possible. 
	this.debug_drawSquare = function(){
		var w= parseInt(this.numCols);
		var h= parseInt(this.numRows);
		for(j=0; j<h; j++){
			for(i=0; i<w; i++){
				if(j==0 || i==0 || j == h-1 || i == w-1){
					myBuf.setPixel(i,j, 0,0,0);
				} else {
					myBuf.setPixel(i,j, 255,255,255);
				}
			}
		}
	}

	this.drawBorder = function(weight, color){
		var w = parseInt(this.numCols);
		var h = parseInt(this.numRows);
		if(!weight){ weight = 1; } // width of border.
		if(!color){ color = colorString(0,0,0); } 
		for(i=0; i<w; i++){
			var y = 0; 
			while(y < weight && y < h/2){
				this.setPixel(i,y, color);
				this.setPixel(i,h-(++y), color);
			}
		}
		for(j=weight; j<h-weight; j++){
			var x = 0; 
			while(x < weight && x < w/2){
     				this.setPixel(x,j, 0,0,0);
       				this.setPixel(w-(++x),j, 0,0,0);
			}
		}
	}



	return this; 
}


