/**
 * Player
 * @classDescription  
 * @dependence        Mootools (http://www.mootools.net)
 * @author            Aken.li (http://www.kxbd.com)
 * @created           2009-11-25
 */
var Player = new Class({

	Implements: [Options,Events],
	
	options:{
		sign:'P',
		interval:30,
		width:40,
		height:40,
		speedX:10,
		speedY:0,
		jumpPower:25,
		gravity:1,
		ground:460
	},
	
	initialize:function(pHolder, options){
		this.setOptions(options);
		this.isJumping = false;
		this.isLiving = false;

		this.x = 350;
		this.y = this.options.ground;
		this.width = this.options.width;
		this.height = this.options.height;
		this.mouseX = 350;
		//this.speedX = this.options.speedX;
		this.speedY = this.options.speedY;
		this.player = this.create();
		this.holder = $(pHolder);
		this.player.inject(this.holder);

		this.init();
	},

	create:function(){
		return new Element('div', {
			'class': 'player',
			'text': this.options.sign,
			'styles': {
				'left':this.x,
				'top':this.y
			}
		});
	},

	init:function(){
		this.attachEvent();
		this.moveXTimer = this.moveX.periodical(this.options.interval,this);
	},

	attachEvent:function(){
		//this.holder.addEvent('click', this.jump.bind(this));
		this.holder.getParent().addEvent('mousemove', function(evt){
			this.mouseX = evt.client.x;
		}.bind(this));
	},

	render:function(){
		this.player.setStyles({
			left:this.x,
			top:this.y
		});
	},

	moveX:function(){
		var _mX = Math.min(Math.max(30, this.mouseX), 690);
		var _x = this.isJumping? Math.abs(_mX - this.x)*0.15:this.options.speedX;
		if (this.x == _mX) {
			this.render();
			return;
		}else {
			if (this.x < _mX ) {
				this.x = Math.min(_mX, this.x + _x);
			}else {
				this.x = Math.max(_mX, this.x - _x);
			}
			this.render();
		}
	},

	moveY:function(){
		this.speedY -= this.options.gravity;
		this.y = Math.min(this.y - this.speedY, this.options.ground);
		if (this.speedY < -90) this.y = this.options.ground;
		if (this.y == this.options.ground) {
			if (this.isLiving == true) {
				this.isLiving = false;
				this.fireEvent('gameOver',this);
			}
			this.isJumping = false;
			this.moveYTimer = $clear(this.moveYTimer);
			this.speedY = 0;
		}
		this.render();
	},

	jump:function(){
		if (!this.isJumping) {
			this.isJumping = true;
			this.speedY = this.options.jumpPower;
			this.moveYTimer = this.moveY.periodical(this.options.interval,this);
		}
	}
});
