package {
	import flash.display.MovieClip;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	import mochi.as3.*;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	
	/**
	 * ...
	 * @author elmortem
	 */
	public dynamic class Preloader extends MovieClip {
		private var progress_bar : Sprite = new Sprite();
		
		public function Preloader() {
			if (stage) {
				stage.scaleMode = StageScaleMode.NO_SCALE;
				stage.align = StageAlign.TOP_LEFT;
			}
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			
			MochiServices.connect("260ab66a99116dac", root);
			MochiEvents.startPlay();
			
			progress_bar.graphics.beginFill(0x888888);
			progress_bar.graphics.drawRect(0, 0, 800, 400);
			progress_bar.graphics.endFill();
			addChild(progress_bar);			
		}
		
		private function checkFrame(e:Event):void {
			if (currentFrame == totalFrames) {
				stop();
				if (MochiServices.connected) {
					loadingFinished();					
				}
			}
		}
		
		private function progress(e:ProgressEvent):void {
			if (e.bytesTotal != 0){
				progress_bar.x = 800 * e.bytesLoaded / e.bytesTotal;
				if (e.bytesLoaded >= e.bytesTotal){
					progress_bar.visible = false;
					loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
				}
			}
		}
		
		private function loadingFinished():void {
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			
			progress_bar.visible = false;
				
			var mainClass : Class = getDefinitionByName("Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
	}
	
}