package com.sarmatianHeroes 
{
	import flash.events.*;
    import flash.display.*;	
	
	public class Game extends Sprite
	{
		public var inGame:Boolean;
        private static var _instance:Game = null;
		private var _map:Map;
		private var _app:App = App.getInstance();
		var _worldmap:MovieClip;
		var _back_bt:SimpleButton;
		var _level1_bt:SimpleButton;
		var _opened:Array = [1, 0, 0, 0, 0, 0, 0, 0, 0 ];

		public function Game() 
		{
			if (_instance != null)
            {
                throw "Game.as is a singleton class. Use Game.getInstance();";
            }
            _instance = this;
            if (stage)
            {
                init();
            }
            else
            {
                addEventListener(Event.ADDED_TO_STAGE, init);
            }
		}
		
		public function init(event:Event = null) : void
        {
            _worldmap = new worldmap();
			addChild(_worldmap);
			_back_bt = _worldmap.Back_btn;
			_back_bt.addEventListener(MouseEvent.CLICK, this.onBackBtn);
			showOpenedLevels();
			inGame = false;
			
			addEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
			//removeEventListener(Event.ADDED_TO_STAGE, init);
        }
		
		function showOpenedLevels():void
		{
			var _nameB:String;
			var _numB:int;
			var arrL:int = _opened.length;
			for(var i:int = 0; i < arrL; i++)
			{
				_numB = i+1;
				_nameB = "Level"+_numB.toString();
				var tempBt:SimpleButton;
				var newBt:SimpleButton;
				tempBt = _worldmap[_nameB] as SimpleButton;
				if(_opened[i] == 1)
				{
					newBt = new Go_btn;
					newBt.x = tempBt.x;
					newBt.y = tempBt.y;
					newBt.name = _nameB;
					_worldmap.removeChild(tempBt);
					_worldmap.addChild(newBt);
					newBt.addEventListener(MouseEvent.CLICK, this.onLevelBtn);
				}
				else
				{
					tempBt.enabled = false;
				}
			}
		}
		
		function onBackBtn(event:MouseEvent) : void
		{
			removeChild(_worldmap);
			//_back_bt.removeEventListener(MouseEvent.CLICK, this.onBackBtn);
			removeEventListener(Event.ENTER_FRAME, this.enterFrameHandler);
			_worldmap = null;
			parent.removeChild(this);
			_app.init();
		}
		
		function onLevelBtn(event:MouseEvent) : void
		{
			removeChild(_worldmap);
			_back_bt.removeEventListener(MouseEvent.CLICK, this.onBackBtn);
			_worldmap = null;
			_map = Map.getInstance();
			_map.currentLevel = event.target.name;
			addChild(_map);
			trace("load ",_map.currentLevel);
		}
		
        private function enterFrameHandler(event:Event) : void
        {
			if (inGame)
			{
				_map.process();
			}
        }// end function

		
        public static function getInstance() : Game
        {
            return _instance == null ? (new Game) : (_instance);
        }
		

	}
	
}
