package 
{
	import fl.transitions.Tween;
	import flash.display.MovieClip;
	import flash.geom.ColorTransform;
	import flash.media.Video;
	import flash.text.TextFieldAutoSize;
	import flash.net.navigateToURL;
	import flash.media.SoundChannel;
	import flash.display.BlendMode;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	//include tweener class
	import caurina.transitions.Tweener;

	//include away3d classes
	import away3d.cameras.*;
	import away3d.containers.*;
	import away3d.core.base.*;
	import away3d.events.*;
	import away3d.materials.*;
	import away3d.primitives.Plane;
	import away3d.core.math.Number3D;
	import away3d.events.MouseEvent3D;
	import away3d.core.render.*;

	//include as3d mod classes for bending 
	import com.as3dmod.ModifierStack;
	import com.as3dmod.modifiers.Bend;
	import com.as3dmod.modifiers.Perlin;
	import com.as3dmod.plugins.away3d.LibraryAway3d;
	import com.as3dmod.util.ModConstant;
	import com.as3dmod.util.XMath;

	//include flash classes
	import flash.display.StageAlign;
	import flash.display.StageQuality;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;	
	import flash.net.FileReference;
	import flash.media.Sound;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	import caurina.transitions.Tweener;
	import flash.display.StageDisplayState;
	import flash.net.FileReference;

	// Import Filters
	import flash.filters.*;
	import caurina.transitions.properties.ColorShortcuts;

	
	// Import Tweener propertie shortcuts
	import caurina.transitions.properties.FilterShortcuts;

	import caurina.transitions.properties.TextShortcuts;
	

	public class PageFlip extends Sprite
	
	{
		//engine variables
		private var scene:Scene3D;
		private var view:View3D; 

		//camera variables
		private var myCamera:HoverCamera3D;
		private var cameraTarget:Object3D;
		private var lastPanAngle:Number;
		private var lastTiltAngle:Number;
		private var lastMouseX:Number;
		private var lastMouseY:Number;
		private var moveCameraTarget:Boolean;

		//pages varables
		private var pageRight:Boolean;
		private var turnPage:Boolean = false;
		private var holdingPage:Boolean = false;
		private var gotoLeft:Boolean = false;
		private var gotoRight:Boolean = false;
		private var sheet:Plane;
		private var sheetList:Vector.<Plane> = new Vector.<Plane>;
		private var thumbList:Vector.<String> = new Vector.<String>;
		private var pageList:Vector.<String> = new Vector.<String>;
		private var typeList:Vector.<String> = new Vector.<String>;
		private var turnSquares:Vector.<Plane> = new Vector.<Plane>;
		
		private var materialList:Array = new Array();
		private var totalPages:Number;
		private var page:Number;
		private var loaded:Boolean = false;
		private var currentPage:Number;
		private var lastPage:Boolean = false;

		private var animating:Boolean = false;
		private var turn:Boolean = false;
		private var i:Number;

		//bending variables
		private var stack:ModifierStack;
		private var stackList:Vector.<ModifierStack> = new Vector.<ModifierStack>;
		private var paperMod:Bend;
		private var paperModList:Vector.<Bend> = new Vector.<Bend>;
		private var paperMod2:Bend;
		private var paperModList2:Vector.<Bend> = new Vector.<Bend>;

		//perlin
		private var perlin:Perlin;
		private var perlinList:Vector.<Perlin> = new Vector.<Perlin>;
		//var paperMod2:Bend;
		//var paperModList2:Array = new Array();

		//preloader text
		private var myTextField:TextField;

		//xml file
		private var settings_xml:XML;
		
		private var pagesXML:String ;
		private var settingsXML:String ;

		//settings variables
		private var page_width:Number;
		private var page_height:Number;
		private var thumb_width:Number;
		private var thumb_height:Number;
		private var thumb_spacing:Number;
		private var freecam:Boolean;
		private var cam_tilt_angle:Number;
		private var cam_pan_angle:Number;
		private var cam_zoom:Number;
		private var cam_focus:Number;
		private var cam_distance:Number;
		private var paper_thickness:Number;
		private var turning_speed:Number;
		private var free_cam:Number;
		private var oldStageHeight:Number;
		private var zoomResizeFactor:Number;
		private var mousewheel_zoom_normal:Number;
		private var mousewheel_zoom_fullscreen:Number;
		private var speed:Number = 0.7;
		private var newPanAngle:Number;
		private var newTiltAngle:Number;
		private var newForce:Number;
		private var bound:Number;
		private var coef:Number;
		private var newRot:Number;
		//flip sounds
		private var flip_sound_on:String;
		private var flipSound:Sound = new Sound();
		private var flipSound2:Sound = new Sound();
		private var sc2:SoundChannel = new SoundChannel();
		private var flipSoundLoaded:Boolean = false;
		private var flipSoundLoaded2:Boolean = false;
		private var page_flip_sound:String;
		private var page_flip_sound2:String;

		private var message1:String;
		private var message2:String;
		private var message3:String;
		private var message4:String;
		private var message5:String;
		private var message6:String;
		private var message7:String;

		private var isPlaying2:Boolean = false;

		private var leftPage:Number = 0;
		private var rightPage:Number = 1;

		private var cameraSpeed:Number = 0.03;

		private var t1:Number;
		private var t2:Number;
		private var t3:Number;

		private var loadingCounter:Number = 0;
		private var pagesCounter:Number = 0;

		private var page1:BitmapFileMaterial;
		private var page2:BitmapFileMaterial;

		private var txt:Text;
		private var loadedAllPages:Boolean = false;
		//autorotation
		//private var autoflip:Boolean;
		//private var autoflipTime:Number;
		//private var flipTimer:Timer;
		
		private var preloaderMaterial:MovieMaterial;
		private var thumbText:Text;
		
		//material holders
		private var bfm:TransformBitmapMaterial;
		private var mm:MovieMaterial;
		
		//sliders
		private var movingSliders:Boolean = false;
		private var movingZoomSlider:Boolean = false;
		private var movingPanSlider:Boolean = false;
		private var movingTiltSlider:Boolean = false;
		
		private var tp:Tooltip = new Tooltip();
		private var tp2:TooltipBottom = new TooltipBottom();

		private var contentContainer:Sprite = new Sprite();
		
		private var pageAbout:AboutPage;
		private var pageContact:ContactPage;
		private var activePage:String;

		private var myBlur:BlurFilter = new BlurFilter();
		private var tweenTime:Number = 0.6;
		private var myLoader:Loader = new Loader();

		//loader 
		private var urlLoader:URLLoader = new URLLoader();
		//xml variables
		private var song_path:String;
		private var pdf_url:String;
		private var music_autoplay:String;
		private var bg_color:Number;
		private var bg_image:String;
		private var bg_image_path:String;
		private var icon_color:Number;
		private var icon_bg_color:Number;
		private var aboutOn:String;
		private var contactOn:String;
		private var pdfOn:String;
		private var zoomOn:String;
		private var panOn:String;
		private var tiltOn:String;
		private var speedOn:String;
		private var thicknessOn:String;
		private var thumbOn:String;
		//private var interactOn:String;
		private var musicOn:String;
		private var settingsLoaded:Boolean = false;
		private var text1:String;
		private var text2:String;
		private var text3:String;
		private var text4:String;
		private var text5:String;
		private var text6:String;
		private var text7:String;
		private var text8:String;
		private var text9:String;
		private var text10:String;
		private var text11:String;
		private var text12:String;
		private var text13:String;
		private var text14:String;
		private var text15:String;
		private var text16:String;
		private var text17:String;
		private var text18:String;
		
		private var now:int = 0;
		private var focusInPageNumber:Boolean = false;
		private var goingToPage:Boolean = false;
		private var targetPage:Number;
		
		private var song:Sound;
		private var sc:SoundChannel;
		private var isPlaying:Boolean = false;
		private var timer:Timer;
		
		private var xPos:Number = 0;
		private var yPos:Number = 0;
		private var container:Sprite = new Sprite();
		private var movingUp:Boolean = false;
		private var movingDown:Boolean = false;
		private var thumbsOn:Boolean = false;
		
		//position buttons

		private var btnPosX:Number;		
		private var tp2On:Boolean  = false;
		//private var interactWithPages:Boolean = false;
		private	var thumbCounter:Number = 0;
		private var _loaderArray : Array = [];
		private var sceneRotation:int = 0;
		
		public function PageFlip():void
		{
			//hide sliders 
			zoom.visible = false;
			pan.visible = false;
			tilt.visible = false;
			thicknessSlider.visible = false;
			speedSlider.visible = false;
			btnPosX = - stage.stageWidth / 2;
			addChild(contentContainer);
			addChild(container);
			container.x = 0;
			container.y = -thumb_height;
			container.buttonMode = true;
			container.useHandCursor = true;
			init();
		}
		
		private function init():void
		{
			//stage setup
			stage.quality = StageQuality.MEDIUM;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.stageFocusRect = false;
			// *** Very Importaint *** : Initialize shortcuts
			FilterShortcuts.init();
			TextShortcuts.init();
			ColorShortcuts.init();
			//flashvars
			if (this.root.loaderInfo.parameters.settings != null && this.root.loaderInfo.parameters.pages != null)
			{
				var flashVars = this.root.loaderInfo.parameters;
				settingsXML = flashVars.settings;
				pagesXML = flashVars.pages;
			}
			else 
			{
				settingsXML = "settings.xml";
				pagesXML = "pages.xml";
			}
			//load settings.xml
			var xml_loader:URLLoader = new URLLoader();
			xml_loader.load( new URLRequest (settingsXML));
			xml_loader.addEventListener(Event.COMPLETE, loadSettings);
			oldStageHeight = stage.stageHeight;
			zoomResizeFactor = oldStageHeight / 600;
			sc = new SoundChannel();
								//auto hide slider 

			//counter
			timer = new Timer(1000);
			initListeners();
		}

		//init listeners for camera control and mouse events
		private function initListeners():void 
		{
			stage.addEventListener(Event.RESIZE, onResize);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, MouseDown);
			stage.addEventListener(MouseEvent.MOUSE_UP, MouseUp);
			stage.addEventListener(MouseEvent.MOUSE_UP, animate);
			stage.addEventListener(MouseEvent.MOUSE_WHEEL, ZoomIn);
			navBar.nextBtn.addEventListener(MouseEvent.CLICK, nextPage);
			navBar.prevBtn.addEventListener(MouseEvent.CLICK, previousPage);
			navBar.lastBtn.addEventListener(MouseEvent.CLICK, gotoLastPage);
			navBar.firstBtn.addEventListener(MouseEvent.CLICK, gotoFirstPage);
			navBar.addEventListener(Event.ENTER_FRAME, onFrame2);
			navBar.aboutBtn.addEventListener(MouseEvent.CLICK, buttonClick);
			navBar.aboutBtn.page = "aboutPage";
			navBar.contactBtn..addEventListener(MouseEvent.CLICK, buttonClick);
			navBar.contactBtn.page = "contactPage";
			navBar.pdfBtn..addEventListener(MouseEvent.CLICK, callLink);
			navBar.visible = false;
			navBar.pageNumber.addEventListener(FocusEvent.FOCUS_IN, focusInPageNum);
			navBar.pageNumber.addEventListener(FocusEvent.FOCUS_OUT, focusOutPageNum);

			zoom.addEventListener(MouseEvent.ROLL_OUT, out1);
			pan.addEventListener(MouseEvent.ROLL_OUT, out1);
			tilt.addEventListener(MouseEvent.ROLL_OUT, out1);
			speedSlider.addEventListener(MouseEvent.ROLL_OUT, out1);
			thicknessSlider.addEventListener(MouseEvent.ROLL_OUT, out1);

			zoom.addEventListener(MouseEvent.MOUSE_DOWN, click1);
			pan.addEventListener(MouseEvent.MOUSE_DOWN, click1);
			tilt.addEventListener(MouseEvent.MOUSE_DOWN, click1);
			speedSlider.addEventListener(MouseEvent.MOUSE_DOWN, click1);
			thicknessSlider.addEventListener(MouseEvent.MOUSE_DOWN, click1);
			timer.addEventListener(TimerEvent.TIMER, onTimer);

			stage.addEventListener(Event.ENTER_FRAME, bringUpThumbs);

			navBar.thumbBtn.addEventListener(MouseEvent.CLICK, thumbBtnClick);
			//navBar.interactBtn.addEventListener(MouseEvent.CLICK, interactBtnClick);
			//=============Fullscreen===================
			navBar.fullscreenBtn.addEventListener(MouseEvent.CLICK, onFSClick);

			
		}
		
		//private function toggleAutoflip(e:MouseEvent = null):void 
		//{
			//if (autoflip)
			//{
				//autoflip = false;
				//navBar.autoflipBtn.icon.play_mc.visible = true;
				//navBar.autoflipBtn.icon.pause_mc.visible = false;
				//if (e)
					//showInfoText(message7);
			//}
			//else
			//{
				//autoflip = true;
				//navBar.autoflipBtn.icon.play_mc.visible = false;
				//navBar.autoflipBtn.icon.pause_mc.visible = true;
				//if (e)
					//showInfoText(message6);
			//}
			//
		//}

		//load settings variables from settings.xml
		private function loadSettings(e:Event):void
		{
			settings_xml = new XML(e.target.data);
			
			freecam = settings_xml.freecam;
			cam_tilt_angle = settings_xml.cam_tilt_angle;
			cam_pan_angle = settings_xml.cam_pan_angle;
			cam_zoom = settings_xml.cam_zoom;
			cam_zoom *= zoomResizeFactor;
			cam_focus = settings_xml.cam_focus;
			cam_distance = settings_xml.cam_distance;
			page_width = settings_xml.page_width;
			page_height = settings_xml.page_height;
			thumb_width = settings_xml.thumb_width;
			thumb_height = settings_xml.thumb_height;
			thumb_spacing = settings_xml.thumb_spacing;
			paper_thickness = settings_xml.paper_thickness;
			free_cam = settings_xml.free_cam;
			mousewheel_zoom_normal = settings_xml.mousewheel_zoom_normal;
			mousewheel_zoom_fullscreen = settings_xml.mousewheel_zoom_fullscreen;
			turning_speed = settings_xml.turning_speed;
			page_flip_sound = settings_xml.page_flip_sound.toString();
			page_flip_sound2 = settings_xml.page_flip_sound2.toString();
			//autoflip = settings_xml.autoflip;
			//autoflipTime = settings_xml.autoflipTime;
			thumbOn = settings_xml.thumbOn.toString();
			flip_sound_on = settings_xml.flip_sound_on.toString();
			message1= settings_xml.message1.toString();
			message2= settings_xml.message2.toString();
			message3= settings_xml.message3.toString();
			message4= settings_xml.message4.toString();
			message5 = settings_xml.message5.toString();
			message6 = settings_xml.message6.toString();
			message7 = settings_xml.message7.toString();
			pdf_url =  settings_xml.pdf_url.toString();
			
			song_path = settings_xml.song_path.toString();
			music_autoplay = settings_xml.music_autoplay.toString();
			bg_color = settings_xml.bg_color;
			icon_color = settings_xml.icon_color;
			icon_bg_color = settings_xml.icon_bg_color;
			bg_image = settings_xml.bg_image.toString();
			bg_image_path = settings_xml.bg_image_path.toString();
			
			aboutOn = settings_xml.about.toString();
			contactOn = settings_xml.contact.toString();
			pdfOn = settings_xml.pdf.toString();
			zoomOn = settings_xml.zoom.toString();
			panOn = settings_xml.pan.toString();
			tiltOn = settings_xml.tilt.toString();
			speedOn = settings_xml.speed.toString();
			thicknessOn = settings_xml.thickness.toString();
			thumbOn =settings_xml.thumbs.toString();
			//interactOn = settings_xml.interact.toString();
			musicOn = settings_xml.music.toString();
			sceneRotation = settings_xml.rotation;
			text1 = settings_xml.text1.toString();
			text2 = settings_xml.text2.toString();
			text3 = settings_xml.text3.toString();
			text4 = settings_xml.text4.toString();
			text5 = settings_xml.text5.toString();
			text6 = settings_xml.text6.toString();
			text7 = settings_xml.text7.toString();
			text8 = settings_xml.text8.toString();
			text9 = settings_xml.text9.toString();
			text10 = settings_xml.text10.toString();
			text11 = settings_xml.text11.toString();
			text12 = settings_xml.text12.toString();
			text13 = settings_xml.text13.toString();
			text14 = settings_xml.text14.toString();
			text15 = settings_xml.text15.toString();
			text16 = settings_xml.text16.toString();
			text17 = settings_xml.text17.toString();
			text18 = settings_xml.text18.toString();
			settingsLoaded = true;
			initColors();
			initButtons();
			//autoflip = !autoflip;
			//toggleAutoflip();
			navBar.visible = true;
			
			initEngine();
		}	

		//Initialise the engine

		private function initEngine():void 
		{
			// create the scene
			scene = new Scene3D();
			scene.roll(sceneRotation);
			// Create and set up the camera
			myCamera = new HoverCamera3D({zoom:0.01, focus:cam_focus, distance:cam_distance});
			myCamera.panAngle = cam_pan_angle;
			myCamera.tiltAngle = -90;
			
			myCamera.hover(true);
			myCamera.yfactor = 1;
			//setup view
			view = new View3D({scene:scene, camera:myCamera });
			addChild(view);
			this.setChildIndex(view, 1);
			Tweener.addTween(myCamera, {tiltAngle:cam_tilt_angle,time:2, transition:"easeInExpo"});
			Tweener.addTween(myCamera, {zoom:cam_zoom,time:3, transition:"easeInExpo"});
				
			view.mouseZeroMove=true; 
			
			view.x = stage.stageWidth / 2;
			view.y = stage.stageHeight / 2;
			
			//camera target, used for effect of camera following the mouse movement, we move the camera target and then update camera position with mycamera.hoover()
			cameraTarget = new Object3D();
			cameraTarget.x = 0;
			cameraTarget.y  = 0;
			myCamera.target = cameraTarget;
			view.scene.addChild(cameraTarget);
			
			//loading pages.xml which contains paths to page images
			var xmlLoader:URLLoader = new URLLoader();
			xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
			xmlLoader.load(new URLRequest(pagesXML));
			
			//flip sounds
			if (flip_sound_on == "true")
			{
				flipSound.load(new URLRequest(page_flip_sound));
				flipSound.addEventListener(Event.COMPLETE, soundLoaded1);
				flipSound2.load(new URLRequest(page_flip_sound2));
				flipSound2.addEventListener(Event.COMPLETE, soundLoaded2);
			}
			setupSliders();
		}
		//flip sounds loaded
		private function soundLoaded1(e:Event) 
		{
			flipSoundLoaded = true;
		}
		private function soundLoaded2(e:Event) 
		{
			flipSoundLoaded2 = true;
		}


		//create an array of path strings to page images
		private function LoadXML(e:Event):void
		{
			//create a new flash.xml.XMLDocument object  
			var xml:XML = new XML(e.target.data);  
			//ignore the white spaces in the file  
			xml.ignoreWhite = true;  
			totalPages = xml.page.length();
			
			for( i = 0; i < totalPages; i++ )
			{
				pageList.push( xml.page[i].fileName.toString());
				thumbList.push( xml.page[i].thumbnail.toString());
				typeList.push( xml.page[i].fileType.toString());
			}
			var loader:Loader = new Loader();
			var req:URLRequest = new URLRequest("preloader.swf"); 
			loader.load(req);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, initObjects); 
		}
		
		//initialise the scene objects
		private function initObjects(e:Event):void
		{
			var mc:MovieClip = new MovieClip();
			mc.addChild(e.target.content);
			
			preloaderMaterial = new MovieMaterial(mc);
			preloaderMaterial.smooth = true;
			
			//create all sheets and load front and back images on them
			
			for (i=0; i< (pageList.length / 2); i++)
			{
				//create sheet as an instance of Plane object with parameters loaded from the settings.xml file, set materials on fron and back side 
				sheet= new Plane({width:page_width, height:page_height, segmentsW:10, segmentsH:3, material:preloaderMaterial, bothsides:true});
				//push it on the sheet array
				sheetList.push(sheet);
				//place it in the scene
				sheetList[i].z = 0;
				sheetList[i].x = 0;
				sheetList[i].rotationY = -180;
				sheetList[i].rotationX = 90;
				//pivot point for the sheet
				sheetList[i].pivotPoint = new Number3D(sheet.width / 2, 0,0);
				//ownCanvas property is enabled for better rendering and z sorting
				sheetList[i].ownCanvas = true;
				
				//set the z offset, used for z sorting
				sheetList[i].screenZOffset = 100 * i;

				//sheetList[i].z = i;
				//add it to the scene
				view.scene.addChild(sheetList[i]);
				//create new modifier stack for the sheet, in which we add modifiers
				stack = new ModifierStack(new LibraryAway3d(), sheetList[i]);
				stackList.push(stack);
				// add bend modifier to the stack of bend modifiers
				paperMod = new Bend(0, 0, 0);
				//paperMod2 = new Bend(0, 0, 0);
				//set constraint for bending so one side of the sheet stays in place
				paperMod.constraint = ModConstant.LEFT;
				if (page_width > page_height)
					paperMod.switchAxes = true;
				//paperMod2.constraint = ModConstant.LEFT;
				paperModList.push(paperMod);
				//paperModList2.push(paperMod2);
				//add the bend modifier to the its modifer stack 
				stackList[i].addModifier(paperModList[i]);
				//stackList[i].addModifier(paperModList2[i]);
				
				//create perlin
				if (page_width <= page_height)
				{
					perlin = new Perlin(0);
					perlin.setFalloff(1,0);
					perlinList.push(perlin);
					stackList[i].addModifier(perlinList[i]);
				}
			}
			//create page turn squares
			createTurnSquare(page_width * 9 / 10, page_height * 4 / 10);
			createTurnSquare(page_width * 9 / 10, - page_height * 4 / 10);
			createTurnSquare(- page_width * 9 / 10, page_height * 4 / 10);
			createTurnSquare( - page_width * 9 / 10, - page_height * 4 / 10);
			///============ whole page clickable 
			//createTurnSquare(page_width * 1/2, page_height * 1/4);
			//createTurnSquare(page_width * 1/2, - page_height * 1/4);
			//createTurnSquare(- page_width * 1/2, page_height * 1/4);
			//createTurnSquare(- page_width * 1/2, - page_height * 1/4);
			//preloader 
			createPreloaderText();
			//when all sheets are created activate first sheet and set it to right page 
			currentPage = 0;
			activateTurnSquares("right");
			pageRight = true;
			//start rendering on every frame
			//loadBitmaps(loadingCounter);
			loadMaterial(0);
			//calculate tween durations for page turning
			calculateTimes(paper_thickness);
			//autorotate
			//flipTimer = new Timer(autoflipTime * 1000, 1);
			//flipTimer.addEventListener(TimerEvent.TIMER, autoflipTimerHandler);
			//flipTimer.start();
			addEventListener(Event.ENTER_FRAME, render);
			
		}
		
		private function createTurnSquare(xPos:Number, yPos:Number):void 
		{
			var turnSquare:Plane = new Plane({width:page_width / 5, height:page_height / 5, segmentsW:1, segmentsH:1});
			///============ whole page clickable 
			//var turnSquare:Plane = new Plane({width:page_width, height:page_height / 2, segmentsW:1, segmentsH:1});
			turnSquare.ownCanvas = true;
			turnSquare.screenZOffset = -10000;
			turnSquare.x = xPos;
			turnSquare.y = yPos;
			turnSquare.z = -1;	
			turnSquare.rotationX = 90;
			turnSquare.alpha = 0;
			//turnSquare.pivotPoint = new Number3D(-xPos, 0, 0);
			turnSquares.push(turnSquare);

		}
		//add event listeners to turnSquares used for turning pages
		private function activateTurnSquares(str:String):void
		{
			for each(var turnSquare:Plane in turnSquares)
			{
				if ((str == "left" && turnSquare.x < 0) ||  (str == "right" && turnSquare.x > 0))
				{
					turnSquare.addOnMouseDown(pageClick);
					turnSquare.addOnMouseUp(pageClick);
					turnSquare.useHandCursor = true;
					view.scene.addChild(turnSquare);
				}
			}
		}
		
	

		//remove event listeners
		private function deactivateTurnSquares(str:String):void
		{
			trace("deactivate " + str);
			for each(var turnSquare:Plane in turnSquares)
			{
				if ((str == "left" && turnSquare.x < 0) ||  (str == "right" && turnSquare.x > 0))
				{	
					turnSquare.removeOnMouseDown(pageClick);
					turnSquare.removeOnMouseUp(pageClick);
					turnSquare.useHandCursor = false;
					view.scene.removeChild(turnSquare);
				}
			}
		}

		//when the page is clicked, if its not animating or held already, disable camera tilt and pan movement and enable page turning so we can grab it
		function pageClick(event:MouseEvent3D):void
		{
			if (!animating && !holdingPage)
				turn = true;
			//autoflip = false;
				
			moveCameraTarget = false;
		}
		

		private function createPreloaderText():void
		{
			txt = new Text();
			txt.x = stage.stageWidth / 2;
			txt.y = stage.stageHeight / 2;
			addChild(txt);
			txt.txt.autoSize = TextFieldAutoSize.CENTER;
			txt.txt.text = "Loading page 1 / "+(2* sheetList.length);
			txt.bg.width = txt.txt.width + 20 ;
		}

		//load material for sheets
		private function loadMaterial(num:Number):void
		{
				if (typeList[num] == "bitmap")
					loadBitmap(num);
				else if(typeList[num] == "swf")
					loadSwf(num);
		}



		//load bitmap material from file
		private function loadBitmap(num:Number)
		{
			var loader:Loader = new Loader();
			var req:URLRequest = new URLRequest(pageList[num]); 
			loader.load(req);
			//wait to finnish loading material
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedBitmap); 
			
		}

		//load an external swf
		private function loadSwf(num:Number):void
		{
			var loader:Loader = new Loader();
			_loaderArray[num] = loader;
			var req:URLRequest = new URLRequest(pageList[num]); 
			loader.load(req);
			//wait to finnish loading material
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedSwf); 
		}

		//when swf is loaded
		private function loadedSwf(e:Event):void
		{
			var mc:MovieClip = new MovieClip();
			mc.addChild(e.target.content);
			//movieMaterialSprite = new albumPage();
			mc.width = page_width;
			mc.height = page_height;
			mm = new MovieMaterial(mc);
			if (loadingCounter > 0)
			{
				mm.interactive = true;
				mm.autoUpdate = true;
			}
			else 
			{
				mm.interactive = false;
				mm.autoUpdate = false;
			}
			materialList.push(mm);
			
			//if front and back materials are loaded
			if (loadingCounter % 2)
			{
				//front material
				
				materialList[loadingCounter ].smooth = true;
				//materialList[loadingCounter ].interactive = true;
				//materialList[loadingCounter ].autoUpdate = true;
				sheetList[pagesCounter].material = materialList[loadingCounter ];
				//back material
				
				materialList[loadingCounter - 1].smooth = true;
				//materialList[loadingCounter - 1].interactive = true;
				//materialList[loadingCounter - 1].autoUpdate = true;
				materialList[loadingCounter - 1].scaleX = -1;
				//materialList[loadingCounter - 1].repeat = true;
				materialList[loadingCounter - 1].offsetX = page_width;
				sheetList[pagesCounter].back = materialList[loadingCounter - 1];
				
				//go to next sheet
				pagesCounter++;
				
			}
			
			//next material
			loadingCounter++;
			//if not all materials are loaded
			if (pagesCounter < sheetList.length)
			{
				txt.txt.text = "Loading page "+(loadingCounter + 1)+" / "+(2* sheetList.length);
				loadMaterial(loadingCounter);
			}
			//if all materials are loaded remove preloader
			else 
			{
				//this.removeChild(txt);
				//setVisiblePageDown();
				txt.visible = false;
				showInfoText(message1);
				createThumbs();
				loadedAllPages = true;
				initSound();
			}
		}

		private function duplicateImage(original:Bitmap):Bitmap {
					var image:Bitmap = new Bitmap(original.bitmapData.clone());
					return image;
				}
				
		//when bitmap material is loaded
		private function loadedBitmap(e:Event):void
		{
			var loader:Loader = Loader(e.target.loader);
			var image:Bitmap = Bitmap(loader.content);

			var duplicate:Bitmap = duplicateImage(image);
			var bitmapData:BitmapData = duplicate.bitmapData;
			bfm = new TransformBitmapMaterial(bitmapData);
			//push material to stack
			materialList.push(bfm);
			
			//if front and back are loaded apply materials
			if (loadingCounter % 2)
			{
				//front material
				sheetList[pagesCounter].material = materialList[loadingCounter ];
				materialList[loadingCounter ].smooth = true;
				//back material
				sheetList[pagesCounter].back = materialList[loadingCounter - 1];
				materialList[loadingCounter - 1].smooth = true;
				materialList[loadingCounter - 1].scaleX = -1;
				materialList[loadingCounter - 1].repeat = true;
				
				pagesCounter++;
			}
			
			loadingCounter++;
			if (pagesCounter < sheetList.length)
			{
				txt.txt.text = "Loading page "+(loadingCounter + 1)+" / "+(2* sheetList.length);
				loadMaterial(loadingCounter);
			}
			else 
			{
				//this.removeChild(txt);
				txt.visible = false;
				showInfoText(message1);
				createThumbs();
				loadedAllPages = true;
				initSound();
			}
			
		}

		//thumbnails
		function createThumbs():void
		{
			
			if (thumbOn == "true")
			{
				var loader:Loader = new Loader ();

				var req:URLRequest = new URLRequest(thumbList[thumbCounter]); 
				loader.load(req);
				//wait to finnish loading material
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadedThumb); 
			}
		}

		function thumbBtnClick(e:MouseEvent):void
		{
			if (!thumbsOn)
			{
				thumbsOn = true;
				movingDown = true;
				movingUp = false;
				Tweener.addTween(container, {y:0, time:1,  transition:"easeInOutExpo" });
				Tweener.addTween(container, {alpha:1, time:1,  transition:"easeInOutSine" });
				e.target.alpha = 0.6;
				//info text
				showInfoText(message2);
				
			}
			else
			{
				thumbsOn = false;
				movingDown = false;
				movingUp = true;
				Tweener.addTween(container, {y:-thumb_height, time:1,  transition:"easeInOutExpo" });
				Tweener.addTween(container, {alpha:0, time:2,  transition:"easeOutExpo" });
				e.target.alpha = 1;
				//info text
				showInfoText(message3);
			}
		}

		function showInfoText(infoText:String):void
		{
			txt.visible = true;
			txt.alpha = 1;
			txt.txt.text = infoText;
			txt.bg.width = txt.txt.width + 20 ;
			Tweener.addTween(txt, {alpha:0, time:1, delay:3,  transition:"easeInExpo", onComplete:txtVisibleFalse });
		}
		function txtVisibleFalse():void
		{
			txt.visible = false;
			
		}


		//toggle interact with pages and turn pages on interactBtn click
		//function interactBtnClick(e:MouseEvent):void
		//{
