/**
 * @author cashbit
 */
function WorkFlow(name){
	return {
		Name: name,
		TargetReached : false, 
		Targets: [],
		ActualStep : null,
		onStep : null,
		onCannotStep : null,
		canContinue : true ,
		CheckTargetReached : function(){
			var wf = this ;
			for (i=0;i<this.Targets.length;i++){
				var targetitem = this.Targets[i] ;
				if (targetitem.Name == wf.ActualStep.Name){
					wf.TargetReached = true ;
					break ;
				}
			}
		},
		Start : function(EntryPointStep){
			this.canContinue = true ;
			this.ActualStep = EntryPointStep ;
			this.CheckTargetReached() ;
			while (!this.TargetReached && this.canContinue) {
			  this.ActualStep = this.ActualStep.GetNextStep() ;
			  if (this.onStep != null) {
			  	this.ActualStep.isStarted = true ;
			  	this.canContinue = this.onStep();
				if (typeof(this.canContinue) == 'undefined') {
					this.canContinue = true ;
				}
				this.ActualStep.isCompleted = this.canContinue ;
			  } else {
			  	this.canContinue = false ;
			  }
			  
			  this.CheckTargetReached() ;
			} 			
		},
		Step : function(){
			var nextstep = this.ActualStep.GetNextStep() ;
			if (nextstep.ns != null){
				this.ActualStep = nextstep ;
				if (this.onStep != null) {
				  	this.ActualStep.Started(true) ;
				  	this.canContinue = this.onStep();
					if (typeof(this.canContinue) == 'undefined') {
						this.canContinue = true ;
					}
					if (this.ActualStep.Complete){
						this.ActualStep.Complete(this.canContinue) ;
					}
				}				
			} else {
				if (this.onCannotStep != null) {
					this.onCannotStep(this.ActualStep,nextstep.message);
				}
			}	
 		
		},
		GotoStep : function(Step){
			if (Step.active) {
				this.ActualStep = Step ;
				if (this.onStep != null) {
					this.ActualStep.Started(true) ;
				  	this.canContinue = this.onStep();
					if (typeof(this.canContinue) == 'undefined') {
						this.canContinue = true ;
					}
					if (this.ActualStep.Complete){
						this.ActualStep.Complete(this.canContinue) ;
					}
				 }	
			} else {
				if (this.onCannotStep != null) {
					this.onCannotStep(Step,'Step not active');
				}
			}		
		}
	}
}


function WorkFlowStep(stepname){
	return {
		Name: stepname,
		active : true,
		isStarted: false,
		isCompleted: false,
		NextSteps: [],
		onStart: null,
		onCompleted: null,
		Started : function(__started){
			this.isStarted = __started ;
			if (this.onStart != null) this.onStart() ;
		},
		Completed : function(__completed){
			this.isCompleted = __completed ;
			if (this.onCompleted != null) this.onCompleted() ;
		},
		GetNextStep : function(){
			var ns = null ;
			var message = '' ;
			for (i=0;i<this.NextSteps.length;i++){
				var NextStep = this.NextSteps[i] ;
				if (NextStep.condition) {
					ns = NextStep.step ;
					break ;
				} else {
					message = message + NextStep.message + ';' 
				}
			}
			return {
				ns: ns,
				message: message
			} ;
		}
	}
}


