module jg {
	/*
	Copyright (c) Ubiquitous Entertainment Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
	*/
	export class ParallelAction extends Action {
		actions: Action[];
		endedActions: Action[];

		constructor(param?:any) {
			super(param);
			this.actions = new Action[];
			this.endedActions = new Action[];

			this.action_start = new Trigger();
			this.action_start.handle(this, this.parallelActionStart);
		}

		//override
		addedToTimeline(p:ActionEventArgs) {
			super.addedToTimeline(p);
	        for (var i = 0, len = this.actions.length; i < len; i++) {
	            this.actions[i].added_to_timeline.fire(p);
	        }
		}

		//override
		removedFromTimeline() {
			super.removedFromTimeline();

			this.actions = this.endedActions;
			this.endedActions = [];
		}

		//override
		actionTick(evt:ActionTickEventArgs) {
			super.actionTick(evt);

			var self = this;
			var i, len, timeline = {
				next: function(remaining:number) {
					var action = self.actions[i];
					self.actions.splice(i--, 1);
					len = self.actions.length;
					self.endedActions.push(action);

					if (action.action_end)
						action.action_end.fire({timeline: this});

					action.removed_from_timeline.fire({timeline: this});
				}
			};

			var e =  {
				timeline: timeline,
				elapsed: evt.elapsed
			}
			for (i = 0, len = this.actions.length; i < len; i++) {
				this.actions[i].action_tick.fire(e);
			}

			if (this.actions.length === 0) {
				evt.timeline.next(1);
			}
		}

		parallelActionStart(e:any) {
			for (var i = 0, len = this.actions.length; i < len; i++) {
				if (this.actions[i].action_start)
					this.actions[i].action_start.fire(e);
			}
		}
	}
}