(function() {
    var window = this, undefined, jsx = window.jsx;
    jsx.Process = function(action, options) {
        this.action = action;
        this.refresh = 0;
        this._intervalID;
        
        this._execList = [];
        this._currentAction;
        this._test;
        this._execIndex = 0;
        
        this._sleepStartTime = 0;
        this._sleepTime = 0;
    };
    window.$Process = function(action) {
    	return new jsx.Process(action);
    };
    jsx.Process.prototype.run = function() {
        var self = this;
        setTimeout(function() {
            self._execIndex = 0;
            /*self._execList = [];*/
            if (typeof self.action === "function") {
            	self.action.call(self);
            }
            executeAction(self);
        }, 1);
    };
    jsx.Process.prototype.sleep = function(action, millis) {
        this._execList.push({action:action, sleep:millis});
        return this;
    };
    jsx.Process.prototype.wake = function() {
        clearTimeout(this._intervalID);
        executeAction(this);
    };
    jsx.Process.prototype.yield = function(action) {
        return this.sleep(action, 1);
    };
    jsx.Process.prototype.while = function(test, action) {
        this._execList.push({action:action, test:test, sleep:1});
    	return this;
    };
    function executeAction(self) 
    {
        var action, actionObject;
        if (self._currentAction) {
            self._currentAction.call(self);
            if (!self._test) {
            	self._currentAction = null;
            } else {
				if (self._test()) {
					executeAction(self);
				} else {
					self._test = null;
					self._currentAction = null;
				}

            }
        }
        if (!self._test) {
			if (!self._execList.length <= 0) {
				actionObject = self._execList.splice(0,1)[0];
				self._currentAction = actionObject.action;
				
				if (actionObject.test) {
					self._test = actionObject.test;
					self._intervalID = setTimeout(function() {
						if (self._test()) {
							self._currentAction.call(self);
							executeAction(self);
						} else {
							self._test = null;
							self._currentAction = null;
						}
					}, actionObject.sleep);
				} else {
					self._intervalID = setTimeout(function() {
						self._currentAction.call(self);
						self._currentAction = null;
						executeAction(self);
					}, actionObject.sleep);
				}
			}
		}
    }
})();