/**
@author bibby
A moveable character
**/

var Char = function(params)
{
	this.extends(Tangible)
	.extend({
		'class':'Char',
		imgpath:'imgs/',
		dir:['S','W'],
		id:'char'+Math.floor(Math.random()*10000),
		stepi:0,
		stepTime:4,
		stepSize:[5,5],
		char:null,
		imgs:{},
		
		step:function(i)
		{
			if(is(i,'number') && i < 4 )
			{
				this.stepi=i;
				return;
			}
			
			this.stepi++;
			if(this.stepi == 4)
				this.stepi=0;
		},
		
		make:function()
		{
			var imgs={}, img, dir;
			var dirs = ['NE','NW','SE','SW'];
			do
			{
				dir = dirs.current();
				imgs[dir]=[];
				img = new Image(this.dim.width,this.dim.height);
				img.src = this.imgpath + this.id + dir + '1.gif';
				
				imgs[dir][0] =
				imgs[dir][2] = img;
				
				img = new Image(this.dim.width,this.dim.height);
				img.src = this.imgpath + this.id + dir + '2.gif';
				imgs[dir][1] = img;
				
				img = new Image(this.dim.width,this.dim.height);
				img.src = this.imgpath + this.id + dir + '3.gif';
				imgs[dir][3] = img;
					
				this.imgs[dir] = imgs[dir];
				
			} while (is(dirs.next()));
			
			return this;
		},
		
		display:function()
		{
			if(!is(document.getElementById(this.id)))
			{
				this.char = new Image(this.dim.width,this.dim.height);
				with(this.char)
				{
					src = this.src();
					id = this.id;
				};
				document.body.appendChild(this.char);
			}
			else
				this.char.src = this.src();
			
			with(this.char.style)
			{
				position = 'absolute';
				left = this.pos.left;
				top = this.pos.top;
				zIndex = 100;
			};
			
		},
		
		src:function()
		{
			return this.imgs[this.dir.join('')][this.stepi].src;
		},
		
		load:function()
		{
			Timer.reg(this);
			this.make().display();
			if(is(Contact,'object'))
				Contact.register(this);
		},
		
		timer:function(t)
		{
			if( t % this.stepTime != 0)
				return;
			
			var keys= Key.getKeys();
			if(keys.length == 0)
			{
				if(this.stepi!=0)
				{
					this.step(0);
					this.char.src = this.src();
				}
				return;
			}
			
			
			if(keys.has(37))
				keys = keys.filterOut(39);
			if(keys.has(38))
				keys = keys.filterOut(40);
			if( (keys.has(37) || keys.has(39)) && !keys.has(38) )
				this.dir[0]='S';
			
			this.move(keys);
		},
		
		move:function(keys)
		{
			var area = this.area();
			keys.each(function(i,dood)
			{
				switch(+this)
				{
					case 37:
						dood.pos.left -= dood.stepSize[0];
						dood.dir[1]='W';
						break;
					case 38:
						dood.pos.top -= dood.stepSize[1];
						dood.dir[0]='N';
						break;
					case 39:
						dood.pos.left += dood.stepSize[0];
						dood.dir[1]='E';
						break;
					case 40:
						dood.pos.top += dood.stepSize[1];
						dood.dir[0]='S';
						break;
				}
			},this);
			
			this.step();
			this.display();
			
		}
		
		
	},true) // override Tangible.move
	.extend(params,true)
	.init();
};
