package 
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	
	/**
	 * ...
	 * @author beisik
	 */
	public class Preloader extends MovieClip 
	{
		private var progressBar: Vector.<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);
			loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
						
			this.graphics.beginFill(0);
			this.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
			
			progressBar = new Vector.<Sprite>(2);
			progressBar[0] = new Sprite();
			progressBar[0].graphics.beginFill(0xFFFFFF);
			progressBar[0].graphics.drawRect(0, 0, stage.stageWidth, 30);
			progressBar[0].graphics.endFill();
			progressBar[0].width = 0;
			progressBar[0].x = 50;
			progressBar[0].y = (stage.stageHeight - 30) / 2;
			
			progressBar[1] = new Sprite();
			progressBar[1].graphics.lineStyle(4, 0xFFFFFF);
			progressBar[1].graphics.drawRect(50, (stage.stageHeight - 30) / 2, stage.stageWidth - 100, 30);
			progressBar[1].graphics.endFill();
			
			addChild(progressBar[0]);
			addChild(progressBar[1]);
		}
		
		private function ioError(e:IOErrorEvent):void 
		{
			trace(e.text);
		}
		
		private function progress(e:ProgressEvent):void 
		{
			if (e.bytesTotal != 0)
				progressBar[0].width = (stage.stageWidth - 100) * e.bytesLoaded / e.bytesTotal;
		}
		
		private function checkFrame(e:Event):void 
		{
			if (currentFrame == totalFrames) 
			{
				stop();
				loadingFinished();
			}
		}
		
		private function loadingFinished():void 
		{
			removeEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			
			progressBar[0].visible = false;
			progressBar[1].visible = false;
			progressBar.shift();
			progressBar.shift();
			progressBar = null;
			
			startup();
		}
		
		private function startup():void 
		{
			var mainClass:Class = getDefinitionByName("Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
		
	}
	
}