package
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	
	import caurina.transitions.Tweener
	import flash.events.MouseEvent
	
	public class BusinessCard3D_SecondPart extends Sprite
	{
		
		private var businessCard:Sprite
		private var frontHolder:Sprite
		private var backHolder:Sprite
		
		private var frontTexture:Bitmap
		private var backTexture:Bitmap
		
		private var p1:Point
		private var p2:Point
		private var p3:Point
		
		private var p1_:Point = new Point(0,0)
		private var p2_:Point = new Point(100,0)
		private var p3_:Point = new Point(0,100)
		
		private var frontFace:Boolean = true
		
		public function BusinessCard3D_SecondPart()
		{
			getTextures()
			addIntoHolders()
			initCards()
			addEventListener(Event.ENTER_FRAME,render)
			businessCard.addEventListener(MouseEvent.MOUSE_DOWN,onDown)
		}
		
		public function getTextures() {
			frontTexture = new Bitmap(new CardFront(0,0))
			backTexture = new Bitmap(new CardBack(0,0))
		}
		
		public function addIntoHolders() {
			businessCard = new Sprite()
			frontHolder = new Sprite()
			backHolder = new Sprite()
				
			frontHolder.addChild(frontTexture)
			backHolder.addChild(backTexture)
			
			businessCard.addChild(frontHolder)
			businessCard.addChild(backHolder)
			addChild(businessCard)
		}
				
		public function initCards() {
			backHolder.rotationY = 180
				
			frontTexture.x = -frontTexture.width/2
			frontTexture.y = -frontTexture.height/2
				
			backTexture.x = -backTexture.width/2
			backTexture.y = -backTexture.height/2
		}
		
		public function isFrontFacing(displayObject:DisplayObject):Boolean {
			
			p1 = displayObject.localToGlobal(p1_);
			p2 = displayObject.localToGlobal(p2_);
			p3 = displayObject.localToGlobal(p3_);

			return Boolean((p2.x-p1.x)*(p3.y-p1.y) - (p2.y-p1.y)*(p3.x-p1.x) > 0);
		}
		
		public function render(e:Event) {
			businessCard.x = stage.stageWidth/2
			businessCard.y = stage.stageHeight/2
			
			frontHolder.visible = isFrontFacing(frontHolder);
			backHolder.visible = isFrontFacing(backHolder);
		}
		
		public function onDown(e:MouseEvent) {
			if(frontFace) {
				Tweener.addTween(businessCard,{rotationY:180,time:1})
				frontFace = false
			}else{
				Tweener.addTween(businessCard,{rotationY:0,time:1})
				frontFace = true
			}
		}

	}
}