/*
 * Javascript Wolfenstein 3D Enemy Texture
 * Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com
 */

Canvas3D.EnemyTexture = function(strSource) {
	var oImg = new Image();

	this._strSource = strSource;

	var oTextureCanvas = document.createElement("canvas");
	oTextureCanvas.width = oTextureCanvas.style.width = 64*13;
	oTextureCanvas.height = oTextureCanvas.style.height = 64;
	var oTextureCtx = oTextureCanvas.getContext("2d");

	var iLODLevels = 3;
	var iTextureSize = 64;
	var aLOD = [];
	var aLODSizes = [64,48,24];

	var bLoaded = false;

	oImg.onload = function() {
		var iTime = new Date().getTime();

		oTextureCtx.drawImage(this,0,0,64*13,64);

		//document.body.appendChild(oTextureCanvas);

		var iLODSize = iTextureSize;
		for (var i=0;i<iLODLevels;i++) {
			if (i==0) {
				aLOD[i] = oTextureCanvas;
				aLOD[i].lodsize = iTextureSize;
			} else {
				iLODSize = aLODSizes[i];

				var oLODCanvas = document.createElement("canvas");
				oLODCanvas.width = oLODCanvas.style.width = iLODSize*13;
				oLODCanvas.height = oLODCanvas.style.height = iLODSize;
				var oLODCtx = oLODCanvas.getContext("2d");

				oLODCtx.drawImage(
					oTextureCanvas,
					0, 0,
					64*13, 64,
					0, 0,
					iLODSize*13, iLODSize
				);
				aLOD[i] = oLODCanvas;
				oLODCanvas.lodsize = iLODSize;
			}
			//document.body.appendChild(aLOD[i]);
		}
		bLoaded = true;
		//console.log("Enemy texture prepared in " + (new Date().getTime() - iTime) + " ms");
	}
	oImg.src = strSource;

	this.getCanvas = function() {
		if (bLoaded) return oTextureCanvas;
	}

	this.isLoaded = function() {
		return bLoaded;
	}

	this.draw = function(oCtx, iIdx, iLOD, iX, iY, fWidth, fHeight) {
		if (iX == NaN || iY == NaN || fWidth == NaN || fHeight == NaN) return;
		if (fHeight < 1 || fWidth < 1 || fHeight > 1000 || fWidth > 1000) return;
		
		var iLODSize = aLOD[iLOD].lodsize;
		//console.log(iLODSize, iX, iY, fWidth, fHeight);
		try {
		oCtx.drawImage(
			aLOD[iLOD],
			iIdx*iLODSize, 0,
			iLODSize, iLODSize,
			iX,
			iY,
			fWidth,
			fHeight
		);
		} catch(e) {}
	}
};



