var CanvasBird = function(w, h){
	this.w = w;
	this.h = h;
	
	this.x = Math.random() * w;
	this.y = (Math.random() < 0.5) ? -50 : h + 50;
	this.z = Math.random(); // 0 far away 1 close
	
	this.nFrames = 22;
	this.currentFrame = parseInt((this.nFrames-1)*Math.random());
	this.grabNewFrame = false;
	
	this.speed = 1 + 2*Math.random();
	
	this.size = 5 + 20*Math.random();
	
	this.dx = Math.random()*w;
	this.dy = Math.random()*h;
	
	this.vx = (this.dx - this.x)*this.speed/Math.abs(this.dx-this.x) * this.z;
	this.vy = (this.dy - this.y)*this.speed/Math.abs(this.dy-this.y) * this.z;
	this.vz = 0.25*(Math.random() - Math.random());
	
	this.phase = Math.random()*360;
	
	this.angle = Math.atan2(this.vy, this.vx);
	
	this.friction = 0.95;
	
	this.update = function(){
		var angle = this.phase * Math.PI / 180;
		this.vx = (Math.sin(angle) - Math.cos(angle));
		
		this.phase += Math.random();
		if(this.phase > 360) this.phase = 0;
		
		this.x += this.vx;
		this.y += this.vy;
		
		if(this.outOfBounds()){
			this.reset();
		}
		
		this.angle = Math.atan2(this.vy, this.vx);
		
		if(this.grabNewFrame){
			this.currentFrame--;
			if(this.currentFrame < 0){
				this.currentFrame = this.nFrames - 1;
			}
			this.grabNewFrame = false;
		}
		else this.grabNewFrame = true;
	}
	
	this.outOfBounds = function(){
		return (this.x < -50 || this.x > this.w + 50) || (this.y < -50 || this.y > this.h + 50);
	}
	
	this.render = function(ctx, texture){
		var x = 25*this.currentFrame;
		
		//ctx.fillStyle = "#000";
		ctx.save();
		ctx.translate(this.x, this.y);
		ctx.rotate(this.angle);
		ctx.drawImage(texture, x, 0, 25, 25, 0, 0, this.z*this.size, this.z*this.size);
		//ctx.fillRect(0, 0, this.z*this.size, this.z*this.size);
		ctx.restore();
	}
	
	this.reset = function(){
		this.dx = Math.random()*w;
		this.dy = Math.random()*h;
		
		this.vx = (this.dx - this.x)*this.speed/Math.abs(this.dx-this.x) * this.z;
		this.vy = (this.dy - this.y)*this.speed/Math.abs(this.dy-this.y) * this.z;
		
		this.phase = Math.random() * 360;
	}
	
	this.resize = function(w, h){
		this.w = w;
		this.h = h;
	}
}
