
/**
 * repräsentiert ein Teilbild eines Sprites.
 *
 */
function SpritePart(){
	this.id = 0;
	this.image = 0;
	this.x = 0;
	this.y = 0;
	this.width = 0;
	this.height = 0;
}

/**
 * Ein Bild, dass sich aus mehreren Einzelbildern zusammensetzt. 
 *
 */
function Sprite(){
	this.image = null;
	this.parts = new Array();
}

Sprite.prototype.draw = function(id, x, y, sx, sy){
	var part = this.parts[id];
	
	if(x + part.width > 0){
		context.scale(sx,sy);
		
		var _x = x / sx;
		if(sx == -1){
			_x -= part.width;
		}

		context.drawImage(this.image, part.x, part.y, part.width, part.height,_x,y/sy, part.width, part.height);
		// undo scale
		context.scale(1/sx,1/sy);
	}
	
}

/**
 * Ein Spritebild in gleichmäßige Teile aufspalten.
 *
 */
function createEquallySizedSprite(image, partsX, partsY){
	logDebug("createEquallySizedSprite("+image+", "+partsX+", "+partsY+")");

	var sprite = new Sprite();
	sprite.image = image;
	var id = 0;
	for(var y = 0; y < partsY; y++){
		var offsetY = y * (image.height / partsY);
		var height = (y+1)*(image.height / partsY) - offsetY;
		for(var x = 0; x < partsX; x++){
			var offsetX = x * (image.width / partsX);
			var width = (x+1)*(image.width / partsX) - offsetX;
			
			var part = new SpritePart();
			part.id = id;
			id++;
			part.image = image;
			part.x = offsetX;
			part.y = offsetY;
			part.width = width;
			part.height = height;
			
			sprite.parts.push(part);
		}
	}
	
	logDebug("createEquallySizedSprite - end");
	return sprite;
}

/**
 * Eine Animation besteht aus mehreren SpriteParts die hintereinander abgespielt werden.
 * die KeyFrames bestimmen, zu welchem Zeitpunkt welches der SpriteParts gezeichnet werden soll. 
 *
 */
function SpriteAnimation(sprite){
	this.sprite = sprite;
	this.keyFrames = new Array();
	this.time = 0;
	this.end = 0;
}

SpriteAnimation.prototype.addKeyFrame = function(time, index){
	this.keyFrames[time] = index;
	this.keyFrames.sort(function(a,b){return a - b});
	this.end = Math.max(this.end, time);
}

SpriteAnimation.prototype.addTime = function(time){
	//logDebug("addTime("+time+")");
	this.time += time;
	while(this.time > this.end){
		this.time = this.time - this.end;
	}
}

SpriteAnimation.prototype.setTime = function(time){
	this.time = time;
}

SpriteAnimation.prototype.getIndex = function(){
	var last = 0;
	for(var i in this.keyFrames){
		if(last <= this.time && this.time <= i){
			if(this.time - last > i - this.time){
				return this.keyFrames[i];
			}else{
				return this.keyFrames[last];
			}
		}
	}
}

SpriteAnimation.prototype.dump = function(time){
	for(var i in this.keyFrames){
		logInfo(i + "=" + this.keyFrames[i]);
	}
}