//
			//if (!interactWithPages)
			//{
				//if (leftPage > 0)
					//deactivateSheet(leftPage / 2 - 1);
				//if (leftPage < totalPages)
					//deactivateSheet(leftPage / 2);
				//interactWithPages = true;
				//e.target.alpha = 0.6;
				//showInfoText(message4);
				//
			//}
			//else
			//{
				//interactWithPages = false;
				//showInfoText(message5);
				//if (leftPage > 0)
					//activateSheet(leftPage / 2 - 1);
				//if (leftPage < totalPages)
					//activateSheet(leftPage / 2);
				//
				//e.target.alpha = 1;
			//}
			//
		//}


		function bringUpThumbs(e:Event):void 
		{
			if (settingsLoaded )
			{
				if (thumbOn == "true")
				{
					if (mouseY < 30 && !movingDown )
					{
						movingDown = true;
						movingUp = false;
						Tweener.addTween(container, {y:0, time:1,  transition:"easeInOutExpo" });
						Tweener.addTween(container, {alpha:1, time:1,  transition:"easeInOutSine" });
					}
					if (mouseY > thumb_height && !movingUp && !thumbsOn)
					{
						movingDown = false;
						movingUp = true;
						Tweener.addTween(container, {y:-thumb_height, time:1,  transition:"easeInOutExpo" });
						Tweener.addTween(container, {alpha:0, time:2,  transition:"easeOutExpo" });
					}
					if (container.width > stage.stageWidth)
						container.x = - mouseX / stage.stageWidth * (container.width - stage.stageWidth) ;
					else 
						container.x = 0;
				}
			}

		}

		private function loadedThumb(e:Event):void
		{
			var thumb:MovieClip = new MovieClip();
			e.target.content.smoothing = true;
			thumb.addChild(e.target.content);
			thumb.x = xPos;
			thumb.y = yPos;
			thumb.width = thumb_width;
			thumb.height = thumb_height;
			thumb.number = thumbCounter;
			xPos += thumb_width + thumb_spacing;
			thumb.alpha = 0;

			container.addChild(thumb);
			thumb.addEventListener(MouseEvent.CLICK, thumbClick);
			thumb.addEventListener(MouseEvent.ROLL_OVER, thumbOver);
			thumb.addEventListener(MouseEvent.ROLL_OUT, thumbOut);
			Tweener.addTween(thumb, {alpha:0.9, time:1,  transition:"easeOut" });

			thumbCounter++;
			if (thumbCounter < totalPages)
				createThumbs();
		}

		private function thumbClick(e:MouseEvent):void
		{
			targetPage = e.target.number + 1;
			goingToPage = true;
			//paper_thickness = 1;
			gotoPage(targetPage, leftPage);
			
		}
		
		private function thumbOver(e:MouseEvent):void
		{
			var num:Number =  e.target.number + 1;
			Tweener.addTween(e.target, {alpha:1, time:.3, transition:"easeInOutSine"});
			thumbText = new Text();
			thumbText.x = mouseX;
			thumbText.y = mouseY+ 30;
			addChild(thumbText);
			addEventListener(Event.ENTER_FRAME, moveThumbText);
			thumbText.txt.autoSize = TextFieldAutoSize.CENTER;
			thumbText.txt.text = num.toString();
			thumbText.bg.width = thumbText.txt.width + 10;
			
		}
		private function thumbOut(e:MouseEvent):void
		{
			Tweener.addTween(e.target, {alpha:0.8, time:.3, transition:"easeInOutSine"});
			removeEventListener(Event.ENTER_FRAME, moveThumbText);
			removeChild(thumbText);
		}


		//update tooltip position
		private function moveThumbText(e:Event):void
		{
			thumbText.x = mouseX;
			thumbText.y = mouseY + 30;
			
		}


		
		//when mouse button is down read current pan and tilt angles from the camera and current mousex and mousey 
		function MouseDown(event:MouseEvent):void
		{
			lastPanAngle = myCamera.panAngle;
			lastTiltAngle = myCamera.tiltAngle;
			lastMouseX = stage.mouseX;
			lastMouseY = stage.mouseY;
			moveCameraTarget = true;
		}

		//disable camera movement
		function MouseUp(event:MouseEvent):void
		{
			moveCameraTarget= false;
		}

		//calculates camera zoom based on the mouse wheel event
		function ZoomIn(event:MouseEvent):void
		{
			if (   ( myCamera.zoom + event.delta / 20 > 0.7 ) && ( myCamera.zoom + event.delta / 20 < 4.2 )   )
				{
					if (   ( (mousewheel_zoom_normal == 1) && (stage.displayState == StageDisplayState.NORMAL) ) || ( (mousewheel_zoom_fullscreen == 1) && (stage.displayState == StageDisplayState.FULL_SCREEN) )   )   
						myCamera.zoom += (event.delta / 15);
				}
		}



		//enable camera tilt and pan movement
		//function pageOut(event:MouseEvent3D):void
		//{
			//moveCameraTarget = false;
			//autoflip = true;
		//}

		//every sheet is in its own canvas and has its own z offset, and based on which page is currently in front this method calculates the new z offset for each sheet to bring correct sheets in front
 		function correctZOrder()
 		{
			//stage.quality = StageQuality.LOW;
			if (pageRight)
			{
				page = currentPage;
				if (sheetList[page].screenZOffset != -100)
				{
					for (i=0; i< sheetList.length; i++)
					{
						if (i < page)
						{
							sheetList[i].screenZOffset += 100;
						}
						else 
						{
							sheetList[i].screenZOffset -= 100;
						}
					}
					
				}
			}
			else 
			{
				if(lastPage)
				{
					page = currentPage;
					
				}
				else				
				{
					page = currentPage - 1;
					if (sheetList[page].screenZOffset != -100)
					{
						for (i=0; i< sheetList.length; i++)
						{
							if (i <= page)
							{
								sheetList[i].screenZOffset -= 100;
								
							}
							else
							{
								sheetList[i].screenZOffset += 100;
							}
							trace(i, sheetList[i].screenZOffset);
						}
						
					}
					
				}
			}
			//tilts camera slightly and updates it so the new z order can take effect
			myCamera.zoom += 0.000001;
			//updates bend modifier for the current page
			
			for (i=0; i< sheetList.length; i++)
			{
				//trace(sheetList[i].screenZOffset);
				if (sheetList[i].screenZOffset > 100 && loadedAllPages)
				{
					paperModList[i].force = 0;
					paperModList[i].offset = 1;
					sheetList[i].visible = false;
					if (typeList[2 * i] == "swf")
					{
						materialList[2 * i].autoUpdate = false;
						materialList[2 * i].interactive = false;
					}
				if (typeList[2 * i + 1] == "swf")
					{
						materialList[2 * i + 1].autoUpdate = false;
						materialList[2 * i + 1].interactive = false;
					}
				}
				else if (sheetList[i].screenZOffset < 150 && loadedAllPages)
				{
					sheetList[i].visible = true;
					if (typeList[2 * i] == "swf")
					{
						materialList[2 * i].autoUpdate = false;
						materialList[2 * i].interactive = false;
					}
				if (typeList[2 * i + 1] == "swf")
					{
						materialList[2 * i + 1].autoUpdate = false;
						materialList[2 * i + 1].interactive = false;
					}
				}
				else if (sheetList[i].screenZOffset == 0 && loadedAllPages)
				{
					sheetList[i].visible = true;
					paperModList[i].force = 0;
					paperModList[i].offset = 1;
					
				}
				stackList[i].apply();
				myCamera.zoom += 0.000001;
			}
		}

		//	ANIMATE PAGE TURN
		//======================================================================================================

		//times for page turn animatons
 		private function calculateTimes(num:Number):void
 		{
			
			//ROTATION Y time
			t1 = 3 * speed;
			//ANIMATE time
			t2 =  t1  * speed * speed * speed  * speed / Math.sqrt(num);
			//ANIMATE OUT time
			t3 = t1 * (30- 2* num) / 18 * speed ;
			
		}

		//when page is clicked bend it in the opposite direction and rotate it around Y axis
 		private function animate(event:MouseEvent):void 
 		{	
		//if we are holding page (if it has been clicked)it can be animated 
			if(holdingPage)
			{
				if(animating) return;
				animating = true;
				turn = false;
				//target angle for rotation around Y axis
				var targetAngle:Number;
				if (flipSoundLoaded2 )
				{
					//sc.stop();
					sc2 = flipSound2.play();
				}
				//calculating the target angle for the sheet, 0 for turning to the left side or -180 for turning to the right side based on which sheet is clicked
				if (pageRight)
					targetAngle = 0;
				else
					targetAngle = -180;
				//animate page turning, the time is based on paper_thickness variable
				Tweener.addTween(sheetList[page], {rotationY:targetAngle, time:( t1  - Math.abs(1 - Math.abs(paperModList[page].force /4) )) *(0.1 * (Math.abs(Math.abs(targetAngle) - Math.abs(sheetList[page].rotationY)) / 180) + 1.1) ,  transition:"easeOutCubic" });
				//if we're holding the sheet on its original side
				if ((pageRight && (paperModList[page].force > 0)) || (!pageRight && paperModList[page].force < 0))
				
				//animate page bending to the opposite direction, bending force and time are based on the paper_thickness, current force and offset
					Tweener.addTween(paperModList[page], {force: - Math.abs(paperModList[page].force) /  paperModList[page].force * (1 - Math.sqrt(Math.abs(paperModList[page].force)) /3)/ 3 / (paper_thickness / 2) * Math.sqrt(paperModList[page].offset)* (Math.random()/2 + 1)  ,time: t2 , transition:"easeInOutSine", onComplete:animateOut});
				//else if we dragged the sheet already on the other side go to animateOut without bending it 
				else 
				{
					Tweener.addTween(paperModList[page], {force: Math.abs(paperModList[page].force) /  paperModList[page].force * (1 - Math.sqrt(Math.abs(paperModList[page].force)) /3)/ 3  / paper_thickness  * Math.sqrt(paperModList[page].offset)* (Math.random()/2 + 1)  ,time: t2 , transition:"easeInOutSine", onComplete:animateOut});
				}
			}
		}


		//drops down page by removing the bending force slowly
 		private function animateOut():void
 		{
			
			//determine which page needs to be animated
			if (pageRight || lastPage)
			{
				page = currentPage;
			}
			else
			{
				page = currentPage - 1;
			}
			//tween the bending modifier force to 0, tween time is based on the paper_thickness variable
			Tweener.addTween(paperModList[page], {offset:1, time: t3 , transition:"easeInOutSine" });
			Tweener.addTween(paperModList[page], {force:paperModList[page].force / paper_thickness, time: t3 , transition:"easeInOutSine", onComplete:onAnimated});
			if (page_width <= page_height)
				Tweener.addTween(perlinList[page], {force:0, time: t3, transition:"easeOut"});
		}



		//when the sheet is turned, update the currentPage counter based on if it is the first sheet, the last sheet or the middle sheet and if it was left or right
 		private function onAnimated():void 
 		{
			isPlaying2 = false;
			
			paperModList[page].force = 0;
			paperModList[page].offset = 1;
			stackList[page].apply();
			
			turn = false;
			holdingPage = false;
			if (pageRight)
			{
				if (currentPage == 0 && sheetList.length > 1)
				{	
					activateTurnSquares("left");
					currentPage++;
				}
				else if (currentPage < stackList.length - 1)
				{

					currentPage++;
				}
				else
				{
					deactivateTurnSquares("right");
					lastPage = true;
				}
				leftPage +=2;
				rightPage +=2;
			}
			else
			{
				if (currentPage == 1 && sheetList.length > 2) 
				{
					deactivateTurnSquares("left");
					currentPage--;
				}
				else if (!lastPage )
				{

					currentPage--;
				}
				else
				{
					lastPage = false;
					activateTurnSquares("right");
				}
				leftPage -= 2;
				rightPage -=2;
			}
			
			animating = false;
			setVisiblePageDown();		
			//trace("setvisible");
			
			if (leftPage == targetPage || rightPage == targetPage)
			{
				goingToPage = false;
				gotoRight = false;
				gotoLeft = false;
			}
			if (leftPage < totalPages && !animating && gotoRight)
			{
				pageRight = true;
				if (currentPage < stackList.length)
				{
					page = currentPage;
				}
				paperModList[page].force = Math.random() / 5 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				correctZOrder();
				nextPageAnimate();
				
			}
			if (rightPage > 1 && !animating && gotoLeft)
			{
				pageRight = false;
				if (currentPage)
					{
						if (lastPage)
							page = currentPage;
						else
							page = currentPage - 1;
					}
				else page = 0;

				paperModList[page].force = - Math.random() / 10 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				correctZOrder();
				nextPageAnimate();
			}
				
			
			if (leftPage == totalPages)
				gotoRight = false;
			if (rightPage == 1)
				gotoLeft = false;
				
			
		}


		//=====================DRAG PAGE===============================
		
		//when we're holding the sheet it animates bending modifiers, offset, force and angle, to follow mouse movement, so we can bend the sheet in any directoin
 		private function dragPage(mousex:Number, mousey:Number, num:Number):void
 		{
			if(!animating && turn) 
			{
				if (flipSoundLoaded && !isPlaying2)
				{
					isPlaying2 = true;
					sc2 = flipSound.play();
				}
				
				var rotAngle:Number = sheetList[num].rotationY;
				//set holdingPage to true to disable camera tilt and pan
				if(!holdingPage)
				{
					paperModList[num].force = 0;
					holdingPage = true;
					//determine if we're holding left or right sheet
					if (rotAngle > -90)
						pageRight = false;
					else 
						pageRight = true;
					//call correctZOrder to bring the correct sheets in front
					correctZOrder();
				}
				//when we're holding a page, camera doesn't move
				moveCameraTarget = false;
				
				coef = ((mousex - stage.stageWidth / 2 ) / stage.stageWidth * 2);
				
				//FORCE
				
				//calculate new bending force for current mouse x position and the page_bending
				
				newForce = (coef / (paper_thickness * paper_thickness) - paperModList[num].force) / 10 ;
				//set bounds for bending
				if (page_width <= page_height)
					bound = 0.3 + (1 - page_width / page_height);
				else 
					bound = 0.3 + (1 -  page_height / page_width);
				if ( paperModList[num].force + newForce < bound && paperModList[num].force + newForce > - bound)
				
					paperModList[num].force += newForce / 3 /  speed;
					
				//OFFSET
				
				//calculate new offset for bending based on mouse x position
				if (mousex > stage.stageWidth / 2)
					paperModList[num].offset = .2* (mousex - stage.stageWidth / 2) / sheetList[0].width + 0.1;
				else 
					paperModList[num].offset = - .2* (mousex - stage.stageWidth / 2) / sheetList[0].width  + 0.1;
				//calculate new angle for bending based on curent mouse y position
				
				//ANGLE
				
				if (mousey > stage.stageHeight /2)
				{
					paperModList[num].angle = Math.PI / 2  + (mousey - stage.stageHeight / 2) / sheetList[0].height /2 ;
					//paperModList[num].angle = (mousey - stage.stageHeight / 2) / sheetList[0].height /2 ;
					
				}
				else if (mousey < stage.stageHeight /2)
				{
					paperModList[num].angle = Math.PI / 2  - (stage.stageHeight / 2 - mousey ) / sheetList[0].height /2 ;
					//paperModList[num].angle =  (stage.stageHeight / 2 - mousey ) / sheetList[0].height /2 ;
					
				}
				//default bending is rotated for 90 degrees because by default the bend modifier angle is set to bend the plane around shorter axis and we need to bend it aroun longer axis
				else
				{
					paperModList[num].angle = Math.PI / 2;
					//paperModList[num].angle = 0;
					
				}
				//calculate new sheet rotation around y=0 based on current mouse position 
				
				//ROTATION
				newRot = sheetList[num].rotationY + (-180 * (mousex / stage.stageWidth) - sheetList[num].rotationY ) / 3 / Math.sqrt(paper_thickness);
				if (!animating && newRot <= 0 && newRot >= -180)
					sheetList[num].rotationY = newRot;
			
				//PERLIN FORCE
				
				if (page_width <= page_height)
					perlinList[num].force = (2 - Math.sqrt(Math.abs(paperModList[num].force))) / paper_thickness ;
			
			}
			
			//apply new bending parameters by calling modifierStack.apply()
			//paperModList2[num].force = - paperModList[num].force;
			//paperModList2[num].offset = 	paperModList[num].offset;
			//paperModList2[num].angle = - paperModList[num].angle;
			stackList[num].apply();
			/*for (i=0; i <  sheetList.length; i++)
				trace(i, paperModList[i].force);*/
		}


		//on every frame
 		private function render(event:Event):void 
 		{
			// if we're not holding sheet already, determine which sheet has been picked up, left or right
			if(!holdingPage && !animating)
			{
				
				if (mouseX > stage.stageWidth / 2)
				{
					if (currentPage < stackList.length )
						page = currentPage;
				}
				else
				{
					if (currentPage)
					{
						if (lastPage)
							page = currentPage;
						else
							page = currentPage - 1;
					}
					else page = 0;
				
				}
				
			}

			//pass current mouse position and currently active sheet to the dragPage()
			dragPage(mouseX, mouseY, page);
			
			//update camera pan and tilt if the freecam is active
			if(moveCameraTarget && free_cam !=0 && !movingSliders)
			{
				
				newPanAngle = cameraSpeed * (stage.mouseX  - lastMouseX) + lastPanAngle;
				if (newPanAngle < - 160 && newPanAngle > - 200)
					myCamera.panAngle = newPanAngle;
				newTiltAngle = cameraSpeed * (stage.mouseY - lastMouseY) + lastTiltAngle;
				if (newTiltAngle < 45 && newTiltAngle > - 45)
				myCamera.tiltAngle = newTiltAngle;
				myCamera.hover();
			}
			if ((myCamera.zoom * 600 / stage.stageHeight) > 1.2 && !movingSliders)
			{
				
				//camera is following mouse movement by moving the cameraTarget, and the cameraTarget object is set as the target for our camera. It moves slower if camera the zoom is greater
				cameraTarget.x += (sheetList[0].width * (stage.mouseX - stage.stageWidth / 2) / stage.stageWidth / 2 * myCamera.zoom - cameraTarget.x) / 3;
				cameraTarget.y = - (sheetList[0].height * (stage.mouseY - stage.stageHeight / 2) / stage.stageHeight / 2 * myCamera.zoom - cameraTarget.y) / 3;
				myCamera.hover();
			}
			else 
				cameraTarget.x = cameraTarget.y = 0;
			//update camera and render the scene
			
			
			//update slider values and set variables from sliders
			//pan slider
			if (movingPanSlider)
				myCamera.panAngle =  (pan.marker.y / pan.bar.height) * 90 - 135;
			 pan.marker.y =( myCamera.panAngle + 135) / 90 * pan.bar.height;
			 //tilt slider
			if (movingTiltSlider)
				myCamera.tiltAngle = - tilt.marker.y / tilt.bar.height * 90 - 45;
			tilt.marker.y = - (myCamera.tiltAngle + 45) / 90 * tilt.bar.height;
			//speed slider
			if (!gotoLeft && !gotoRight)
				speed = 1.35 + speedSlider.marker.y / speedSlider.bar.height / 3 - 0.66;
			//thickness slider
			if (!goingToPage)
				paper_thickness = - thicknessSlider.marker.y /  thicknessSlider.bar.height * 9 + 1;
			//zoom slider
			if (movingZoomSlider)
				myCamera.zoom = (- zoom.marker.y / zoom.bar.height) * 3.5 + 0.7;
			zoom.marker.y =  - (myCamera.zoom - 0.7) / 3.5 * zoom.bar.height;
			
			if (focusInPageNumber && !goingToPage && navBar.pageNumber.text.text !="")
			{
				
				targetPage = Number(navBar.pageNumber.text.text);
				
			}
			else if (!focusInPageNumber)
				updatePageNumbers();
			
			calculateTimes(paper_thickness);
			myCamera.hover();
			view.render();

		}


		//on resize shift the view to the center of the stage
 		private function onResize(event:Event):void 
 		{
			view.x = stage.stageWidth / 2;
			view.y = stage.stageHeight / 2;
			
			txt.x = stage.stageWidth / 2;
			txt.y = stage.stageHeight / 2;
			
			zoomResizeFactor = stage.stageHeight / oldStageHeight ;
			myCamera.zoom *= zoomResizeFactor;
			oldStageHeight = stage.stageHeight;
		}
		private function setupSliders():void
		{
			// speed slider


			speedSlider.marker.y = - (1.35 - 0.66 - turning_speed) * 3 * speedSlider.bar.height;
			speedSlider.addEventListener(MouseEvent.MOUSE_DOWN, sliderClicked);
			addEventListener(MouseEvent.MOUSE_UP, sliderOut);
			
			// paper thickness slider

			thicknessSlider.marker.y = - ((paper_thickness - 1) / 9 ) * thicknessSlider.bar.height ;
			thicknessSlider.addEventListener(MouseEvent.MOUSE_DOWN, sliderClicked);
			addEventListener(MouseEvent.MOUSE_UP, sliderOut);
			
			// camera zoom slider
			

			zoom.value = .1;
			zoom.addEventListener(MouseEvent.MOUSE_DOWN, sliderClicked);
			zoom.addEventListener(MouseEvent.MOUSE_DOWN, zoomSliderClicked);
			addEventListener(MouseEvent.MOUSE_UP, sliderOut);
			
			//pan slider
			//controlBar.pan.marker.x = .5 * controlBar.pan.bar.width;
			pan.addEventListener(MouseEvent.MOUSE_DOWN, sliderClicked);
			pan.addEventListener(MouseEvent.MOUSE_DOWN, panSliderClicked);
			addEventListener(MouseEvent.MOUSE_UP, sliderOut);
			
			//tilt slider
			
			//controlBar.tilt.marker.x = .5 * controlBar.tilt.bar.width;
			tilt.addEventListener(MouseEvent.MOUSE_DOWN, sliderClicked);
			tilt.addEventListener(MouseEvent.MOUSE_DOWN, tiltSliderClicked);
			addEventListener(MouseEvent.MOUSE_UP, sliderOut);
		}

		//disable free camera while dragging sliders
		private function sliderClicked(e:MouseEvent):void
		{
			movingSliders = true;	
		}

		//disable free camera while dragging sliders
		private function zoomSliderClicked(e:MouseEvent):void
		{
			movingZoomSlider = true;
		}

		private function panSliderClicked(e:MouseEvent):void
		{
			movingPanSlider = true;
		}

		private function tiltSliderClicked(e:MouseEvent):void
		{
			movingTiltSlider = true;
		}

		//enable free camera
		private function sliderOut(e:MouseEvent):void
		{
			movingSliders = false;
			movingZoomSlider = false;
			movingPanSlider = false;
			movingTiltSlider = false;
		}


		private function focusInPageNum(e:FocusEvent):void
		{
			focusInPageNumber = true;
			navBar.pageNumber.text.text =  "";
			this.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);

		}

		private function keyDownHandler(event : KeyboardEvent) : void
		{
			if (event.keyCode == 13)
			{
				goingToPage = true;
				//paper_thickness = 1;
				gotoPage(targetPage, leftPage);
			}
		}
		private function focusOutPageNum(e:FocusEvent):void
		{
			focusInPageNumber = false;
			this.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
		}
 		private function updatePageNumbers():void
 		{
			if (!focusInPageNumber)
			{
				if (rightPage == 1)
				{
					navBar.pageNumber.text.text =  "1 / "+totalPages.toString();
				}
				
				else if (leftPage == totalPages)
				{
					navBar.pageNumber.text.text = leftPage.toString()+ " / "+totalPages.toString();
				}
				else
				{
					navBar.pageNumber.text.text = leftPage.toString()+ " - "+ rightPage..toString()+ " / "+totalPages.toString();
				}
			}
			
		}
 
		private function gotoPage(num:Number, current:Number) : void
		{
			if (num<current && num >=0)
			{
				gotoLeft = true;
				gotoRight = false;
				speed = 0.001;
				if (rightPage > 1 && !animating)
				{
					pageRight = false;
					if (currentPage)
						{
							if (lastPage)
								page = currentPage;
							else
								page = currentPage - 1;
						}
					else page = 0;
					correctZOrder();
					paperModList[page].force = - Math.random() / 10 / paper_thickness;
					paperModList[page].offset = Math.random() / 5 + 0.2;
					paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;
			
					
					nextPageAnimate();
				}
			}
			else if (num>current + 1 && num <=totalPages)
			{
				gotoLeft = false;
				gotoRight = true;
				speed = 0.001;
				if (leftPage < totalPages && !animating)
				{
					pageRight = true;
					if (currentPage < stackList.length)
					{
						page = currentPage;
					}
					correctZOrder();
					paperModList[page].force = Math.random() / 5 / paper_thickness;
					paperModList[page].offset = Math.random() / 5 + 0.2;
					paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;
			
					
					nextPageAnimate();
				}
				
			}
			else goingToPage = false;
		}



		private function gotoLastPage(event:MouseEvent) : void
		{
				targetPage = -1;

			gotoLeft = false;
			gotoRight = true;
			speed = 0.35;
			if (leftPage < totalPages && !animating)
			{
				pageRight = true;
				if (currentPage < stackList.length)
				{
					page = currentPage;
				}
				correctZOrder();
				paperModList[page].force = Math.random() / 5 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				
				nextPageAnimate();
			}
		}
		private function gotoFirstPage(event:MouseEvent) : void
		{
			targetPage = -1;

			gotoLeft = true;
			gotoRight = false;
			speed = 0.35;
			if (rightPage > 1 && !animating)
			{
				pageRight = false;
				if (currentPage)
					{
						if (lastPage)
							page = currentPage;
						else
							page = currentPage - 1;
					}
				else page = 0;
			correctZOrder();
				paperModList[page].force = - Math.random() / 10 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				
				nextPageAnimate();
			}
		}
		//next page 
		private function nextPage(event:MouseEvent = null):void
		{
			gotoLeft = false;
			gotoRight = false;
			if (leftPage < totalPages && !animating)
			{
				pageRight = true;
				if (currentPage < stackList.length)
				{
					page = currentPage;
				}
				correctZOrder();
				paperModList[page].force = Math.random() / 5 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				nextPageAnimate();
			}
			
		}

		//previous page
		private function previousPage(event:MouseEvent) : void
		{
			gotoLeft = false;
			gotoRight = false;
			if (rightPage > 1 && !animating)
			{
				pageRight = false;
				if (currentPage)
					{
						if (lastPage)
							page = currentPage;
						else
							page = currentPage - 1;
					}
				else page = 0;
					correctZOrder();

				paperModList[page].force = - Math.random() / 10 / paper_thickness;
				paperModList[page].offset = Math.random() / 5 + 0.2;
				paperModList[page].angle = Math.PI / 2 + Math.random() / 2 - 0.25;

				nextPageAnimate();
			}
			
		}

		//animate page turn
		private function nextPageAnimate() : void
		{
			if(animating) return;
			animating = true;
			turn = false;
			//target angle for rotation around Y axis
			var targetAngle:Number;
			if (flipSoundLoaded2 )
				{
					//sc.stop();
					sc2 = flipSound2.play();
				}
			//calculating the target angle for the sheet, 0 for turning to the left side or -180 for turning to the right side based on which sheet is clicked
			if (pageRight)
				targetAngle = 0;
			else
				targetAngle = -180;
			calculateTimes(paper_thickness);
			
			//animate page turning, the time is based on paper_thickness variable
			Tweener.addTween(sheetList[page], {rotationY:targetAngle, time:( t1  - Math.abs(1 - Math.abs(paperModList[page].force /4) )) *(0.1 * (Math.abs(Math.abs(targetAngle) - Math.abs(sheetList[page].rotationY)) / 180) + 1.1) ,  transition:"easeOutCubic" });
			//bend the page
			Tweener.addTween(paperModList[page], {force: - Math.abs(paperModList[page].force) /  paperModList[page].force * (1 - Math.sqrt(Math.abs(paperModList[page].force)) /3)/ 2.5 / (paper_thickness / 2) * Math.sqrt(paperModList[page].offset)* (Math.random()/2 + 1)  ,time: t2 , transition:"easeInOutSine", onComplete:animateOut});
			
		}

		//var invisiblePage:WireframeMaterial = new WireframeMaterial();

		private function setVisiblePageDown():void
		{
			if (loadedAllPages)
			{
				if (rightPage == 1)
				{
					//trace("1");
					//sheetList[0].material = preloaderMaterial;
					//sheetList[0].back = materialList[0];
					sheetList[1].visible = false;
					sheetList[2].visible = false;
					for (i=0;i <totalPages ; i++)
					{
						if (typeList[i] == "swf")
						{
							//materialList[0 ].autoUpdate = true;
							if (i == 0)
							{
								materialList[i].autoUpdate = true;
								materialList[i].interactive = true;
							}
							else 
							{
								materialList[i].autoUpdate = false;
								materialList[i].interactive = false;
								stopVideo(_loaderArray[i]);
							}
						}
					}
					
						
				}
				
				else if (leftPage == totalPages)
				{
					//trace("2");
					//sheetList[sheetList.length - 1].material = materialList[sheetList.length - 1];
					//sheetList[0].back = preloaderMaterial;
					sheetList[sheetList.length - 2].visible = false;
					sheetList[sheetList.length - 3].visible = false;
					for (i=0; i < totalPages ; i++)
					{
						//trace(typeList[i], totalPages);
						if (typeList[i] == "swf")
						{
							//materialList[0 ].autoUpdate = true;
							if (i == (totalPages - 1))
							{
								materialList[i].autoUpdate = true;
								materialList[i].interactive = true;
							}
							else 
							{
								materialList[i].autoUpdate = false;
								materialList[i].interactive = false;
								stopVideo(_loaderArray[i]);
							}
						}
					}
					
				}
				else
				{
			
					if (leftPage > 2 )
						sheetList[leftPage / 2 - 2].visible = false;
					if (leftPage > 4 )
					{
						sheetList[leftPage / 2 - 3].visible = false;
					}
					if (rightPage < materialList.length - 2)
						sheetList[leftPage / 2 + 1].visible = false;
					if (rightPage < materialList.length - 4)
					{
						sheetList[leftPage / 2 + 2].visible = false;
					}
						
					for (i=0; i < totalPages ; i++)
					{
						//trace(typeList[i], totalPages, leftPage, rightPage);
						if (typeList[i] == "swf")
						{
							//materialList[0 ].autoUpdate = true;
							if (i == (leftPage - 1) || i == leftPage)
							{
								materialList[i].autoUpdate = true;
								materialList[i].interactive = true;
							}
							else 
							{
								materialList[i].autoUpdate = false;
								materialList[i].autoUpdate = false;
								stopVideo(_loaderArray[i]);
							}
						}
					}
				}
			}
			//stage.quality = StageQuality.MEDIUM;
			myCamera.zoom += 0.000001;
			for (i = 0; i < (totalPages/2)  ; i++)
			{
				trace("sheet "+i+" visible : "+ sheetList[i].visible);
			}
		}
		
		private function stopVideo(ldr:Loader):void 
		{
		
			var mc:MovieClip = MovieClip(ldr.content);
			trace("stop video, mc.numchildren = " + mc.numChildren);
			for (var i:int = 0; i < mc.numChildren; i++)
			{
				trace(mc.getChildAt(i));
				if (mc.getChildAt(i) is Video)
				{
					mc.stopVideo();
				}
			}
		}

		//private function autoflipTimerHandler(e:TimerEvent):void
		//{
			//if (autoflip)
			//{
				//trace("time handler");
				//trace(this.leftPage);
				//if (leftPage != totalPages)
					//nextPage();
				//else gotoPage(1, leftPage);
			//}
			//flipTimer.reset();
			//flipTimer.start();
			//
		//}
		private function buttonClick(e:MouseEvent):void
		{	
			if (e.target.page == "aboutPage" && activePage !=  "aboutPage")
			{
				removeListeners();
				
				loadAbout();
			}
			else if (e.target.page == "contactPage" && activePage !=  "contactPage")
			{
				removeListeners();
				
				loadContact();
			}
		}

		private function loadAbout():void
		{
			removeAllChildren();
			activePage =  "aboutPage";
			pageAbout = new AboutPage();
			contentContainer.addChild(pageAbout);
			pageAbout.closeBtn.addEventListener(MouseEvent.CLICK, closePage);
			slideIn();
		}

		private function loadContact():void
		{
			removeAllChildren();
			activePage =  "contactPage";
			pageContact = new ContactPage();
			contentContainer.addChild(pageContact);
			pageContact.closeBtn.addEventListener(MouseEvent.CLICK, closePage);
			slideIn();
		}

		private function closePage(e:MouseEvent):void
		{

			slideOut();
			
		}

		private function slideIn():void
		{
			removeListeners();
			contentContainer.x = - stage.stageWidth ;
			contentContainer.y = stage.stageHeight /2 - contentContainer.height /2;
			myBlur.blurX = 10;
			myBlur.blurY = 10;
			Tweener.addTween (contentContainer, {_Blur_blurX: 0, _Blur_blurY :0, time:tweenTime , transition:"easeInOutCubic"});
			Tweener.addTween(contentContainer, {x:stage.stageWidth/2 - contentContainer.width /2, time:tweenTime, transition:"easeInOutCubic", onComplete:addListeners});
			free_cam = 0;
		}

		private function slideOut():void
		{
			activePage =  "";
			removeListeners();
			Tweener.addTween (contentContainer, {_Blur_blurX: 10, _Blur_blurY :10, time:tweenTime  , transition:"easeInOutCubic"});
			Tweener.addTween(contentContainer, {x:stage.stageWidth, time:tweenTime , transition:"easeInOutCubic", onComplete:removeAllChildren});
			free_cam = 1;
		}

		private function removeAllChildren():void
		{
			if (contentContainer.numChildren)
			{
				var k:int = contentContainer.numChildren;
				while( k -- )
				{
					contentContainer.removeChildAt( k );
				}
			}
			addListeners();
		}

		private function removeListeners():void
		{
			
			navBar.aboutBtn.removeEventListener(MouseEvent.CLICK, buttonClick);
			navBar.contactBtn.removeEventListener(MouseEvent.CLICK, buttonClick);

		}

		private function addListeners():void
		{
			navBar.aboutBtn.addEventListener(MouseEvent.CLICK, buttonClick);
			navBar.contactBtn.addEventListener(MouseEvent.CLICK, buttonClick);

		}

		private function callLink(e:MouseEvent):void 
		{
			var url:String = pdf_url;
			var request:URLRequest = new URLRequest(url);
			try 
			{
				navigateToURL(request, '_blank');
			} 
			catch (e:Error) 
			{
				trace("Error occurred!");
			}
		}


		private function onFrame(e:Event):void
		{

			bg.scaleX = stage.stageWidth / 1000;
			bg.scaleY = stage.stageHeight / 600;
			bg.x = stage.stageWidth /2;
			bg.y = stage.stageHeight /2;
			
		}

		private function onFrame2(e:Event):void
		{
			//position sliders
			
			zoom.y = pan.y = tilt.y = speedSlider.y = thicknessSlider.y = navBar.y - navBar.height +5;
			btnPosX = - stage.stageWidth / 2;
			if (settingsLoaded)
				positionButtons();
		}
		private function onStageResize(e:Event):void
		{
			bg.scaleX = stage.stageWidth / 1000;
			bg.scaleY = stage.stageHeight / 600;
			bg.x = stage.stageWidth /2;
			bg.y = stage.stageHeight /2;
			
			contentContainer.x=stage.stageWidth/2-contentContainer.width/2;
			contentContainer.y=stage.stageHeight/2-contentContainer.height/2;
			
			//position sliders
			
			zoom.y = pan.y = tilt.y = speedSlider.y = thicknessSlider.y = navBar.y - navBar.height +5;
		}



		//show tooltip
		private function over(e:MouseEvent):void
		{
			tp.x = mouseX;
			tp.y = mouseY + 30;
			tp.tooltipText.text = e.target.message;
			tp.tooltipText.selectable = false;
			tp.tooltipText.autoSize = TextFieldAutoSize.CENTER;
			tp.tooltipBg.width = tp.tooltipText.width + 10;
			
			tp.alpha = 0;
			if (!tpOn)
			{
				this.addChild(tp);
				tpOn = true;
			}
			Tweener.addTween (tp, {alpha: 1, time:0.2 , transition:"easeInSine"});
			addEventListener(Event.ENTER_FRAME, moveTooltip)
		}
		var tpOn:Boolean = false;
		//hide tooltip

		private function out(e:MouseEvent):void
		{
			removeEventListener(Event.ENTER_FRAME, moveTooltip)

			Tweener.addTween (tp, {alpha: 0, time:1 , transition:"easeInOutCubic", onComplete:removeToolTip1});
		}

		private function removeToolTip1():void
		{
				this.removeChild(tp);
				tpOn = false;
		}

		//move tooltip 
		private function moveTooltip(e:Event):void
		{
			tp.x = mouseX;
			tp.y = mouseY + 30;
			
		}

		//===================================================================================

		//Music player

		//===================================================================================
		private function initSound()
		{
			song = new Sound();
			song.load(new URLRequest(song_path));
			//song.addEventListener(Event.COMPLETE, soundLoaded);
			//song.addEventListener(ProgressEvent.START, soundLoading);
			soundLoading();
		}

		


		private function onFSClick(e:MouseEvent):void
		{
			if (stage.displayState == StageDisplayState.FULL_SCREEN) 
			{
				
				stage.displayState = StageDisplayState.NORMAL;

			}
			else 
			{
				stage.displayState = StageDisplayState.FULL_SCREEN;

			}
			
		}

		 
		//when sound is loaded enable click on the music icon 
		private function soundLoading() 
		{
			if (music_autoplay == "true")
			{
				isPlaying = true;
				sc = song.play(0,9999);
				navBar.musicPlayer.icon.musicOn.visible = true;
			}
			else
				navBar.musicPlayer.icon.musicOn.visible = false;
				
			navBar.musicPlayer.addEventListener(MouseEvent.CLICK, togglePlay);
		}

		//if it is not playing then play, else stop playing the mp3 file
		private function togglePlay(e:MouseEvent):void
		{
			if(!isPlaying)
			{
				sc = song.play();
				isPlaying = true;
						navBar.musicPlayer.icon.musicOn.visible = true;

			}
			else
			{
				sc.stop();
				isPlaying = false;
						navBar.musicPlayer.icon.musicOn.visible = false;

			}
			
		}


		//==================================================================================

		//Navigation  bar tooltip actions

		//==================================================================================

		private function initColors():void
		{
			//colors for icons and icon backgrounds
			if (bg_image == "false")
			{
				var bgTransform = new ColorTransform();
				bgTransform.color = bg_color;
				bg.transform.colorTransform = bgTransform;
				bg.addEventListener(Event.ENTER_FRAME, onFrame)
				stage.addEventListener(Event.RESIZE, onStageResize);

			}
			else 
			{
				var myUrl:String = bg_image_path;
				myLoader.load(new URLRequest(myUrl));
				myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onBgImageLoaded);
			}
			var iconColorTransform = new ColorTransform();
			iconColorTransform.color = icon_color;
			var iconBgColorTransform = new ColorTransform();
			iconBgColorTransform.color = icon_bg_color;
			
			//apply colors
			
			
			navBar.aboutBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.aboutBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.contactBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.contactBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.pdfBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.pdfBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.zoomBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.zoomBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.panBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.panBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.tiltBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.tiltBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.speedBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.speedBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.thicknessBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.thicknessBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.thumbBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.thumbBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			//navBar.interactBtn.icon.transform.colorTransform = iconColorTransform;
			//navBar.interactBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.prevBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.prevBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.nextBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.nextBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			//navBar.autoflipBtn.icon.transform.colorTransform = iconColorTransform;
			//navBar.autoflipBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.firstBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.firstBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.lastBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.lastBtn.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.musicPlayer.icon.transform.colorTransform = iconColorTransform;
			navBar.musicPlayer.bg.transform.colorTransform = iconBgColorTransform;
			
			navBar.fullscreenBtn.icon.transform.colorTransform = iconColorTransform;
			navBar.fullscreenBtn.bg.transform.colorTransform = iconBgColorTransform;
		}


		private function onBgImageLoaded(e:Event):void
		{
			
			e.target.content.smoothing = true;

			myLoader.width = bg.width;
			myLoader.height = bg.height;
			myLoader.x = - bg.width / 2;
			myLoader.y = - bg.height / 2;
			myLoader.alpha = 0;
			bg.addChild(myLoader);
			Tweener.addTween (myLoader, {alpha: 1, time:1 , transition:"easeInOutCubic"});
			bg.addEventListener(Event.ENTER_FRAME, onFrame)
			stage.addEventListener(Event.RESIZE, onStageResize);

		}



		private function initButtons():void
		{
			navBar.aboutBtn.message = text1;
			navBar.aboutBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.aboutBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.contactBtn.message = text2;
			navBar.contactBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.contactBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.pdfBtn.message = text3;
			navBar.pdfBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.pdfBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.zoomBtn.message = text5;
			navBar.zoomBtn.addEventListener(MouseEvent.CLICK, clickZoom);
			navBar.zoomBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.zoomBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.panBtn.message = text6;
			navBar.panBtn.addEventListener(MouseEvent.CLICK, clickPan);
			navBar.panBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.panBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.tiltBtn.message = text7;
			navBar.tiltBtn.addEventListener(MouseEvent.CLICK, clickTilt);
			navBar.tiltBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.tiltBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.speedBtn.message = text8;
			navBar.speedBtn.addEventListener(MouseEvent.CLICK, clickSpeed);
			navBar.speedBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.speedBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.thicknessBtn.message = text9;
			navBar.thicknessBtn.addEventListener(MouseEvent.CLICK, clickThickness);
			navBar.thicknessBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.thicknessBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.thumbBtn.message = text10;
			//navBar.thumbBtn.addEventListener(MouseEvent.CLICK, clickThickness);
			navBar.thumbBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.thumbBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			//navBar.interactBtn.message = text17;
			//navBar.interactBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			//navBar.interactBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.prevBtn.message = text11;
			navBar.prevBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.prevBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.nextBtn.message = text12;
			navBar.nextBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.nextBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			//navBar.autoflipBtn.message = text18;
			//navBar.autoflipBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			//navBar.autoflipBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.firstBtn.message = text4;
			navBar.firstBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.firstBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.lastBtn.message = text13;
			navBar.lastBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.lastBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.pageNumber.message = text14;
			navBar.pageNumber.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.pageNumber.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.musicPlayer.message = text15;
			navBar.musicPlayer.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.musicPlayer.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			navBar.fullscreenBtn.message = text16;
			navBar.fullscreenBtn.addEventListener(MouseEvent.ROLL_OVER, overNav);
			navBar.fullscreenBtn.addEventListener(MouseEvent.ROLL_OUT, outNav);
			
			//sliders

			zoom.message = text5;
			zoom.addEventListener(MouseEvent.ROLL_OVER, over);
			zoom.addEventListener(MouseEvent.ROLL_OUT, out);
			
			pan.message = text6;
			pan.addEventListener(MouseEvent.ROLL_OVER, over);
			pan.addEventListener(MouseEvent.ROLL_OUT, out);
			
			tilt.message = text7;
			tilt.addEventListener(MouseEvent.ROLL_OVER, over);
			tilt.addEventListener(MouseEvent.ROLL_OUT, out);
			
			speedSlider.message = text8;
			speedSlider.addEventListener(MouseEvent.ROLL_OVER, over);
			speedSlider.addEventListener(MouseEvent.ROLL_OUT, out);
			
			thicknessSlider.message = text9;
			thicknessSlider.addEventListener(MouseEvent.ROLL_OVER, over);
			thicknessSlider.addEventListener(MouseEvent.ROLL_OUT, out);
			
		}

		private function overNav(e:MouseEvent):void
		{
			//e.target.blendMode = BlendMode.HARDLIGHT;
			Tweener.addTween(e.target, {_brightness:0.5, time:.3, transition:"easeInOutSine"});
			tp2.x = mouseX;
			tp2.y = mouseY - 30;
			tp2.tooltipText.text = e.target.message;
			tp2.tooltipText.selectable = false;
			tp2.tooltipText.autoSize = TextFieldAutoSize.CENTER;
			tp2.tooltipBg.width = tp2.tooltipText.width + 10;
			
			tp2.alpha = 0;
			if (!tp2On)
			{
				this.addChild(tp2);
				tp2On = true;
			}
			Tweener.addTween (tp2, {alpha: 1, time:0.2 , transition:"easeInSine"});
			
			addEventListener(Event.ENTER_FRAME, moveTooltipNav)
			
		}

		//button roll out, hide tooltip
		private function outNav(e:MouseEvent):void
		{
			removeEventListener(Event.ENTER_FRAME, moveTooltipNav);
			Tweener.addTween(e.target, {_brightness:0, time:.3, transition:"easeInOutSine"});
			//e.target.blendmode = BlendMode.NORMAL;
			Tweener.addTween (tp2, {alpha: 0, time:1 , transition:"easeInOutCubic", onComplete:removeToolTip});
		}

		//show and hide slider on button click
		private function clickZoom(e:MouseEvent):void
		{
			now = 0;
			if (!zoom.visible)
				{
				zoom.alpha = 0;
				zoom.visible = true;
				Tweener.addTween (zoom, {alpha: 1, time:.5 , transition:"easeInOutCubic"});
			}
			else 
				zoom.visible = false;
		}
		private function clickPan(e:MouseEvent):void
		{
				now = 0;

			if (!pan.visible)
			{
				pan.alpha = 0;
				pan.visible = true;
				Tweener.addTween (pan, {alpha: 1, time:.5 , transition:"easeInOutCubic"});

			}
			else 
			{
				pan.visible = false;
			}
		}
		private function clickTilt(e:MouseEvent):void
		{
				now = 0;

			if (!tilt.visible)
			{
				tilt.alpha = 0;
				tilt.visible = true;
				Tweener.addTween (tilt, {alpha: 1, time:.5 , transition:"easeInOutCubic"});
			}
			else 
				tilt.visible = false;
		}
		private function clickSpeed(e:MouseEvent):void
		{
				now = 0;

			if (!speedSlider.visible)
			{
				speedSlider.alpha = 0;
				speedSlider.visible = true;
				Tweener.addTween (speedSlider, {alpha: 1, time:.5 , transition:"easeInOutCubic"});
				
			}
			else 
				speedSlider.visible = false;
		}
		private function clickThickness(e:MouseEvent):void
		{
				now = 0;

			if (!thicknessSlider.visible)
			{
				thicknessSlider.alpha = 0;
				thicknessSlider.visible = true;
				Tweener.addTween (thicknessSlider, {alpha: 1, time:.5 , transition:"easeInOutCubic"});
			}
			else 
				thicknessSlider.visible = false;
		}

		private function removeToolTip():void
		{
				this.removeChild(tp2);
				tp2On = false;
		}

		//update tooltip position
		private function moveTooltipNav(e:Event):void
		{
			tp2.x = mouseX;
			tp2.y = mouseY - 30;
			
		}
		private function out1(e:MouseEvent):void
		{
			timer.start();
		}

		private function click1(e:MouseEvent):void
		{
			now = 0;
		}
		private function onTimer(e:TimerEvent):void 
		{
			now++; 
			if (now == 5)
			{
				zoom.visible = false;
				pan.visible = false;
				tilt.visible = false;
				speedSlider.visible = false;
				thicknessSlider.visible = false;

				now = 0;
			}
		}

		private function positionButtons():void
		{
			//position buttons
			if (aboutOn == "true")
			{
				navBar.aboutBtn.x = btnPosX;
				btnPosX += navBar.aboutBtn.width;
			}
			else navBar.aboutBtn.visible = false;
			if (contactOn == "true")
			{
				navBar.contactBtn.x = btnPosX;
				btnPosX += navBar.contactBtn.width;
			}
			else navBar.contactBtn.visible = false;
			
			if (pdfOn == "true")
			{
				navBar.pdfBtn.x = btnPosX;
				btnPosX += navBar.pdfBtn.width;
			}
			else navBar.pdfBtn.visible = false;
			
			if (zoomOn == "true")
			{
				navBar.zoomBtn.x = btnPosX;
				zoom.x = navBar.zoomBtn.x + stage.stageWidth / 2 + navBar.zoomBtn.width / 2;
				btnPosX += navBar.zoomBtn.width;
				
			}
			else 
				navBar.zoomBtn.visible = zoom.visible = false;
			
			if (panOn == "true")
			{
				navBar.panBtn.x = btnPosX;
				pan.x = navBar.panBtn.x + stage.stageWidth / 2 + navBar.panBtn.width / 2;
				btnPosX += navBar.panBtn.width;
			}
			else 
				navBar.panBtn.visible = pan.visible = false;
			
			if (tiltOn == "true")
			{
				navBar.tiltBtn.x = btnPosX;
				tilt.x = navBar.tiltBtn.x + stage.stageWidth / 2 + navBar.tiltBtn.width / 2;
				btnPosX += navBar.tiltBtn.width;
			}
			else navBar.tiltBtn.visible = tilt.visible = false;
			
			if (speedOn == "true")
			{
				navBar.speedBtn.x = btnPosX;
				speedSlider.x = navBar.speedBtn.x + stage.stageWidth / 2 + navBar.speedBtn.width / 2;
				btnPosX += navBar.speedBtn.width;
			}
			else navBar.speedBtn.visible = speedSlider.visible = false;
			
			if (thicknessOn == "true")
			{
				navBar.thicknessBtn.x = btnPosX;
				thicknessSlider.x = navBar.thicknessBtn.x + stage.stageWidth / 2 + navBar.thicknessBtn.width / 2;
				btnPosX += navBar.thicknessBtn.width;
			}
			else navBar.thicknessBtn.visible = thicknessSlider.visible = false;
			
			if (thumbOn == "true")
			{
				navBar.thumbBtn.x = btnPosX;
				btnPosX += navBar.thumbBtn.width;
			}
			else navBar.thumbBtn.visible = false;
			
			//if (interactOn == "true")
			//{
				//navBar.interactBtn.x = btnPosX;
				//btnPosX += navBar.interactBtn.width;
			//
			//}
			//else navBar.interactBtn.visible = false;
			
			
			navBar.fullscreenBtn.x = stage.stageWidth / 2 - navBar.fullscreenBtn.width;
			
			if (musicOn == "true")
			{
				navBar.musicPlayer.x = navBar.fullscreenBtn.x - navBar.fullscreenBtn.width;
			
			}
			else navBar.musicPlayer.visible = false;

		}

	}
	
}