/*
* Support class for most visual things.
* Manages a power-of-2 sheet of power-of-2 image tiles.
*
* tilew: pow(2,tilew) = pixel width of 1 tile
* tileh: pow(2,tileh) = pixel height of 1 tile
* sheetw: pow(2,sheetw) = number of tiles on one row of the sheet
* sheeth: pow(2,sheeth) = number of tiles on one column of the sheet
* image: image (or canvas) containing the pixel content to draw
*/

"use strict";

var TileSheet = function(tilew, tileh, sheetw, sheeth, image){
	this.tile_width = (tilew!=null && !isNaN(parseInt(tilew))) ? parseInt(tilew) : 4;
	this.tile_width = Math.max(0,this.tile_width);
	this.tile_pixel_width = 1<<this.tile_width;

	this.tile_height = (tileh!=null && !isNaN(parseInt(tileh))) ? parseInt(tileh) : 4;
	this.tile_height = Math.max(0,this.tile_height);
	this.tile_pixel_height = 1<<this.tile_height;

	this.sheet_width = (sheetw!=null && !isNaN(parseInt(sheetw))) ? parseInt(sheetw) : 4;
	this.sheet_width = Math.max(0,this.sheet_width);

	this.sheet_height = (sheeth!=null && !isNaN(parseInt(sheeth))) ? parseInt(sheeth) : 4;
	this.sheet_height = Math.max(0,this.sheet_height);

	this.index_col_mask = (1<<this.sheet_width) - 1;
	this.index_row_mask = ((1<<this.sheet_height) - 1)<<this.sheet_width;

	if (image==null){
		this.tile_bank = document.createElement('canvas');
		this.tile_bank.width  = (1<<this.tile_width)<<this.sheet_width;
		this.tile_bank.height = (1<<this.tile_height)<<this.sheet_height;
	}
	else{
		this.tile_bank=image; // and cross our fingers it really is an image
	}
};
	/* draws tile tilenum onto the given canvas at (x,y) */
	TileSheet.prototype.drawIntoCanvas = function(canvas,tilenum,x,y){
		var tilecol = tilenum & this.index_col_mask;
		var tilerow = (tilenum & this.index_row_mask)>>this.sheet_width;
		canvas.getContext("2d").drawImage(
			this.tile_bank, 
			tilecol<<this.tile_width, tilerow<<this.tile_height, 
			this.tile_pixel_width, this.tile_pixel_height,
			x,y,
			this.tile_pixel_width, this.tile_pixel_height);
	};
