
if (Object.isUndefined(CodeCompany)) { var CodeCompany = {}; }

CodeCompany.FunctionChain = Class.create({

	log: function(str) {
		if (!Object.isUndefined(site)) { site.log('FunctionChain['+this.name+']: '+str); }
	},

	initialize: function(name,options) {
		this.options = Object.extend({
			defaultPriority:	50
		},options || {});
		this.name = name;
		this._chain = [];
		this.executed = false;
	},
	
	addFunction: function(fn,name,priority) {
		if (this.executed) {
			this.log('Error: addFunction() after chain execution!');
			return false;
		}
		if (undefined===name) {
			name = 'Function #'+this._chain.length;
		}
		if (undefined===priority) {
			priority = this.options.defaultPriority;
		}
		this._chain.push({
			'fn':		fn,
			'name':		name,
			'priority':	priority
		});
	},
	
	executeChain: function() {
		var i=0;
		this.log('Begins');
		this._chain.sortBy(function(item){ return item.priority; }).each((function(item) {
			var identity = item.name+' (Priority '+item.priority+') ';
			var ok = true;
			try {
				item.fn();
			}
			catch (ex) {
				this.log(identity+'Failed: '+ex.message);
				ok = false;
			}
			if (ok) {
				this.log(identity+'Successful');
			}
		}).bind(this));
		this.executed = true;
		this.log('Ends');
	},
	
	hasBeenExecuted: function() {
		return this.executed;
	}
});

