package{
	import flash.display.*;
	import flash.geom.*;
  import flash.events.*;
  import flash.net.*;
	import flash.media.*;
  import flash.ui.ContextMenu;
  import flash.ui.ContextMenuItem;
	import flash.ui.Mouse;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	import com.terry.engine.*;
	import gamecontrol.*;
	import config.*;

	public class Main extends Sprite {
  	include "config/inputlogicrender.as";
		include "init.as";
  	include "input.as";
  	include "logic.as";
  	include "render.as";
		
		public function Main():void {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, gameinit);
		}
		
		private function gameinit(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, gameinit);
			var rc_menu:ContextMenu = new ContextMenu();
			var credit:ContextMenuItem = new ContextMenuItem("Visit distractionware.com");
			credit.addEventListener( ContextMenuEvent.MENU_ITEM_SELECT, visit_distractionware );
			rc_menu.hideBuiltInItems();
			rc_menu.customItems.push(credit);
			this.contextMenu = rc_menu;
			
			addEventListener(Event.DEACTIVATE, windowNotActive);
			addEventListener(Event.ACTIVATE, windowActive);
			
			//Input
			key.init(stage);
			mouse.init(stage);
			SoundMixer.soundTransform = new SoundTransform(1);	
			music.init();
			flag.init();
			obj.init();
			game.init();
			map.init();
			astar.init();
			gfx.init();
			textbox.init();
			
			control.init();
			world.init();
			draw.init();
			
			init();
			loadresources();
			
			Mouse.hide();
			
			addChild(gfx.screen);
			
			stage.fullScreenSourceRect = new Rectangle(0, 0, 768, 480);
			
			_timer.addEventListener(TimerEvent.TIMER, mainloop);
			_timer.start();
		}
		
		public function windowNotActive(e:Event):void{ game.infocus = false; }
    public function windowActive(e:Event):void{ game.infocus = true; }
		
		public function visit_distractionware(e:Event):void{
      var distractionware_link:URLRequest = new URLRequest( "http://www.distractionware.com" );
      navigateToURL( distractionware_link, "_blank" );
    }
		
		// Timer information (a shout out to ChevyRay for the implementation)
		public static const TARGET_FPS:Number = 60; // the fixed-FPS we want the game to run at
		private var	_rate:Number = 1000 / TARGET_FPS; // how long (in seconds) each frame is
		private var	_skip:Number = _rate * 10; // this tells us to allow a maximum of 10 frame skips
		private var	_last:Number = -1;
		private var	_current:Number = 0;
		private var	_delta:Number = 0;
		private var	_timer:Timer = new Timer(4);
	}
}