package {
	
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import caurina.transitions.Tweener;
 
	public class Main extends Sprite {
		
		public function Main() {
			var piece:Rectangle = new Rectangle(0, 0, 800, 600); //ページのサイズ
			var current:Point = new Point(0, 0); //フィールド内のページ位置
			var pivot:Sprite = new Sprite(); //ステージの中心点
			var field:Sprite = new Sprite();
			pivot.addChild(field);
			stage.addChild(pivot);
			setPivot(pivot);
			
			//ステージのスケールを固定で、原点を左上に
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			
			//横15×縦10のページでフィールドを作成
			makeField(new Point(15, 10));
			
			//フィールドを作成
			function makeField(grid:Point):void {
				for (var i:uint = 0; i < grid.y; i++) {
					for (var j:uint = 0; j < grid.x; j++) {
						
						//ページに矩形を描きランダムに彩色
						var shape:Shape = new Shape;
						shape.x = piece.width*j-piece.width/2;
						shape.y = piece.height*i-piece.height/2;
						shape.graphics.beginFill(Math.random()*0x1000000);
						shape.graphics.drawRect(piece.x, piece.y, piece.width, piece.height);
						shape.graphics.endFill();
						field.addChild(shape);
					}
				}
				stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress(grid));
			}
			
			//方向キーでスクロールの設定
			function onKeyPress(grid:Point):Function {
				return function(event:KeyboardEvent):void {
					switch (event.keyCode) {
						case 37: current.x--; break; //左キー
						case 38: current.y--; break; //上キー
						case 39: current.x++; break; //右キー
						case 40: current.y++; break; //下キー
					}
					
					//フィールドの端まで移動したとき
					if (current.x < 0) current.x = 0;
					if (current.x >= grid.x) current.x = grid.x-1;
					if (current.y < 0) current.y = 0;
					if (current.y >= grid.y) current.y = grid.y-1;
					
					Tweener.addTween(field, {time:0.75, x:-piece.width*current.x, y:-piece.height*current.y});
				}
			}
			
			//ステージサイズに合わせて中心点を移動
			function setPivot(pivot:Sprite):void {
				stage.addEventListener(Event.RESIZE, transfield);
				transfield();
				
				function transfield():void {
					Tweener.addTween(pivot, {time:0.75, x:stage.stageWidth/2, y:stage.stageHeight/2});
				}
			}
		}
	}
}