import GraphHolder;
import mx.controls.NumericStepper;
class Bead extends MovieClip {
	var graph:GraphHolder;
	var x0:Number;
	var vx:Number = 0;
	var vy:Number = 0;
	var track:Array;
	var crossTrack:Array;
	var vTrack:Array;
	var replaying:Boolean = false;
	var frame:Number = 0;
	var cross:MovieClip;
	var damping:NumericStepper;

	function Bead() {
		init();
		reset();
	}
	
	function reset():Void {
		track = [];
		crossTrack = [];
		vTrack = [];
		frame = 0;
		cross._x = _x;
		cross._y = _y;
	}
	
	function init():Void {
		x0=_x;
		var line = _root.createEmptyMovieClip("line", 95);
		line.lineStyle(3, 0x008888, 30);
		line.moveTo(0, _y);
		line.lineTo(Stage.width, _y);
		cross = _root.attachMovie("CrossHair", "cross", 100, {_x:_x, _y:_y, bead:this});
		cross.onPress = function() {
			this.startDrag(true, 0, _y, Stage.width, _y);
			this["bead"].drag();
		}
		cross.onRelease = function() {
			this.stopDrag();
			this["bead"].noDrag();
		}
		cross.onReleaseOutside = cross.onRelease;
	}
	
	function drag() {
		reset();
		_x = x0;
		vx = 0;
		graph.clearAll();
		graph.timer();
	}
	
	function noDrag() {
		graph.timer();
	}
/*
	function onPress() {
		this.startDrag(true, 0, 0, Stage.width, Stage.height);
		graph.clearAll();
		graph.timer();
	}
	
	function onRelease() {
		this.stopDrag();
		graph.timer();
	}
	
	function onReleaseOutside() {
		//y = _y;
		onRelease(); //this.stopDrag();
	}
*/
	function replay():Void {
		replaying = !replaying;
		_x = x0;
		vx = 0;
		frame = 0;
		graph.clearAll(); 
		//trace("START");
		graph.zeroHScroll();
		graph.timer();
	}
	
	function x():Number {
		var result:Number;
		//trace("Stepper = " + damping.value);
		if(replaying) {
			if(frame >= track.length) {
				// stop graph
				replaying = false;
				//trace("STOP");
				graph.timer();
			}
			result = track[frame];
			_x = result + x0;
			cross._x = crossTrack[frame]._x;
			cross._y = crossTrack[frame]._y;
			vx = vTrack[frame];
			frame++;
		}
		else {
			vx *= (1-damping.value/100);
			vx += (cross._x-_x)/5;
			_x += vx;
			//trace(cross._x + " " + _x);
			result = _x - x0;
			track.push(result);
			crossTrack.push({_x:cross._x, _y:cross._y});
			vTrack.push(vx);
		}
		//trace("frame = " + frame + "x="+result + " vx = "+vx);
		return result;
	}

	function v():Number {
		//trace("V = "+vx);
		return vx;
	}
}