/**
 * NengaBitkun
 * 
 * args:
 * 	selname
 *	targetY
 *	marginTop
 *	animation
 */
var NengaBitkun = function (args) {
	var _args = args;
	var $_element = $(args.selname);
	var _pos = null;
	var _locs = [];

	/**
	 * init
	 */
	var init = function () {
		$_element.css("marginTop", (_args.marginTop+"px"));
		_pos = {x: parseInt($_element.css("marginLeft")), y: parseInt($_element.css("marginTop")) };
dPut("NengaBitkun: pos=" + _pos.x + ", " + _pos.y);

		if (args.animation) {
			var px = _pos.x,
				pxe = -301,
				step = 5,
				py;
			var calcY = function (x) {
				return parseInt(Math.sin(x / 180 * Math.PI)*30);
			};
			
			var index = 1;
			while (px > pxe) {
				py = calcY(index*3);
				_locs.push({x:px, y:py});
//dPut("loc: " + px + "," + py );
				px -= step;
				index++;
			}
			$_element.css("marginLeft", (px+"px"));
			_locs.reverse();
		}
	};

	/**
	 * animate
	 */
	this.animate = function () {
		var index = 0;
		var movef = function () {
			if (index >= _locs.length) {
				jQuery(window).trigger(new NengaEvent('bitkunAnimateionCompleted'));
				return;
			}
//dPut(index + ": " + _locs[index].x + "," + _locs[index].y);
			$_element.css({marginLeft: (_locs[index].x+"px"), marginTop: (_pos.y + _locs[index].y + "px")});

			if (++index >= _locs.length) {
				jQuery(window).trigger(new NengaEvent('bitkunAnimateionCompleted'));
				return;
			}
			setTimeout(movef, 20);
		};
		
		$_element.css("display", "block");
		movef();
	};
	
	/**
	 * quake
	 */
	this.quake = function () {
		var targetY = parseInt($_element.css("marginTop"));
		var py = targetY - 20;

		$_element.css("marginTop", (py+"px"));
		$_element.animate({marginTop: (targetY+"px")}, 300, "easeOutBounce");
	};
	
	/**
	 * changeUp
	 */
	this.changeUp = function (b) {
		$("#bitkunUp").css("display", ((b)? "block" : "none"));
	};
	
	/**
	 * scroll
	 */
	this.scroll = function (scrollY, ticks, tickpct) {
		var py = _pos.y - ((_pos.y - _args.targetY) * tickpct);
		var px = Math.floor(Math.sin((ticks/10) / 180 * Math.PI) * 4);
		
		$_element.css({marginTop: (py+"px"), marginLeft: (_pos.x + px + "px")});
	};
	
	init();
};
