var Task = ( function ( ) {

	var call = function ( context, fn ) {
		if ( typeof fn != "function" ) return undefined;
		var args = Array.prototype.slice.call ( arguments, 2 );
		return fn.call ( context, args );
	}

	var $class = function ( md ) {
		this._metadata = md;
		Events.init ( this );
	}

	$class.prototype.extend = function ( model ) {
		for ( var item in model ) {
			if ( typeof model[item] == "function" ) {
				( function ( fn ) {
					Events.subscribe ( this, item, function ( ) {
						var args = Array.prototype.slice.call ( arguments, 0 );
						var cb = args.pop();
						fn ( cb );
						return true;
					} );
				} ).call ( this, model[item] );
			}
		}
	}

	$class.prototype.setup = function ( autoStart ) {
		if ( !this._settingup && !this._setup ) {
			this._settingup = true;
			Events.fire ( this, "setup", function ( ) {
				this._settingup = false;
				this._setup = true;
				Events.fire ( this, "loaded" );
				if ( autoStart )
					this.start();
			} );
		} else if ( this._setup ) {
			if ( autoStart ) this.start();
		}
	}

	$class.prototype.start = function ( ) {
		var task = this;
		API.smokescreen.task.start ( Mission.get("index"), this._metadata.index, function ( ) {
			Events.fire ( task, "start", function ( ) {
				this.end();
			} );
		} );
	}

	$class.prototype.end = function ( ) {
		var task = this;
		API.smokescreen.task.end ( Mission.get("index"), this._metadata.index, function ( ) {
			task._metadata.completed = true;
			Events.fire ( task, "end" );
		} );
	}

	$class.prototype.fail = function ( ) {
		// TO DO: something...
		alert ( "Failed task '" + this._metadata.name + "'" );
	}

	$class.prototype.get = function ( key ) {
		return this._metadata[key];
	}
	$class.prototype.completed = function ( ) {
		return this._metadata.completed !== false;
	}

	$class.prototype.toString = function ( ) {
		return this.get('name') || 'Task ' + this.get('index');
	}

	return $class;

} )();
