//Tiina Vuorenmaa
//Sr Proj - Itera
//Started: 6/3/2010
//Updated: 9/30/2010
//Main.as
//here is where everything is put together

package
{
	//import from flash
	import flash.system.Security;
	import flash.system.System;
	import flash.display.MovieClip;
	import flash.geom.ColorTransform;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	//for saving to php/mysql
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequestMethod;
	import flash.net.navigateToURL;
	import flash.external.ExternalInterface;
	import flash.events.Event;
	import flash.ui.Mouse;
	
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;

	
	//mvc imports
	import model.*
	import view.*;
	import controller.*;
	
	public class Main extends MovieClip
	{
		
		//variables
		//for the customize section
		private var _clothingModel:ClothingModel;
		private var _clothingController:ClothingController;
		private var _extrasModel:ExtrasModel;
		private var _extrasController:ExtrasController;
		private var _avatarModel:AvatarModel;
		private var _avatarController:AvatarController;
		private var _myAvatar:AvatarView; //view avatar clothing and extras
		
		private var _nexusModel:NexusModel;
		private var _nexusController:NexusController;
		private var _myNexus:NexusView; //views nexus (seat, bkg and tint)
		
		//different parts of the user model
		private var _userModel:UserModel;
		private var _userController:UserController; //level, energy, xp - things that change
		private var _userStaticModel:UserStaticModel;
		private var _userStaticController:UserStaticController; //id,name - only get once
		private var _userLockedModel:UserLockedModel;
		private var _userLockedController:UserLockedController;  //deals with karma and customize btns that are locked
		private var _userNeighborsModel:UserNeighborsModel;
		private var _userNeighborsController:UserNeighborsController;
		
		private var _userFriendsModel:UserFriendsModel;
		private var _userFriendsController:UserFriendsController;
		private var _friendsView:FriendsView;
		
		private var _userAvatarModel:UserAvatarModel;
		private var _userAvatarController:UserAvatarController;
		private var _userPostModel:UserPostModel;
		private var _userPostController:UserPostController;
		private var _dailyQuoteModel:DailyQuoteModel;
		private var _dailyQuoteController:DailyQuoteController;
		
		private var _neighborModel:CurrentNeighborModel;
		private var _neighborController:CurrentNeighborController;
		private var _neighborsView:NeighborsView;
		
		private var _receiveKarmaModel:ReceiveKarmaModel;
		private var _receiveKarmaController:ReceiveKarmaController;
		private var _sendKarmaModel:SendKarmaModel;
		private var _sendKarmaController:SendKarmaController;
		private var _karmaModel:KarmaModel;
		private var _karmaController:KarmaController;
		private var _karmaView:KarmaView;
		
		private var _postsModel:PostsModel;
		private var _postsController:PostsController;
		private var _postsView:PostsView;
		
		
		
		private var _customizeModel:CustomizeModel;
		private var _tabModel:TabModel;
		private var _sectionModel:CustomizeSectionModel;
		private var _customizeController:CustomizeController;
		private var _tabController:TabController;
		private var _sectionController:CustomizeSectionController;
		private var _customizeView:CustomizeView;
		
		private var _avatarPrice:Number;
		private var _newNeighbor:String;
		
		//saving to file
		private var uploadedVariables:URLVariables;
		private var uploadRequest:URLRequest;
		private var uploader:URLLoader;
		
		//loading info
		private var downloadedVariables:URLVariables;
		private var downloadRequest:URLRequest;
		private var downloader:URLLoader;
		var downloadedAvatarArray:Array = new Array();
		
		//zoom variables
		private var zoomDragY:Number;
		private var zoomY:Number;
		private const ZOOMBARMIDDLE:Number = 258.10;

		//exit and saving from customize menu
		private var saveExitCustomizeBtn:SaveAvatarBtn = new SaveAvatarBtn();
		private var cancelCustomizeBtn:RoundCancelBtn = new RoundCancelBtn();
		
		//if there are no posts or neighbors
		// the  buttons for the mini message
		private var _inviteBtn:InviteSimpleButton;
		private var _addNeighborBtn:AddNeighborSimpleButton;
		private var _sendDailyBtn:DailyKarmaSimpleButton;
		private var _sendGiftBtn:GiftKarmaSimpleButton;
		
		private var _invitedBy:String;
        private var _invitedByID:String;
		private var _currentPage:String;
		
		//helpscreen scrollbars
		private var _scrollBar:TallScrollBar = new TallScrollBar();
		//scroll bar colors
		private var scrollColorTransform:ColorTransform = new ColorTransform();
		
		// mini tutorial
		private var _tutorial:Boolean;
		
		//sounds
		private var _bkgMusic:Sound = new Sound();
		private var _rewardSound:Sound = new Sound();
		private var _dingSound:Sound = new Sound();
		private var _musicChannel:SoundChannel = new SoundChannel();
		private var _soundChannel:SoundChannel = new SoundChannel();
		private var _musicVolume:SoundTransform;
		private var _soundVolume:SoundTransform;
		
		private var _basicLevelXPArray:Array;
		private var _tempBoughtPartsSectionArray:Array;
		private var _tempBoughtPartsArray:Array;

				
		public function Main ():void
		{
			//this begins the game
			//in setupMain, there is a "cover"
			//the cover is removed when the user info is done dowloading
			//ExternalInterface.addCallback("sendInviteInfoToFlash", getInviteInfoFromJavaScript);
			
			//for security issues since the index.php is now on apps.facebook.com and the swf is still on itera-game.com
			Security.allowDomain("itera-game.com");
			
			setupMain();
			trace("in Main class");
			_currentPage = "Home";
			_tutorial = true;
			
			_tempBoughtPartsSectionArray = new Array();
			_tempBoughtPartsArray = new Array();
			
			_bkgMusic.load(new URLRequest("sounds/itera_bkgsound.mp3"));
			_rewardSound.load(new URLRequest("sounds/itera_ding_reward.mp3"));
			_dingSound.load(new URLRequest("sounds/itera_ding_message.mp3"));
			
			//_musicChannel = _bkgMusic.play(0,999);
			_musicVolume = new SoundTransform(0.8,0);
			_musicChannel.soundTransform = _musicVolume;
			
			_soundVolume = new SoundTransform(0.8,0);
			_soundChannel.soundTransform = _soundVolume;
			
			//_soundChannel = _rewardSound.play(5,0);
			
			//_soundChannel = _dingSound.play(15,0);
																	  
						
		}//end contructor

//beginning functions with javascript
		function getInviteIDFromJavaScript(a_inviteID:String):void
		{
			_invitedByID = a_inviteID;
		}
		
		function getInviteNameFromJavaScript(a_inviteName:String):void
		{
			_invitedBy = a_inviteName;
            showMiniMessage("Welcome to Itera");
		}
		
		function getKarmaInfoFromJavaScript(str:String):void
		{
				trace("Karma From JavaScript: " + str);
		}
		
		
		private function setupMain():void
		{
			//for the avatar
			_avatarModel = new AvatarModel();
			_avatarController = new AvatarController(_avatarModel);
			_clothingModel = new ClothingModel();
			_clothingController = new ClothingController(_clothingModel);
			_extrasModel = new ExtrasModel();
			_extrasController = new ExtrasController(_extrasModel);
			//views avatar, clothing and extras
			_myAvatar = new AvatarView(_avatarModel, _clothingModel, _extrasModel);
			
			//for the nexus
			_nexusModel = new NexusModel();
			_nexusController = new NexusController(_nexusModel);
			_myNexus = new NexusView(_nexusModel);
			
			//customize section
			_customizeModel = new CustomizeModel();
			_tabModel = new TabModel();
			_sectionModel = new CustomizeSectionModel();
			_customizeController = new CustomizeController(_customizeModel);
			_tabController = new TabController(_tabModel);
			_sectionController = new CustomizeSectionController(_sectionModel);
			_customizeView = new CustomizeView(_customizeModel,_tabModel, _sectionModel, _customizeController, _tabController, _sectionController, _avatarController, _clothingController, _extrasController, _nexusController);
			
			//user model and variations
			_userModel = new UserModel();
            _userController = new UserController(_userModel); //energy, level, xp
			
			_userAvatarModel = new UserAvatarModel();
			_userAvatarController = new UserAvatarController(_userAvatarModel); //avatar
			
            _userNeighborsModel = new UserNeighborsModel();
            _userNeighborsController = new UserNeighborsController(_userNeighborsModel); //neighbors array
			
            _userFriendsModel = new UserFriendsModel();
            _userFriendsController = new UserFriendsController(_userFriendsModel); //friends array
			
            _userPostModel = new UserPostModel();
            _userPostController = new UserPostController(_userPostModel); //my posts
			
            _userLockedModel = new UserLockedModel();
            _userLockedController = new UserLockedController(_userLockedModel); //locked animal array for karma/customize (only on level up)
			
            _userStaticModel = new UserStaticModel();
            _userStaticController = new UserStaticController(_userStaticModel); //id and name and animal array  (once)
			
            _dailyQuoteModel = new DailyQuoteModel();
            _dailyQuoteController = new DailyQuoteController(_dailyQuoteModel); //daily quote (once)
			
            
			//posts (view is below)
			_postsModel = new PostsModel();
            _postsController = new PostsController(_postsModel);
			
			//neighbor (view is below)
			_neighborModel = new CurrentNeighborModel();
			_neighborController = new CurrentNeighborController(_neighborModel);
			
			//karma section
			_karmaModel = new KarmaModel();
			_karmaController = new KarmaController(_karmaModel);
			
			_sendKarmaModel = new SendKarmaModel();
			_sendKarmaController = new SendKarmaController(_sendKarmaModel);
			
			_receiveKarmaModel = new ReceiveKarmaModel();
			_receiveKarmaController = new ReceiveKarmaController(_receiveKarmaModel);
			
			_karmaView = new KarmaView(_karmaModel, _sendKarmaModel, _receiveKarmaModel, _userModel, _userStaticModel, _sendKarmaController, _userController);

			//_friendsView view uses neighbor model and a bunch others so it needs to be below them
			_friendsView = new FriendsView(_userFriendsModel, _customizeModel, _neighborModel, _neighborController, _customizeView);
			
			//postsview needs to be down here because it uses the neighborcontroller
			_postsView = new PostsView(_postsModel, _userStaticModel, _userPostModel, _karmaModel, _sendKarmaController, _neighborController);
			
			//neighbors view uses the posts view so it needs to be below it
			_neighborsView = new NeighborsView(_userNeighborsModel, _neighborModel, _neighborController, _customizeModel, _sendKarmaModel, _postsView, _customizeView);
			

			
			_myNexus.x = 0;
			_myNexus.y = 0;
			nexusHolder.addChild(_myNexus);

			_myAvatar.x = 0;
			_myAvatar.y = 75;
			avatarHolder.addChild(_myAvatar);
			avatarHolder.scaleX = 0.8;
			avatarHolder.scaleY = 0.8;
			avatarHolder.x = 380;
			avatarHolder.y = 316;
			zoomDragBtn.y = 254.3;
			
			_neighborsView.x = 0;
			_neighborsView.y = 450;
			addChild(_neighborsView);
			
			_customizeView.x = 0;
			_customizeView.y = 1425;
			addChild(_customizeView);
			_customizeController.setUpArrays();
			
			addZoomFeature();
			
			mainMenu.x = 688;
			mainMenu.y = 368;
			
			myPost.scaleX = 0;
			createPost.scaleX = 0;
			dailyQuote.scaleX = 0;
			mainMenu.scaleX = 1;
			
			mainMenuBtn.x = 688;
			mainMenuBtn.y = 362;
			mainMenuBtn.buttonMode = true;
			mainMenu.myAvatarBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenu.myPostBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenu.sendKarmaBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenu.viewPostsBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenu.dailyQuoteBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
			
			//top nav buttons
			topNexusBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			topCustomizeBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			topCreateBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			topReadAllBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			topGiftBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			topInviteBtn.addEventListener(MouseEvent.CLICK, openFacebookInviteWindow);
			topHelpBtn.addEventListener(MouseEvent.CLICK, topNavBtnClicked);
			
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			windowScreen.addChild(_scrollBar);
			
			//custom events from neighbors section and others
			_neighborsView.addEventListener("go to SendKarmaView", dispatchEventsToMain);
            _friendsView.addEventListener("go to SendKarmaView", dispatchEventsToMain);
            _neighborsView.addEventListener("go to RespondKarmaView", dispatchEventsToMain);
            _postsView.addEventListener("go to RespondKarmaView", dispatchEventsToMain); //same but from posts
			_postsView.addEventListener("noPosts", dispatchEventsToMain);
			_postsView.addEventListener("noMyPosts", dispatchEventsToMain);
			_neighborsView.addEventListener("noNeighbors", dispatchEventsToMain);
			
            _neighborsView.addEventListener("go to NeighborPostsView", dispatchEventsToMain);
            _neighborsView.addEventListener("close NeighborPostsView", dispatchEventsToMain);
            _neighborsView.addEventListener("close RespondKarmaView", dispatchEventsToMain);
            _postsView.addEventListener("close AllPostsView", dispatchEventsToMain);
            _neighborsView.addEventListener("viewing Neighbor Nexus", dispatchEventsToMain);
            _friendsView.addEventListener("viewing Neighbor Nexus", dispatchEventsToMain);
            _friendsView.addEventListener("send neighbor request", dispatchEventsToMain);
            _karmaView.addEventListener("send karma request", dispatchEventsToMain);
            _karmaView.addEventListener("send karma multifriend request", dispatchEventsToMain);
            _neighborsView.addEventListener("view list of friends", dispatchEventsToMain);
            _userController.addEventListener("level up the User", dispatchEventsToMain);
			
			
			 gotKarmaBtn.buttonMode = false;
            gotKarmaBtn.mouseChildren = false;
            gotKarmaBtn.alpha = 0;
            gotKarmaBtn.scaleX = 0;
			
			addChild(openingCover);
			downloadUserInfo("fake");
			
			
			_basicLevelXPArray= [0,0,25,500,1500,2600,3800,5100,6500,8000,9600]; //top xp for each level starting with level 1=0, level2=25;
			
			//openingCover.enterIteraBtn.addEventListener(MouseEvent.CLICK, mouseEnterItera);
			//this.addEventListener(KeyboardEvent.KEY_DOWN, keyboardEnterItera);
			//openingCover.inputName.addEventListener(MouseEvent.CLICK, clearField);

			//listen for change in the user model and change the view
			//the user model will change once the user info is done downloading
			_userModel.addEventListener(UserModel.UPDATE, updateUserInfo);
			_userAvatarModel.addEventListener(UserAvatarModel.UPDATE, viewCurrentUser);
			//_userNeighborsModel.addEventListener(UserNeighborModel.UPDATE, viewCurrentNeighbors);
			_userModel.addEventListener(UserModel.UPDATE, viewCurrentPost);
			var theResult = ExternalInterface.call("checkingInvitesFromFlash", "yes");
			
			

		}
		
		//top nav buttons click
		private function topNavBtnClicked(event:MouseEvent):void
		{
			//clear all
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			_neighborsView.closeNeighborInfoAndBigBox();
			saveExitCustomizeBtn.x = 6880;
			cancelCustomizeBtn.y = 6880;
			_customizeView.y = 1425;
			mainMenuBtn.gotoAndStop("off");
			mainMenu.scaleX =0;
			myPost.scaleX = 0;
			createPost.scaleX = 0;
			dailyQuote.scaleX = 0;
			
			switch (event.target.name)
			{
				case "topNexusBtn":
				trace("closing all and viewing my nexus");
				//all closed above
				break;
				
				case "topCustomizeBtn":
				trace("closing window and neighbor screens to customize");
				openCustomizeView();
				mainMenuBtn.gotoAndStop("on");
				break;
				
				case "topCreateBtn":
				trace("closing all to view create my post");
				openCreatePostView();
				break;
				
				case "topReadAllBtn":
				trace("viewing window screen - all posts");
				downloadPostArray("0");
				break;
				
				case "topGiftBtn":
				trace("viewing window screen: Gift a Karma");
				openSendKarmaView("mainMenu");
				break;
				
				case "topHelpBtn":
				trace("viewing help screen");
				showHelpScreen();
				break;
				
				default:
				break;
				
			}//end switch
			
		}

		
		///  CHANGING the USER VIEW ///
		//loading the avatar
		public function viewCurrentUser(event:Event):void
		{
			_customizeView.loadCurrentAvatar(_userAvatarModel.savedAvatarArray);
			
		}
		
		public function updateUserInfo(event:Event):void
		{
			energyNum.text = String(_userModel.userEnergy);
			xpBar.xpNum.text = String(_userModel.userXP);
			updateXPBar();
			level.levelNum.text = String(_userModel.userLevel);
			nexusName.text = _userStaticModel.userName +"'s Nexus";
			
		}
		
		public function updateXPBar():void
		{
			//get the total number of XP to next level
			var totalXP:Number =  _basicLevelXPArray[_userModel.userLevel+1] - _basicLevelXPArray[_userModel.userLevel];
			var xpRatio:Number = ((_userModel.userXP - _basicLevelXPArray[_userModel.userLevel])/totalXP) * 180;
			//find how far the user has gone
			xpBar.xpScale.x = -93 + xpRatio;

		}
		
		function viewHomeNexus(event:MouseEvent):void
		{
			topNexusBtn.removeEventListener(MouseEvent.CLICK, viewHomeNexus);
			mainMenuBtn.removeEventListener(MouseEvent.CLICK, viewHomeNexus);
			mainMenuBtn.gotoAndStop("off");
			mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
			_customizeView.loadCurrentAvatar(_userAvatarModel.savedAvatarArray);
			_customizeView.y = 1425;
			_userModel.homeNexus = true;
		}
		
		// DISPATCH EVENTS TO MAIN //
		private function dispatchEventsToMain(event:Event):void
		{
			trace(event.type);
			switch(event.type)
			{
				case "noPosts":
				showMiniMessage("noPosts");
				break;
				
				case "noMyPosts":
				showMiniMessage("noMyPosts");
				break;
				
				case "noNeighbors":
				showMiniMessage("noNeighbors");
				break;
				
				case "level up the User":
				_userLockedController.createLockedArray(_userStaticModel.userAnimalArray, _userModel.userLevel);
				showMiniMessage("levelUp");
				break;
				
				case "view list of friends":
				openAddNeighborView();
				break;
				
				case "send neighbor request":
				uploadNewNeighborRequest();
                //showMiniMessage("Confirm Neighbor Request");
                break;
					
                case "send karma request":
                trace("sending karma request");
				uploadNewKarmaRequest();
               // showMiniMessage("Confirm Karma Request");
                break;

                case "sendMultiKarmaRequest":
                sendMultiKarmaRequest();
                break;
				
				case "viewing Neighbor Nexus":
				windowScreen.x = 1000;
                windowScreen.y = 1000;
				_userModel.homeNexus = false;
				energyNum.text = String(_neighborModel.neighborEnergy);
				xpBar.xpNum.text = String(_neighborModel.neighborXP);
				level.levelNum.text = String(_neighborModel.neighborLevel);
				nexusName.text = _neighborModel.neighborName +"\'s Nexus";
				mainMenu.scaleX = 0;
				topNexusBtn.addEventListener(MouseEvent.CLICK, viewHomeNexus);
				mainMenuBtn.addEventListener(MouseEvent.CLICK, viewHomeNexus);
				mainMenuBtn.gotoAndStop("goHome");
				break;
			
				case "close AllPostsView":
				//this one is coming from posts view
				windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeAllPostsView);
				windowScreen.x = 1000;
				windowScreen.y = 1000;
				_postsView.x = 4535;
				break;
				
				case "go to SendKarmaView":
				openSendKarmaView(_neighborModel.neighborName);
				break;
				
				case "go to RespondKarmaView":
				openResponseKarmaView(_neighborModel.neighborName);
				break;
				
				case "go to NeighborPostsView":
				downloadPostArray(_neighborModel.neighborID);
				break;
				
				case "close NeighborPostsView":
				_postsView.x = 4535;
				break;
				
				case "close RespondKarmaView":
				_karmaView.x = 4535;
				break;
				
				default:
				trace("problem");
				break;
			}
			
		}
		
////////// USER INFO: AVATARS etc. downloading and uploading //
		//uploads the saved avatar to the correct userID
		
		private function uploadUserInfo(a_userID:String):void
		{
			//flash variables I'm sending with the urlrequest
			var uploadedVariables:URLVariables = new URLVariables;
			var arrayToUpload:Array = createCurrentAvatarArray();
			//trace("uploading = "+arrayToUpload);
			trace("uploading info for = " +a_userID);
			uploadedVariables.userID = a_userID;
			uploadedVariables.userLevel = _userModel.userLevel;
			uploadedVariables.userEnergy = _userModel.userEnergy;
			uploadedVariables.userXP = _userModel.userXP;

			
			//trace("uploading = "+uploadedVariables);
			//the url request
			//the file should be a separate processing php file to connect with the database
			var uploadRequest = new URLRequest("http://www.itera-game.com/upload_user_info.php");

			//the method is POST so that the variables don't show in the http url
			//but since it is a processing php file, it won't show up at all
			uploadRequest.method = URLRequestMethod.POST;

			// the variables are added to the data to send to the php file
			//php file can get the variable using $_POST["filename"]
			uploadRequest.data = uploadedVariables;

			//the load will load the requiest
			var uploader = new URLLoader();
			uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
			//when it is loaded let me know (plus other stuff)
			uploader.addEventListener(Event.COMPLETE,doneUploadingUserInfo);
			//load it
			try
            {
                uploader.load(uploadRequest);
            } 
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }

		}
		
		private function doneUploadingUserInfo(event:Event):void
		{
			trace("uploaded");
			//once it is loaded, you can get data from the php file with uploader
			//in this instance the php file created an xml file as output
			
			var checkLoader:URLLoader = URLLoader(event.target);
			var checkUploadedVariables:URLVariables = new URLVariables(checkLoader.data);
			trace(checkLoader.data);
			//trace(checkUploadedVariables.theResult);
   			//trace(checkUploadedVariables.theResult);

		}

		private function uploadSavedAvatar(a_userID:String):void
		{
			//flash variables I'm sending with the urlrequest
			var uploadedVariables:URLVariables = new URLVariables;
			var arrayToUpload:Array = createCurrentAvatarArray();
			//trace("uploading = "+arrayToUpload);
			trace("uploading = " +a_userID);
			uploadedVariables.userID = a_userID;
			uploadedVariables.userEnergy = _userModel.userEnergy;
			uploadedVariables.avatarPart00 = arrayToUpload[0];
			uploadedVariables.avatarPart01 = arrayToUpload[1];
			uploadedVariables.avatarPart02 = arrayToUpload[2];
			uploadedVariables.avatarPart03 = arrayToUpload[3];
			uploadedVariables.avatarPart04 = arrayToUpload[4];
			uploadedVariables.avatarPart05 = arrayToUpload[5];
			uploadedVariables.avatarPart06 = arrayToUpload[6];
			uploadedVariables.avatarPart07 = arrayToUpload[7];
			uploadedVariables.avatarPart08 = arrayToUpload[8];
			uploadedVariables.avatarPart09 = arrayToUpload[9];
			uploadedVariables.avatarPart10 = arrayToUpload[10];
			uploadedVariables.avatarPart11 = arrayToUpload[11];
			uploadedVariables.avatarPart12 = arrayToUpload[12];
			uploadedVariables.avatarPart13 = arrayToUpload[13];
			uploadedVariables.avatarPart14 = arrayToUpload[14];
			uploadedVariables.avatarPart15 = arrayToUpload[15];
			uploadedVariables.avatarPart16 = arrayToUpload[16];
			uploadedVariables.avatarPart17 = arrayToUpload[17];
			uploadedVariables.avatarPart18 = arrayToUpload[18];
			uploadedVariables.avatarPart19 = arrayToUpload[19];
			
			trace("_tempBoughtPartsArray.length = " + _tempBoughtPartsArray.length);
			trace("_tempBoughtPartsArray = " + _tempBoughtPartsArray.toString());
			//upload bought parts
			if(_tempBoughtPartsArray.length > 0)
			{
				//add the bought parts when uploading the saved avatar
				uploadedVariables.boughtPartsSection = _tempBoughtPartsSectionArray.toString();
				uploadedVariables.boughtParts = _tempBoughtPartsArray.toString();
			}
			else
			{
				uploadedVariables.boughtPartsSection = 0;
				uploadedVariables.boughtParts = 0;
			}
			
			//trace("uploading = "+uploadedVariables);
			//the url request
			//the file should be a separate processing php file to connect with the database
			var uploadRequest = new URLRequest("http://www.itera-game.com/save_avatar.php");

			//the method is POST so that the variables don't show in the http url
			//but since it is a processing php file, it won't show up at all
			uploadRequest.method = URLRequestMethod.POST;

			// the variables are added to the data to send to the php file
			//php file can get the variable using $_POST["filename"]
			uploadRequest.data = uploadedVariables;

			//the load will load the requiest
			var uploader = new URLLoader();
			uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
			//when it is loaded let me know (plus other stuff)
			uploader.addEventListener(Event.COMPLETE,doneUploadingAvatar);
			//load it
			try
            {
                uploader.load(uploadRequest);
            } 
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }

		}
		
		private function doneUploadingAvatar(event:Event):void
		{
			trace("uploaded");
			//once it is loaded, you can get data from the php file with uploader
			//in this instance the php file created an xml file as output
			
			var checkLoader:URLLoader = URLLoader(event.target);
			var checkUploadedVariables:URLVariables = new URLVariables(checkLoader.data);
			trace(checkLoader.data);
			//trace(checkUploadedVariables.theResult);
   			//trace(checkUploadedVariables.theResult);

		}
		
		//gets the current look of the avatar and translates it into a saved avatar array
		private function createCurrentAvatarArray():Array
		{
			//finds the number for each part and puts it into an array to upload
			var tempArray:Array = new Array();
			var a:int = 0;
			while(a<_customizeModel.faceShapeArray.length)
			{
				if (_avatarModel.faceShape == _customizeModel.faceShapeArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.faceShapeArray.length + 1;
				}
				a++;
			} 
			
			a = 0;
			while(a<_customizeModel.eyesArray.length)
			{
				if (_avatarModel.eyes == _customizeModel.eyesArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.eyesArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.noseArray.length)
			{
				if (_avatarModel.nose == _customizeModel.noseArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.noseArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.earsArray.length)
			{
				if (_avatarModel.ears == _customizeModel.earsArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.earsArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.mouthArray.length)
			{
				if (_avatarModel.mouth == _customizeModel.mouthArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.mouthArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.browsArray.length)
			{
				if (_avatarModel.brows == _customizeModel.browsArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.browsArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.hairArray.length)
			{
				if (_avatarModel.hair == _customizeModel.hairArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.hairArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.skinColorArray.length)
			{
				if (_avatarModel.skinColor == _customizeModel.skinColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.skinColorArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.eyeColorArray.length)
			{
				if (_avatarModel.eyeColor == _customizeModel.eyeColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.eyeColorArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.hairColorArray.length)
			{
				if (_avatarModel.hairColor == _customizeModel.hairColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.hairColorArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.clothingColorArray.length)
			{
				if (_clothingModel.topClothingColor == _customizeModel.clothingColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.clothingColorArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.clothingColorArray.length)
			{
				if (_clothingModel.bottomClothingColor == _customizeModel.clothingColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.clothingColorArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.topClothingArray.length)
			{
				if (_clothingModel.topClothing == _customizeModel.topClothingArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.topClothingArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.bottomClothingArray.length)
			{
				if (_clothingModel.bottomClothing == _customizeModel.bottomClothingArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.bottomClothingArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.headExtraArray.length)
			{
				if (_clothingModel.headExtra == _customizeModel.headExtraArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.headExtraArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.backExtraArray.length)
			{
				if (_clothingModel.backExtra == _customizeModel.backExtraArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.backExtraArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.seatArray.length)
			{
				if (_extrasModel.avatarSeat == _customizeModel.seatArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.seatArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.itemArray.length)
			{
				if (_extrasModel.handHeldItem == _customizeModel.itemArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.itemArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.bkgArray.length)
			{
				if (_nexusModel.nexusBkg == _customizeModel.bkgArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.bkgArray.length + 1;
				}
				a++;
			}
			
			a = 0;
			while(a<_customizeModel.bkgColorArray.length)
			{
				if (_nexusModel.bkgColor == _customizeModel.bkgColorArray[a])
				{
					tempArray.push(a);
					a = _customizeModel.bkgColorArray.length + 1;
				}
				a++;
			}
			
			trace("the tempArray  = " +tempArray);
			return tempArray;
		}
		
		// downloades all user info at the beginning of the game
		public function downloadUserInfo(a_username:String):void
		{
			trace("getting ready to download");
			//the url request
			//the file should be a separate processing php file to connect with the database
			var downloadRequest = new URLRequest("http://www.itera-game.com/download_user_info.php");

			var downloadVariables:URLVariables = new URLVariables;
			trace(a_username);
			//downloadVariables.userID = a_userID; 
			downloadVariables.username = a_username; //username at the moment
			//downloadVariables.newNeighbor =_newNeighbor;
			downloadRequest.method = URLRequestMethod.POST;
			
			// the variables are added to the data to send to the php file
			//php file can get the variable using $_POST["filename"]
			downloadRequest.data = downloadVariables;

			//the load will load the request
			downloader = new URLLoader();
			//downloader.dataFormat = URLLoaderDataFormat.TEXT;
			downloader.dataFormat = URLLoaderDataFormat.VARIABLES;
			//when it is loaded let me know (plus other stuff)
			downloader.addEventListener(Event.COMPLETE,doneDownloadingUserInfo);
			//load it
			try
            {
                downloader.load(downloadRequest);
            } 
            catch (error:Error)
            {
                trace("Unable to download URL: " + error);
            }

		}
		
		private function doneDownloadingUserInfo(event:Event):void
		{
			trace("downloaded");
			//once it is loaded, you can get data from the php file with uploader
			//in this instance the php file created an xml file as output
			
			var checkDownloader:URLLoader = URLLoader(event.target);
			trace(checkDownloader.data);
			var downloaded:URLVariables = new URLVariables(checkDownloader.data);
			if(downloader.data.newUser =="false")
			{
			downloadedAvatarArray.push(downloaded.avatarPart2);
			downloadedAvatarArray.push(downloaded.avatarPart3);
			downloadedAvatarArray.push(downloaded.avatarPart4);
			downloadedAvatarArray.push(downloaded.avatarPart5);
			downloadedAvatarArray.push(downloaded.avatarPart6);
			downloadedAvatarArray.push(downloaded.avatarPart7);
			downloadedAvatarArray.push(downloaded.avatarPart8);
			downloadedAvatarArray.push(downloaded.avatarPart9);
			downloadedAvatarArray.push(downloaded.avatarPart10);
			downloadedAvatarArray.push(downloaded.avatarPart11);
			downloadedAvatarArray.push(downloaded.avatarPart12);
			downloadedAvatarArray.push(downloaded.avatarPart13);
			downloadedAvatarArray.push(downloaded.avatarPart14);
			downloadedAvatarArray.push(downloaded.avatarPart15);
			downloadedAvatarArray.push(downloaded.avatarPart16);
			downloadedAvatarArray.push(downloaded.avatarPart17);
			downloadedAvatarArray.push(downloaded.avatarPart18);
			downloadedAvatarArray.push(downloaded.avatarPart19);
			downloadedAvatarArray.push(downloaded.avatarPart20);
			downloadedAvatarArray.push(downloaded.avatarPart21);
			trace("avatarArray = " + downloadedAvatarArray);
			trace("XP = " + downloaded.userXP); //xp
			trace("energy = " + downloaded.userEnergy); //energy
			trace("level = " + downloaded.userLevel); //level
			trace("animal array = " + downloaded.animalArray);
			trace("name = " + downloaded.userName); //name?
			trace("post = " + downloaded.thePost);
			trace("numresp = " + downloaded.numResponses);
			trace("userid = " + downloaded.userID);
			trace("boughtParts = " + downloaded.boughtParts);
			
			//once all is set up
			//Main views userController and UserModel
			//use only the controller to change the model and hence the view (Main)
			//added in the user's avatar
			_userAvatarController.changeSavedAvatarArray(downloadedAvatarArray);
			_userPostController.changeCurrentResponses(downloaded.numResponses);
			_userPostController.changeCurrentPost(downloaded.thePost);
			
			//get bought parts (sections and parts in 2 arrays)
            var boughtPartsSectionArray:Array = downloaded.boughtPartsSection.split(",");
            var zeroSection:String = boughtPartsSectionArray.pop();
			trace("boughtPartsSectionArray = " + boughtPartsSectionArray);
			
			var boughtPartsArray:Array = downloaded.boughtParts.split(",");
            var zeroPart:String = boughtPartsArray.pop();
			trace("boughtPartsArray = " + boughtPartsArray);
			
			_userAvatarController.changeBoughtPartsSectionArray(boughtPartsSectionArray);
			_userAvatarController.changeBoughtPartsArray(boughtPartsArray);
			changeCustomizePrices();
			
			}
			else
			{
				_userAvatarController.changeSavedAvatarArray(_customizeView.createRandomAvatarArray());
                uploadSavedAvatar(downloaded.userID);

			}
			
			_userStaticController.changeUserID(downloaded.userID);
			_userStaticController.changeUserName(downloaded.userName); //this one will have to come from facebook
			_userController.changeUserXP(downloaded.userXP);
			_userController.changeUserEnergy(downloaded.userEnergy);
			_userController.changeUserLevel(downloaded.userLevel);
			_userController.changeHomeNexus(true);
			
			//get the animal array and level to get the locked array
			//_userController.changeUserLevel(9);
			_userStaticController.changeAnimalArray(downloaded.animalArray.split(","));
            _userLockedController.createLockedArray(downloaded.animalArray.split(","), _userModel.userLevel);
			
			//get the rest of the info
            downloadGeneralInfo(downloaded.userID);

		}
		
		//need work!
		public function downloadGeneralInfo(a_userID:String) : void
        {
 
            trace("getting ready to download general information");
            var downloadRequest:URLRequest = new URLRequest("http://www.itera-game.com/download_general_info.php");
            var downloadVariables:URLVariables = new URLVariables();
			
            downloadVariables.userID = a_userID;
			
            downloadRequest.method = URLRequestMethod.POST;
            downloadRequest.data = downloadVariables;
            downloader = new URLLoader();
            downloader.dataFormat = URLLoaderDataFormat.VARIABLES;
            downloader.addEventListener(Event.COMPLETE, doneDownloadingGeneralInfo);
            try
            {
                downloader.load(downloadRequest);
            }
            catch (error:Error)
            {
                trace("Unable to download URL: " + error);
            }
          
        }// end function
		
		private function doneDownloadingGeneralInfo(event:Event) : void
        {
            trace("downloaded");
            var checkLoader:URLLoader = URLLoader(event.target);
            trace(checkLoader.data);
            var downloaded:URLVariables = new URLVariables(checkLoader.data);
			//dailyquote
            trace("daily quote = " + downloaded.dailyQuote);
            trace("dQ ID = " + downloaded.dailyQuoteID);
            _dailyQuoteController.changeDailyQuoteID(downloaded.dailyQuoteID);
            _dailyQuoteController.changeDailyQuote(downloaded.dailyQuote);
			
			//neighbors and friends
			//first get all my pending requests to be neighbors
            var allPendingNeighbors:Array = downloaded.myPendingNeighbors.split(",");
            var zeroNeighbor:String = allPendingNeighbors.pop();
            trace("allPendingNeighbors = " + allPendingNeighbors);

           	//then get all my friends requests to be neighbors
            var allPendingRequests:Array = downloaded.neighborRequests.split(",");
            var zeroRequest:String = allPendingRequests.pop();
			trace("allPendingRequests = " + allPendingRequests);
			
			//find which are the same and those are my neighbors
			var myNeighbors:Array = new Array();
            for (var b:int = 0; b < allPendingRequests.length; b++)
            {
				//if its NOT not there, aka if its there
                if (allPendingNeighbors.indexOf(allPendingRequests[b]) != -1)
                {
                    //they are both in my pending neighbors and their requests
					myNeighbors.push(allPendingRequests[b]);
                }
            }
			trace("myNeighbors = " + myNeighbors);
			 _userNeighborsController.changeNeighbors(myNeighbors);

			//from my neighbors, get the ones not my neighbors,
			//so they are just my requests or their requests
			var tempFriends:Array = new Array();
			var tempTypes:Array = new Array();
			for (var p:int = 0; p < allPendingNeighbors.length; p++)
            { 
				//if its not a neighbor, then its a request
                if (myNeighbors.indexOf(allPendingNeighbors[p]) == -1)

                {
                    tempFriends.push(allPendingNeighbors[p]); //add to friends array
					tempTypes.push("pending");	//add to types array
                }
            }
			trace("tempFriends = " + tempFriends);
			for (var r:int = 0; r < allPendingRequests.length; r++)
            { 
				//if its not a neighbor, then its a request
                if (myNeighbors.indexOf(allPendingRequests[r]) == -1)
                {
                    tempFriends.push(allPendingRequests[r]);
					tempTypes.push("request");
                }
            }
			trace("tempFriends = " + tempFriends);
			//now get all my itera friends
			//right now its all itera users
            var allIteraFriends:Array= downloaded.userFriends.split(",");
            var zeroFriend:String = allIteraFriends.pop();
			trace("allIteraFriends = " + allIteraFriends);
			
			//if its not in the neighbors or the current friends list, then add it
			
            for (var f:int = 0; f < allIteraFriends.length; f++)
            { 
			
                if ((myNeighbors.indexOf(allIteraFriends[f]) == -1) && (tempFriends.indexOf(allIteraFriends[f]) == -1))
                {
                    tempFriends.push(allIteraFriends[f]);
					tempTypes.push("friend");
                }

            }
            _userFriendsController.changeFriends(tempFriends);
            _userFriendsController.changeTypes(tempTypes);
			trace("tempFriends = " + tempFriends);
			trace("tempTypes = " + tempTypes);
			
			//karmas
			//get the different types of karma
            var returnedKarmas:Array = downloaded.returnedKarmas.split(",");
            var zeroReturned:String = returnedKarmas.pop();
            trace("returnedKarmas = " + returnedKarmas);
			
            var giftKarmas:Array =  downloaded.giftKarmas.split(",");
            var zeroGift:String = giftKarmas.pop();
            trace("giftKarmas = " + giftKarmas);
			
            var gotKarmas:Array = downloaded.gotKarmas.split(",");
            var zeroGot:String = gotKarmas.pop();
            trace("gotKarmas = " + gotKarmas);
			
			//add them to the karma array with the types
            var tempKarmas:Array = new Array();
            var karmaTypes:Array = new Array();
 			for (var gk:int = 0; gk < gotKarmas.length; gk++)
            { 
                tempKarmas.push(gotKarmas[gk]);
				karmaTypes.push("Received");
            }
			
			for (var rk:int = 0; rk < returnedKarmas.length; rk++)
            { 
                tempKarmas.push(returnedKarmas[rk]);
				karmaTypes.push("Returned");
            }
			
			for (var g:int = 0; g < giftKarmas.length; g++)
            { 
                tempKarmas.push(giftKarmas[g]);
				karmaTypes.push("Gift");
            }

            
			//if there are any received karmas, then open the received karma view button
            if (tempKarmas.length > 0)
            {
				trace("tempKarmas = " + tempKarmas);
				trace("karmaTypes = " + karmaTypes);
				_receiveKarmaController.changeReceivedKarmas(tempKarmas);
            	_receiveKarmaController.changeTypes(karmaTypes);
				
                gotKarmaBtn.addEventListener(MouseEvent.CLICK, openReceivedKarmaView);
                gotKarmaBtn.buttonMode = true;
                gotKarmaBtn.mouseChildren = false;
                gotKarmaBtn.alpha = 1;
                gotKarmaBtn.scaleX = 1;
            }
            openingCover.x = 1000;
            return;
        }// end function

		
////////// HELP SCREEN //
		private function closeHelpScreen(event:MouseEvent):void
		{
			trace("closing help screen");
			windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeHelpScreen);
			windowScreen.x = 1000;
			windowScreen.y = 1000;
		}

		private function showHelpScreen():void
		{
			trace("viewing help screen");
			windowScreen.x = 0;
			windowScreen.y = 30;
			addChild(windowScreen);
			windowScreen.gotoAndStop("help");
			windowScreen.windowTitleText.text = "Help Screen";
			windowScreen.windowContainer.y = 102.45;
			windowScreen.closeBtn.addEventListener(MouseEvent.CLICK, closeHelpScreen);
			
			//scroll bar
			
			_scrollBar.x = 680;
			_scrollBar.y = 110;
			//scrollbar
			scrollColorTransform.color = 0x4E3B31;
			_scrollBar.transform.colorTransform = scrollColorTransform;
			//scrolling
			_scrollBar.upBtn.addEventListener(MouseEvent.CLICK, scrollUp);
			_scrollBar.downBtn.addEventListener(MouseEvent.CLICK, scrollDown);
			_scrollBar.dragBtn.addEventListener(MouseEvent.MOUSE_DOWN, dragSlider);
			
		}
		
		//scrolling functions for help screen
		private function scrollUp(event:MouseEvent):void
		{
			for (var p:int=0; p<8; p++)
			{

				if ( (_scrollBar.dragBtn.y > 36 + (238/8*p)) && (_scrollBar.dragBtn.y <= 36 + (238/8)*(p+1)) )
				{
					trace("scrolling up at "+ p);
					//top of the container minus the scrolling distance
					windowScreen.windowContainer.y = 102.45 - (windowScreen.windowContainer.height-320)/8*(p);
					
					_scrollBar.dragBtn.y = 36 + (238/8)*p;
				}// end if
			}//end for loop
		}

		private function scrollDown(event:MouseEvent):void
		{

			trace("scrolling down");
			trace(windowScreen.windowContainer.y);
			trace(_scrollBar.dragBtn.y);
			for (var p:int=0; p<8; p++)
			{
				//trace("array = "+(274 - scrollDragPosYArray[p]));
				if ( (_scrollBar.dragBtn.y < 274 -(238/8*p)) && (_scrollBar.dragBtn.y >= 274 - (238/8)*(p+1) ) )
				{
					trace("scrolling down at "+ p);

					windowScreen.windowContainer.y = (422.45  -windowScreen.windowContainer.height) + (windowScreen.windowContainer.height-320)/8*p;
					_scrollBar.dragBtn.y = 274 - (238/8)*p;

				}//end if
			}//end for loop
		}

		private function dragSlider(event:MouseEvent):void
		{
			_scrollBar.dragBtn.removeEventListener(MouseEvent.MOUSE_DOWN, dragSlider);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, startDragging);
			stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);

		}

		private function startDragging(event:MouseEvent):void
		{
			//if the mouse is in range, go ahead and drag
			trace("mouseX = " +mouseX);
			trace("mouseY = " +mouseY);
			if ((mouseY >= 152) && (mouseY <= 390))
			{
				_scrollBar.dragBtn.y = mouseY - 116;
				var distY:Number = (_scrollBar.dragBtn.y - 36)/238;

				windowScreen.windowContainer.y = 102.45 - (windowScreen.windowContainer.height-320)*distY;
			}
		}

		private function stopDragging(event:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, startDragging);
			stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
			_scrollBar.dragBtn.addEventListener(MouseEvent.MOUSE_DOWN, dragSlider);
		}
		
		
////////// MINI MESSAGE //
		private function closeMiniMessage(event:MouseEvent):void
		{
			trace("closing mini message");
			miniMessage.okayBtn.removeEventListener(MouseEvent.CLICK, closeMiniMessage);
			miniMessage.okayBtn.removeEventListener(MouseEvent.CLICK, saveAvatarAndCloseMiniMessage);
			miniMessage.cancelBtn.removeEventListener(MouseEvent.CLICK, closeMiniMessage);
			miniMessage.x = 1000;
			miniMessage.y = 1000;
		}

		private function showMiniMessage(a_message:String):void
		{
			trace("viewing mini message");
			trace("the message is for: "+ a_message);
			miniMessage.x = 0;
			miniMessage.y = 0;
			miniMessage.cancelBtn.x = 426.65;
			addChild(miniMessage);
			switch(a_message)
			{
				case "levelUp":
				miniMessage.miniMessageText.text = "Congratulations! You just Leveled Up to Level " + _userModel.userLevel.toString();
                    miniMessage.miniMessageText.appendText("\n");
                    miniMessage.miniMessageText.appendText("You have now unlocked another Itera Spirit. Go to the Customize Menu to see what\'s been randomly unlocked!");
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
                    uploadUserInfo(_userStaticModel.userID);
				break;

				case "postLimit":
				miniMessage.miniMessageText.text = "Sorry. You already have 3 posts today.";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "noPosts":
				miniMessage.miniMessageText.text = "Looks like there are no posts from your neighbors. Try inviting some friend from Facebook or adding some new neighbors. Send some Daily Karma or Gift Karma as reminders to play Itera.";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "noMyPosts":
				miniMessage.miniMessageText.text = "Hey, you don't have any recent posts!";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "noNeighbors":
				miniMessage.miniMessageText.text = "Either all your friends playing Itera are already your neighbors, or they haven't had the pleasure of playing this fine game! Invite some more Facebook friends to play Itera with you.";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "karmaLimit":
                    miniMessage.miniMessageText.text = "Sorry. You already sent a daily karma to that person.";
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
                    break;
					
				case "responseKarmaLimit":
                    miniMessage.miniMessageText.text = "Sorry. That post already has 5 responses.";
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
					break;
					
				 case "Confirm Neighbor Request":
                    miniMessage.miniMessageText.text = "Please confirm that you want " + _neighborModel.neighborName + " to be your neighbor. This will be posted to their Wall.";
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, sendNeighborRequestAndClose);
                    miniMessage.cancelBtn.x = 526.65;
                    miniMessage.cancelBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
                    break;

                case "Confirm Karma Request":
                    miniMessage.miniMessageText.text = "Please confirm that you want to send Karma to " + _neighborModel.neighborName + ". This will be posted to their Wall.";
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, sendKarmaRequestAndClose);
                    miniMessage.cancelBtn.x = 526.65;
                    miniMessage.cancelBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
                    break;

                case "Welcome to Itera":
                    miniMessage.miniMessageText.text = "Welcome to Itera.";
                    miniMessage.miniMessageText.appendText("\n" + "You were invited by " + _invitedBy + "." + _invitedByID);
                    miniMessage.miniMessageText.appendText("\n" + "Would you like to take a tutorial of the game?");
                    miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
                    break;
				
				case "dqLimit":
				miniMessage.miniMessageText.text = "Sorry. You already used the daily quote.";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "avatarPriceHigh":
				miniMessage.miniMessageText.text = "Sorry. You don't have enough energy to spend " + _avatarPrice + " on your new Avatar. Try changing out different features.";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				case "avatarPrice":
				miniMessage.miniMessageText.text = "Are you sure you want to spend " + _avatarPrice + " on your new Avatar?";
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, saveAvatarAndCloseMiniMessage);
				miniMessage.cancelBtn.x = 526.65;
				miniMessage.cancelBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
				default:
				miniMessage.okayBtn.addEventListener(MouseEvent.CLICK, closeMiniMessage);
				break;
				
			}

		}
		
		private function openMainMenu():void
		{
			mainMenuBtn.gotoAndStop("on");
			mainMenu.scaleX =1;
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
		}
		
		private function goBackToMainMenu(event:MouseEvent):void
		{
			openMainMenu();
			mainMenuBtn.removeEventListener(MouseEvent.CLICK, goBackToMainMenu);
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeMainMenu);
		}
		
		private function closeMainMenu(event:MouseEvent):void
		{
			mainMenuBtn.removeEventListener(MouseEvent.CLICK, closeMainMenu);
			mainMenu.scaleX =0;
			
			//why do we close the main menu?
			switch(event.target.name)
			{
				case "myAvatarBtn":
				mainMenuBtn.gotoAndStop("Exit");
				openCustomizeView();
				break;
				
				case "myPostBtn":
				mainMenuBtn.gotoAndStop("off");
				mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
				openCreatePostView();
				break;
				
				case "viewPostsBtn":
				mainMenuBtn.gotoAndStop("off");
				mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
				downloadPostArray("0");
				break;
				
				case "sendKarmaBtn":
				mainMenuBtn.gotoAndStop("off");
				mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
				openSendKarmaView("mainMenu");
				break;
				
				case "dailyQuoteBtn":
				mainMenuBtn.gotoAndStop("off");
				mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
				openDailyQuoteView();
				break;
				
				default:
				mainMenuBtn.gotoAndStop("off");
				mainMenuBtn.addEventListener(MouseEvent.CLICK, goBackToMainMenu);
				break;
			}//end switch
		}
		
		
////////// MY POST VIEWS... DQ, CREATE and ALL MY POSTS //
		private function closeMyPostView(event:MouseEvent):void
		{
			trace("closing my post");
			switch(event.target.name)
			{
				case "dqBtn":
				myPost.dqBtn.removeEventListener(MouseEvent.CLICK, closeMyPostView);
				openDailyQuoteView();
				break;
				
				case "createBtn":
				myPost.createBtn.removeEventListener(MouseEvent.CLICK, closeMyPostView);
				openCreatePostView();
				break;
				
				case "viewMineBtn":
				myPost.viewMineBtn.removeEventListener(MouseEvent.CLICK, closeMyPostView);
				downloadPostArray(_userStaticModel.userID);
				break;
				
				case "mainMenuBtn":
				default:
				mainMenuBtn.removeEventListener(MouseEvent.CLICK, closeMyPostView);
				openMainMenu();
				break;
			}
				myPost.scaleX = 0;
				
		}

		private function openMyPostView():void
		{
			trace("viewing my post");
			myPost.scaleX = 1;
			myPost.thePost.text=_userPostModel.currentPost;
			myPost.responsesLeft.text = (5 - _userPostModel.currentResponses).toString() +" response(s) left!";
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeMyPostView);
			myPost.dqBtn.addEventListener(MouseEvent.CLICK, closeMyPostView);
			myPost.createBtn.addEventListener(MouseEvent.CLICK, closeMyPostView);
			myPost.viewMineBtn.addEventListener(MouseEvent.CLICK, closeMyPostView);
		}
		
		private function viewCurrentPost(event:Event):void
		{
			myPost.thePost.text=_userPostModel.currentPost;
			myPost.responsesLeft.text = (5 - _userPostModel.currentResponses).toString() +" response(s) left!";
		}

		private function closeCreatePostView(event:MouseEvent):void
		{
			trace("closing create post");
			switch(event.target.name)
			{
				case "dqBtn":
				createPost.dqBtn.removeEventListener(MouseEvent.CLICK, closeCreatePostView);
				openDailyQuoteView();
				break;
				
				case "cancelBtn":
				createPost.cancelBtn.removeEventListener(MouseEvent.CLICK, closeCreatePostView);
				openMyPostView();
				break;
				
				case "viewMineBtn":
				createPost.viewMineBtn.removeEventListener(MouseEvent.CLICK, closeCreatePostView);
				downloadPostArray(_userStaticModel.userID);
				break;
				
				case "mainMenuBtn":
				default:
				mainMenuBtn.removeEventListener(MouseEvent.CLICK, closeCreatePostView);
				openMainMenu();
				break;
			}
			createPost.scaleX = 0;
		}
		
		private function openCreatePostView():void
		{
			trace("viewing create post form");
			createPost.scaleX = 1;
			createPost.inputPost.text = "Add a new post?";
			//clear form
			createPost.inputPost.addEventListener(MouseEvent.CLICK, clearInputPostForm);
			createPost.submitBtn.addEventListener(MouseEvent.CLICK, mouseSubmitPost);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardSubmitPost);
			
			//closing this window
			createPost.cancelBtn.addEventListener(MouseEvent.CLICK, closeCreatePostView);
			createPost.dqBtn.addEventListener(MouseEvent.CLICK, closeCreatePostView);
			createPost.viewMineBtn.addEventListener(MouseEvent.CLICK, closeCreatePostView);
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeCreatePostView);
		}
		
		function clearInputPostForm(event:MouseEvent):void
		{
			createPost.inputPost.text = "";
		}
		
		function mouseSubmitPost(event:MouseEvent):void
		{
			createPost.submitBtn.removeEventListener(MouseEvent.CLICK, mouseSubmitPost);
			addNewPost();
		}
		
		function keyboardSubmitPost(event:KeyboardEvent):void
		{
			if (event.keyCode == Keyboard.ENTER)
   			{
       			 addNewPost();
   			}
		}
		
		private function addNewPost():void
		{
			if(createPost.inputPost.text == "" || createPost.inputPost.text == "Add a new post?" || createPost.inputPost.text == "There was no post!")
			{
				trace("no newPost");
				 createPost.inputPost.text = "There was no post!"
			}
			else
			{
				var newPost = createPost.inputPost.text;
				trace("newPost = "+ newPost);
				// createPost.inputPost.text = "Got your post!"
				createPost.scaleX = 0;
				
				openMyPostView();
				uploadNewPost(newPost, 0);
			}
		}
		
		//uploads the saved avatar to the correct userID
		private function uploadNewPost(a_theNewPost:String, a_dailyQuoteID:Number):void
		{
			//flash variables I'm sending with the urlrequest
			//php file can get the variable using $_POST["filename"]
			var uploadedVariables:URLVariables = new URLVariables;
			trace("uploading the new post!!!");
			trace(a_theNewPost);
			trace(a_dailyQuoteID);
			trace(_userStaticModel.userID);
			uploadedVariables.thePost = a_theNewPost;
			uploadedVariables.dailyQuote = a_dailyQuoteID;
			uploadedVariables.userID = _userStaticModel.userID;

			//trace("uploading = "+uploadedVariables);
			//the url request
			//the file should be a separate processing php file to connect with the database
			var uploadRequest = new URLRequest("http://www.itera-game.com/upload_new_post.php");

			uploadRequest.method = URLRequestMethod.POST;
			
			// the variables are added to the data to send to the php file
			uploadRequest.data = uploadedVariables;

			//the load will load the request
			var uploader = new URLLoader();
			uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
			//when it is loaded let me know (plus other stuff)
			uploader.addEventListener(Event.COMPLETE,doneUploadingNewPost);
			//load it
			try
            {
                uploader.load(uploadRequest);
            } 
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }

		}
		
		private function doneUploadingNewPost(event:Event):void
		{
			trace("uploaded");
			var checkLoader:URLLoader = URLLoader(event.target);
			var postVars:URLVariables = new URLVariables(checkLoader.data);
			trace(checkLoader.data);
			
			
			if(postVars.dqLimit == "true" )
			{
				showMiniMessage("dqLimit");
			}
			else if(postVars.postLimit == "true" )
			{
				showMiniMessage("postLimit");
			}
			else
			{
				_userPostController.changeCurrentResponses(0);
				_userPostController.changeCurrentPost(postVars.thePost);
				_userController.changeUserXP(_userModel.userXP+5);
				uploadUserInfo(_userStaticModel.userID);

			}

		}
		
		private function closeDailyQuoteView(event:MouseEvent):void
		{
			trace("closing daily quote");
			
			switch(event.target.name)
			{
				case "createBtn":
				dailyQuote.createBtn.removeEventListener(MouseEvent.CLICK, closeDailyQuoteView);
				openCreatePostView();
				break;
				
				case "cancelBtn":
				dailyQuote.cancelBtn.removeEventListener(MouseEvent.CLICK, closeDailyQuoteView);
				openMyPostView();
				break;
				
				case "viewMineBtn":
				dailyQuote.viewMineBtn.removeEventListener(MouseEvent.CLICK, closeDailyQuoteView);
				downloadPostArray(_userStaticModel.userID);
				break;
				
				case "mainMenuBtn":
				default:
				mainMenuBtn.removeEventListener(MouseEvent.CLICK, closeDailyQuoteView);
				openMainMenu();
				break;
			}
			dailyQuote.scaleX = 0;
			
		}

		private function openDailyQuoteView():void
		{
			trace("viewing daily quote");
			dailyQuote.scaleX = 1;
			dailyQuote.thePost.text = _dailyQuoteModel.dailyQuote;
			dailyQuote.useItBtn.addEventListener(MouseEvent.CLICK, useDailyQuote);
			dailyQuote.createBtn.addEventListener(MouseEvent.CLICK, closeDailyQuoteView);
			dailyQuote.cancelBtn.addEventListener(MouseEvent.CLICK, closeDailyQuoteView);
			dailyQuote.viewMineBtn.addEventListener(MouseEvent.CLICK, closeDailyQuoteView);
			mainMenuBtn.addEventListener(MouseEvent.CLICK, closeDailyQuoteView);

		}
		
		private function useDailyQuote(event:MouseEvent):void
		{
			dailyQuote.useItBtn.removeEventListener(MouseEvent.CLICK, useDailyQuote);
			uploadNewPost(_dailyQuoteModel.dailyQuote, _dailyQuoteModel.dailyQuoteID);
			dailyQuote.scaleX = 0;
			openMyPostView();
		}
		
		
		// INVITE //
		private function closeFriendsView(event:MouseEvent):void
		{
			trace("closing all friends");
			windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeFriendsView);
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			_friendsView.x = 4535;
			openMainMenu();
		}
		
		
		 private function uploadNewNeighborRequest() : void
        {
            var uploadedVariables:URLVariables = new URLVariables();
            trace("uploading friend as new neighbor = " + _neighborModel.neighborID + "for" + _userStaticModel.userID);
			
            uploadedVariables.userID = _userStaticModel.userID;
            uploadedVariables.iteraFriend = _neighborModel.neighborID;
			
            var uploadRequest:URLRequest = new URLRequest("http://www.itera-game.com/upload_neighbor_request.php");
            uploadRequest.method = URLRequestMethod.POST;
            uploadRequest.data = uploadedVariables;
			
            var uploader:URLLoader = new URLLoader();
            uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
            uploader.addEventListener(Event.COMPLETE, doneUploadingNewNeighborRequest);
            try
            {
                uploader.load(uploadRequest);
            }
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }

        }// end function
		
		private function doneUploadingNewNeighborRequest(event:Event):void
        {
			var checkLoader:URLLoader = URLLoader(event.target);
			trace(checkLoader.data);
			
			var jsArgument1:String = _userStaticModel.userName;
			var jsArgument2:String = checkLoader.data.friendFBID;
					
			if(checkLoader.data.areNeighbors == "yes")
			{
				trace("to JavaScript: add friend as new neighbor = " + _neighborModel.neighborID + "for" + _userStaticModel.userID);
					
					var result1:Object = ExternalInterface.call("addNeighborFromFlash",jsArgument1,jsArgument2);
					_friendsView.confirmNeighborSent(_neighborModel.neighborID);
			
			}
			else if(checkLoader.data.sentRequest == "yes")
			{
				trace("to JavaScript: request new neighbor = " + _neighborModel.neighborID + "for" + _userStaticModel.userID);
					
					var result2:Object = ExternalInterface.call("requestNeighborFromFlash",jsArgument1,jsArgument2);
					_friendsView.confirmNeighborSent(_neighborModel.neighborID);
			
			}
			 
			
			
		}
		private function sendNeighborRequestAndClose(event:MouseEvent) : void
        {
            miniMessage.okayBtn.removeEventListener(MouseEvent.CLICK, sendNeighborRequestAndClose);
            miniMessage.cancelBtn.removeEventListener(MouseEvent.CLICK, closeMiniMessage);
            miniMessage.x = 1000;
            miniMessage.y = 1000;
            uploadNewNeighborRequest();

        }// end function
		
		private function openAddNeighborView():void
		{
			windowScreen.x = 0;
			windowScreen.y = 30;
			addChild(windowScreen);
			windowScreen.gotoAndStop("friends");
			
			_friendsView.x = 45.35;
			_friendsView.y = 87.25;
			windowScreen.addChild(_friendsView);
			_userFriendsController.changeFriends(_userFriendsModel.friendsArray);
			_userFriendsController.changeTypes(_userFriendsModel.typesArray);
            windowScreen.windowTitleText.text = "Add Itera Friends as Neighbors";
            windowScreen.windowContainer.y=1000;
			_scrollBar.y = 1100;
            windowScreen.closeBtn.addEventListener(MouseEvent.CLICK, closeFriendsView);
		}

		private function openFacebookInviteWindow (event:MouseEvent):void
		{
			var jsArgument:String = _userStaticModel.userID;
			var result:Object = ExternalInterface.call("getInviteRequestFromFlash",jsArgument);

			trace("sending invites");
		}
		
		// ALL POSTS //
		private function closeAllPostsView(event:MouseEvent):void
		{
			trace("closing all posts");
			windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeAllPostsView);
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			_postsView.x = 4535;
			openMainMenu();
		}

		//uploads the saved avatar to the correct userID
		private function downloadPostArray(a_userID:String):void
		{
			//flash variables I'm sending with the urlrequest
			//php file can get the variable using $_POST["filename"]
			var uploadVars:URLVariables = new URLVariables;
			trace("getting the post array");
			uploadVars.userID = a_userID;

			//trace("uploading = "+uploadedVariables);
			//the url request
			//the file should be a separate processing php file to connect with the database
			var uploadRequest = new URLRequest("http://www.itera-game.com/download_post_array.php");

			uploadRequest.method = URLRequestMethod.POST;
			
			// the variables are added to the data to send to the php file
			uploadRequest.data = uploadVars;

			//the load will load the request
			var uploader = new URLLoader();
			uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
			//when it is loaded let me know (plus other stuff)
			uploader.addEventListener(Event.COMPLETE,doneDownloadingPostArray);
			//load it
			try
            {
                uploader.load(uploadRequest);
            } 
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }

		}
		
		private function doneDownloadingPostArray(event:Event):void
		{
			trace("downloaded");
			
			var checkLoader:URLLoader = URLLoader(event.target);
			trace(checkLoader.data);
			var postVars:URLVariables = new URLVariables(checkLoader.data);
			
			var tempPostArray:Array =  postVars.postIDs.split(",");
			trace("tempPostArray= "+tempPostArray);
			var noPost = tempPostArray.pop();
			trace("tempPostArray= "+tempPostArray);
				
			//set text
			if(postVars.userID == _userStaticModel.userID)
			{
				windowScreen.windowTitleText.text = "All My Posts";
				_userPostController.changeMyPosts("Mine");
				
				_postsController.changePosts(tempPostArray);
				openAllPostsView();
			}
			else if(postVars.userID =="0")
			{
				windowScreen.windowTitleText.text = "All Posts";
				_userPostController.changeMyPosts("Everyone");
				
				_postsController.changePosts(tempPostArray);
				openAllPostsView();

			}
			else
			{
				windowScreen.windowTitleText.text = "All of "+_neighborModel.neighborName +"\'s Posts";
				_userPostController.changeMyPosts(postVars.userID);

				_postsController.changePosts(tempPostArray);
				openNeighborPostsView();
			
			}

		}
		
		private function openAllPostsView():void
		{
			trace("viewing all posts");
			windowScreen.x = 0;
			windowScreen.y = 30;
			addChild(windowScreen);
			windowScreen.gotoAndStop("posts");
			
			_postsView.x = 45.35;
			_postsView.y = 87.25;
			windowScreen.addChild(_postsView);

			windowScreen.windowContainer.y=1000;
			_scrollBar.y = 1100;
			
			windowScreen.closeBtn.addEventListener(MouseEvent.CLICK, closeAllPostsView);
		}
		
		private function openNeighborPostsView():void
		{
			trace("opening neighbor posts view");
			_postsView.x = 45.35;
			_postsView.y = 113;
			addChild(_postsView);
		}
		
		// KARMA //
		private function closeSendKarmaView(event:MouseEvent):void
		{
			trace("closing send karma");
			windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeSendKarmaView);
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			_karmaView.x = 4535;
			openMainMenu();
		}
		
		private function sendKarmaRequestAndClose(event:MouseEvent) : void
        {
            miniMessage.okayBtn.removeEventListener(MouseEvent.CLICK, sendKarmaRequestAndClose);
            miniMessage.cancelBtn.removeEventListener(MouseEvent.CLICK, closeMiniMessage);
            miniMessage.x = 1000;
            miniMessage.y = 1000;
			
			windowScreen.closeBtn.removeEventListener(MouseEvent.CLICK, closeSendKarmaView);
			windowScreen.x = 1000;
			windowScreen.y = 1000;
			_karmaView.x = 4535;
			openMainMenu();
			
            uploadNewKarmaRequest();
           
        }// end function
		
		private function uploadNewKarmaRequest() : void
        {
            var uploadedVariables:URLVariables = new URLVariables();
            trace("uploading karma to  = " + _neighborModel.neighborID + "from" + _userStaticModel.userID);
            uploadedVariables.userID = _userStaticModel.userID;
            uploadedVariables.iteraFriend = _neighborModel.neighborID;
            uploadedVariables.karmaID = _sendKarmaModel.currentKarmaID;
            uploadedVariables.days = _karmaModel.karmaTimeArray[_sendKarmaModel.currentKarmaID];
            uploadedVariables.karmaName = _karmaModel.karmaArray[_sendKarmaModel.currentKarmaID];
            uploadedVariables.karmaImageName = uploadedVariables.karmaName.toLowerCase();
            uploadedVariables.postID = _sendKarmaModel.responseID;
			
            if (_sendKarmaModel.responseID == "0")
            {
                uploadedVariables.responseText = "";
            }
            else
            {
                uploadedVariables.responseText = _sendKarmaModel.responseText;
            }
            var uploadRequest:URLRequest = new URLRequest("http://www.itera-game.com/upload_karma_request.php");
            uploadRequest.method = URLRequestMethod.POST;
            uploadRequest.data = uploadedVariables;
            var uploader:URLLoader = new URLLoader();
            uploader.dataFormat = URLLoaderDataFormat.VARIABLES;
            uploader.addEventListener(Event.COMPLETE, doneUploadingNewKarmaRequest);
            try
            {
                uploader.load(uploadRequest);
            }
            catch (error:Error)
            {
                trace("Unable to load URL: " + error);
            }
			
        }// end function
		
		private function doneUploadingNewKarmaRequest(event:Event) : void
        {
            trace("uploaded");
            trace(event.target.data);
            var checkLoader:URLLoader = URLLoader(event.target);
            var downloaded:URLVariables = new URLVariables(checkLoader.data);

            trace("karmaLimit = " + downloaded.karmaLimit);
            trace("responseKarmaLimit = " + downloaded.responseKarmaLimit);
			trace("which karma = " + downloaded.whichKarma);
			
            if (downloaded.responseKarmaLimit == "true")
            {
                showMiniMessage("responseKarmaLimit");
            }
            else if (downloaded.karmaLimit == "true")
            {
                showMiniMessage("karmaLimit");
            }
			else 
			{
				//post it to the friends wall
				var jsArgument1:String = downloaded.karmaName;
				var jsArgument2:String = downloaded.karmaImageName;
				var jsArgument3:String = downloaded.days;
				var jsArgument4:String = downloaded.responseText;
				var jsArgument5:String = downloaded.thePost;
				var jsArgument6:String = _userStaticModel.userName;
				var jsArgument7:String = downloaded.friendFBID;
				
				if(downloaded.whichKarma == "daily")
				{
					var result1:Object = ExternalInterface.call("sendDailyKarmaFromFlash",jsArgument1,jsArgument2,jsArgument3,jsArgument6,jsArgument7);
				
				}
				else if(downloaded.whichKarma == "response")
				{
					var result2:Object = ExternalInterface.call("sendResponseKarmaFromFlash",jsArgument1,jsArgument2,jsArgument3,jsArgument4,jsArgument5,jsArgument6,jsArgument7);
				
				}
				_karmaView.x = 4535;
				windowScreen.x = 1000;
				windowScreen.y = 1000;
				openMainMenu();
				
			}
       
        }// end function
		
		 private function sendMultiKarmaRequest() : void
        {
            var jsArgument:String = _sendKarmaModel.currentKarmaID;
            var theCall = ExternalInterface.call("getKarmaRequestFromFlash", jsArgument);
            trace("sending karma request");

        }// end function

		private function openReceivedKarmaView(event:MouseEvent):void
		{
			openSendKarmaView("receivedKarmas");
		}
		
		private function openResponseKarmaView(toWho:String):void
		{
			trace("opening response karma view");
			_karmaView.x = 45.35;
			_karmaView.y = 190.25;
			addChild(_karmaView);
	
			windowScreen.windowTitleText.text = "Send a Response Karma to "+ toWho;
			_sendKarmaController.changeResponseID(_neighborModel.neighborPostID);
			//trace("chaing response id tp " + _neighborModel.neighborPostID);
			//_karmaController.loadKarmas();
			//_karmaView.viewKarmas();
		}

		private function openSendKarmaView(toWho:String):void
		{
			trace("viewing send karma");
			windowScreen.x = 0;
			windowScreen.y = 30;
			addChild(windowScreen);
			windowScreen.gotoAndStop("karma");
			
			_karmaView.x = 45.35;
			_karmaView.y = 87.25;
			windowScreen.addChild(_karmaView);
			_sendKarmaController.changeResponseID("0");
			
			
			//set text
			switch(toWho)
			{
				case "mainMenu":
				windowScreen.windowTitleText.text = "Send Gift Karma";
                _karmaController.loadKarmas();
                _sendKarmaController.changeReceiver("0");
				break;
			
				case "receivedKarmas":
				windowScreen.windowTitleText.text = "Congratulations! You Have Karma.";
                    //_receiveKarmaController.loadReceivedKarmas();
                    _sendKarmaController.changeReceiver("0");
				break;
				
				default:
				 windowScreen.windowTitleText.text = "Send a Daily Karma to " + toWho;
                    _karmaController.loadKarmas();
                    _sendKarmaController.changeReceiver(toWho);
				break;
			}
			windowScreen.windowContainer.y=1000;
			_scrollBar.y = 1100;
			
			//listen to close
			windowScreen.closeBtn.addEventListener(MouseEvent.CLICK, closeSendKarmaView);
			
			
		}
		
		// CUSTOMIZE //
		private function openCustomizeView():void
		{
			trace("openCustomizeView");
			_customizeController.createLockedArrays(_userLockedModel.userLockedAnimalNamesArray);
			_customizeView.y = 425;

			saveExitCustomizeBtn.x = 635;
			saveExitCustomizeBtn.y = 362;
			addChild(saveExitCustomizeBtn);
			saveExitCustomizeBtn.addEventListener(MouseEvent.CLICK, saveAndCloseCustomizeView);
			
			cancelCustomizeBtn.x = 700;
			cancelCustomizeBtn.y = 415;
			addChild(cancelCustomizeBtn);
			cancelCustomizeBtn.addEventListener(MouseEvent.CLICK, cancelCustomizeView);
			
		}

		private function closeCustomizeView():void
		{
			trace("closeCustomizeView");
			openMainMenu();
			saveExitCustomizeBtn.x = 6880;
			cancelCustomizeBtn.y = 6880;
			_customizeView.y = 1425;
		}
		
		private function cancelCustomizeView(event:MouseEvent):void
		{
			//remove listeners
			cancelCustomizeBtn.removeEventListener(MouseEvent.CLICK, cancelCustomizeView);
			_userAvatarController.changeSavedAvatarArray(_userAvatarModel.savedAvatarArray);
			//close view and back to main menu
			closeCustomizeView();
			
		}
		
		private function getAvatarPrice(a_avatarArray:Array):Number
		{
			//gets the price and updates the temporary bought parts and section arrays
			//clear the arrays
			_tempBoughtPartsSectionArray = new Array();
			_tempBoughtPartsArray = new Array();
			//clear the price
			_avatarPrice = 0;
			
			_avatarPrice += _customizeModel.faceShapePriceArray[a_avatarArray[0]];
			if(_customizeModel.faceShapePriceArray[a_avatarArray[0]] > 0)
			{
				//add the ids of the part and section to their temp arrays
				//sections are based on the avatarArray
				_tempBoughtPartsSectionArray.push(0);
				_tempBoughtPartsArray.push(a_avatarArray[0]);
			}
			_avatarPrice += _customizeModel.eyesPriceArray[a_avatarArray[1]];
			if(_customizeModel.eyesPriceArray[a_avatarArray[1]] > 0)
			{
				_tempBoughtPartsSectionArray.push(1);
				_tempBoughtPartsArray.push(a_avatarArray[1]);
			}
			_avatarPrice += _customizeModel.nosePriceArray[a_avatarArray[2]];
			if(_customizeModel.nosePriceArray[a_avatarArray[2]] > 0)
			{
				_tempBoughtPartsSectionArray.push(2);
				_tempBoughtPartsArray.push(a_avatarArray[2]);
			}
			_avatarPrice += _customizeModel.earsPriceArray[a_avatarArray[3]];
			if(_customizeModel.earsPriceArray[a_avatarArray[3]] > 0)
			{
				_tempBoughtPartsSectionArray.push(3);
				_tempBoughtPartsArray.push(a_avatarArray[3]);
			}
			_avatarPrice += _customizeModel.mouthPriceArray[a_avatarArray[4]];
			if(_customizeModel.mouthPriceArray[a_avatarArray[4]] > 0)
			{
				_tempBoughtPartsSectionArray.push(4);
				_tempBoughtPartsArray.push(a_avatarArray[4]);
			}
			_avatarPrice += _customizeModel.browsPriceArray[a_avatarArray[5]];
			if(_customizeModel.browsPriceArray[a_avatarArray[5]] > 0)
			{
				_tempBoughtPartsSectionArray.push(5);
				_tempBoughtPartsArray.push(a_avatarArray[5]);
			}
			_avatarPrice += _customizeModel.hairPriceArray[a_avatarArray[6]];
			if(_customizeModel.hairPriceArray[a_avatarArray[6]] > 0)
			{
				_tempBoughtPartsSectionArray.push(6);
				_tempBoughtPartsArray.push(a_avatarArray[6]);
			}
			_avatarPrice += _customizeModel.skinColorPriceArray[a_avatarArray[7]];
			if(_customizeModel.skinColorPriceArray[a_avatarArray[7]] > 0)
			{
				_tempBoughtPartsSectionArray.push(7);
				_tempBoughtPartsArray.push(a_avatarArray[7]);
			}
			_avatarPrice += _customizeModel.eyeColorPriceArray[a_avatarArray[8]];
			if(_customizeModel.eyeColorPriceArray[a_avatarArray[8]] > 0)
			{
				_tempBoughtPartsSectionArray.push(8);
				_tempBoughtPartsArray.push(a_avatarArray[8]);
			}
			_avatarPrice += _customizeModel.hairColorPriceArray[a_avatarArray[9]];
			if(_customizeModel.hairColorPriceArray[a_avatarArray[9]] > 0)
			{
				_tempBoughtPartsSectionArray.push(9);
				_tempBoughtPartsArray.push(a_avatarArray[9]);
			}
			_avatarPrice += _customizeModel.clothingColorPriceArray[a_avatarArray[10]];
			if(_customizeModel.clothingColorPriceArray[a_avatarArray[10]] > 0)
			{
				_tempBoughtPartsSectionArray.push(10);
				_tempBoughtPartsArray.push(a_avatarArray[10]);
			}
			_avatarPrice += _customizeModel.clothingColorPriceArray[a_avatarArray[11]];
			if(_customizeModel.clothingColorPriceArray[a_avatarArray[11]] > 0)
			{
				_tempBoughtPartsSectionArray.push(11);
				_tempBoughtPartsArray.push(a_avatarArray[11]);
			}
			_avatarPrice += _customizeModel.topClothingPriceArray[a_avatarArray[12]];
			if(_customizeModel.topClothingPriceArray[a_avatarArray[12]] > 0)
			{
				_tempBoughtPartsSectionArray.push(12);
				_tempBoughtPartsArray.push(a_avatarArray[12]);
			}
			_avatarPrice += _customizeModel.bottomClothingPriceArray[a_avatarArray[13]];
			if(_customizeModel.bottomClothingPriceArray[a_avatarArray[13]] > 0)
			{
				_tempBoughtPartsSectionArray.push(13);
				_tempBoughtPartsArray.push(a_avatarArray[13]);
			}
			_avatarPrice += _customizeModel.headExtraPriceArray[a_avatarArray[14]];
			if(_customizeModel.headExtraPriceArray[a_avatarArray[14]] > 0)
			{
				_tempBoughtPartsSectionArray.push(14);
				_tempBoughtPartsArray.push(a_avatarArray[14]);
			}
			_avatarPrice += _customizeModel.backExtraPriceArray[a_avatarArray[15]];
			if(_customizeModel.backExtraPriceArray[a_avatarArray[15]] > 0)
			{
				_tempBoughtPartsSectionArray.push(15);
				_tempBoughtPartsArray.push(a_avatarArray[15]);
			}
			_avatarPrice += _customizeModel.seatPriceArray[a_avatarArray[16]];
			if(_customizeModel.seatPriceArray[a_avatarArray[16]] > 0)
			{
				_tempBoughtPartsSectionArray.push(16);
				_tempBoughtPartsArray.push(a_avatarArray[16]);
			}
			_avatarPrice += _customizeModel.itemPriceArray[a_avatarArray[17]];
			if(_customizeModel.itemPriceArray[a_avatarArray[17]] > 0)
			{
				_tempBoughtPartsSectionArray.push(17);
				_tempBoughtPartsArray.push(a_avatarArray[17]);
			}
			_avatarPrice += _customizeModel.bkgPriceArray[a_avatarArray[18]];
			if(_customizeModel.bkgPriceArray[a_avatarArray[18]] > 0)
			{
				_tempBoughtPartsSectionArray.push(18);
				_tempBoughtPartsArray.push(a_avatarArray[18]);
			}
			_avatarPrice += _customizeModel.bkgColorPriceArray[a_avatarArray[19]];
			if(_customizeModel.bkgColorPriceArray[a_avatarArray[19]] > 0)
			{
				_tempBoughtPartsSectionArray.push(19);
				_tempBoughtPartsArray.push(a_avatarArray[19]);
			}
			trace("_avatarPrice = " + _avatarPrice);
			return _avatarPrice;
			
		}
		
		private function changeCustomizePrices():void
		{
			//change the prices in customize view
			for(var p:int = 0; p<_userAvatarModel.boughtPartsArray.length; p++)
			{
					_customizeController.adjustPriceArrays(_userAvatarModel.boughtPartsSectionArray[p],_userAvatarModel.boughtPartsArray[p]);
			}
		}

		private function saveAvatarAndCloseMiniMessage(event:MouseEvent):void
		{
			//remove listeners
			miniMessage.cancelBtn.removeEventListener(MouseEvent.CLICK, closeMiniMessage);
			miniMessage.okayBtn.removeEventListener(MouseEvent.CLICK, saveAvatarAndCloseMiniMessage);
			miniMessage.x = 1000;
			miniMessage.y = 1000;
			
			saveExitCustomizeBtn.removeEventListener(MouseEvent.CLICK, saveAndCloseCustomizeView);
			//chang the energy
			_userController.changeUserEnergy(_userModel.userEnergy - _avatarPrice);
			
			//upload saved avatar
            uploadSavedAvatar(_userStaticModel.userID);
            _userAvatarController.changeSavedAvatarArray(createCurrentAvatarArray());
			
			//adjust prices on which items were bought
			_userAvatarController.changeBoughtPartsSectionArray(_tempBoughtPartsSectionArray);
			_userAvatarController.changeBoughtPartsArray(_tempBoughtPartsArray);
			changeCustomizePrices();
			
			//close view and back to main menu
			closeCustomizeView();
			
		}
		
		private function saveAndCloseCustomizeView(event:MouseEvent):void
		{
			
			//save and upload to database
			if(getAvatarPrice(createCurrentAvatarArray()) > _userModel.userEnergy)
			{
				//show warning first
				showMiniMessage("avatarPriceHigh");
			}
			else if(getAvatarPrice(createCurrentAvatarArray()) > 0)
			{
				//show warning first
				showMiniMessage("avatarPrice");
			}
			else
			{
				//remove listeners
				saveExitCustomizeBtn.removeEventListener(MouseEvent.CLICK, saveAndCloseCustomizeView);
                uploadSavedAvatar(_userStaticModel.userID);
                _userAvatarController.changeSavedAvatarArray(createCurrentAvatarArray());
			
				//close view and back to main menu
				closeCustomizeView();
			}
		}

////////// PAN AND ZOOM FEATURES
		private function addZoomFeature():void
		{
			//reset variables
			zoomDragBtn.y = ZOOMBARMIDDLE;
			avatarHolder.mainCircle.alpha = 0;
			//handCursor.gotoAndStop("open");
			//handCursor.scaleX = 0.6;
			//handCursor.scaleY = 0.6;
			
			//listen
			zoomPlusBtn.addEventListener(MouseEvent.CLICK, zoomIn);
			zoomMinusBtn.addEventListener(MouseEvent.CLICK, zoomOut);
			zoomDragBtn.addEventListener(MouseEvent.MOUSE_DOWN, zoomStartDrag);
			
			//button mode
			zoomPlusBtn.buttonMode = true;
			zoomMinusBtn.buttonMode = true;
			zoomDragBtn.buttonMode = true;

			avatarHolder.addEventListener(MouseEvent.MOUSE_OVER, showHover);
			avatarHolder.addEventListener(MouseEvent.MOUSE_OUT, hideHover);
			avatarHolder.addEventListener(MouseEvent.MOUSE_DOWN, startPan);
			avatarHolder.addEventListener(MouseEvent.MOUSE_UP, stopPan);
			
		}
		
		private function showHover(event:MouseEvent):void
		{

			avatarHolder.mainCircle.alpha = 0.1;
			//handCursor.x = mouseX;
			//handCursor.y = mouseY;
			//Mouse.hide();
			//handCursor.mouseEnabled = false;
			//handCursor.mouseChildren = false;

		}
		
		private function hideHover(event:MouseEvent):void
		{
			avatarHolder.mainCircle.alpha = 0;
			//handCursor.x = -500;
			//handCursor.y = -500
			//Mouse.show();
		}
		
		private function startPan(event:MouseEvent):void
		{
			avatarHolder.startDrag();
			avatarHolder.mainCircle.alpha = 0.25;
			//handCursor.gotoAndStop("closed");
			//handCursor.x = mouseX;
			//handCursor.y = mouseY;
		}
		
		private function stopPan(event:MouseEvent):void
		{
			avatarHolder.stopDrag();
			//handCursor.gotoAndStop("open");
			//avatarHolder.mainCircle.alpha = 0;
		}
		
		private function zoomIn(event:MouseEvent):void
		{
			if(zoomDragBtn.y >= 283)
			{
				avatarHolder.scaleX = 0.8;
				avatarHolder.scaleY = 0.8;
				zoomDragBtn.y = ZOOMBARMIDDLE;
			}
			else
			{
				zoomDragBtn.y = 232.3;
				var bigZoomY:Number = ZOOMBARMIDDLE - zoomDragBtn.y
				avatarHolder.scaleX = 0.8 +bigZoomY/10;
				avatarHolder.scaleY = 0.8 +bigZoomY/10;
			}

		}
		
		private function zoomOut(event:MouseEvent):void
		{
			trace(zoomDragBtn.y);
			if(zoomDragBtn.y <= 233)
			{
				avatarHolder.scaleX = 0.8;
				avatarHolder.scaleY = 0.8;
				zoomDragBtn.y = ZOOMBARMIDDLE;
				avatarHolder.x = 380;
				avatarHolder.y = 316;
			}
			else
			{
				zoomDragBtn.y = 284.3;
				var smallZoomY:Number = ZOOMBARMIDDLE - zoomDragBtn.y
				avatarHolder.scaleX = 0.8 +smallZoomY/55;
				avatarHolder.scaleY = 0.8 +smallZoomY/55;
				avatarHolder.x = 380;
				avatarHolder.y = 316;
			}

			
		}
		
		private function zoomStartDrag(event:MouseEvent):void
		{
			zoomDragBtn.removeEventListener(MouseEvent.MOUSE_DOWN, zoomStartDrag);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, zoomStartDragging);
			stage.addEventListener(MouseEvent.MOUSE_UP, zoomStopDragging);
			//trace("button = " + zoomDragBtn.y);
			

		}
		
		private function zoomStartDragging(event:MouseEvent):void
		{
			if((mouseY >= 233) && (mouseY <= 283))
			{
				//zoomDragBtn.startDrag(false);
				zoomDragBtn.x = 730.85;
				//zoomDragBtn.y = mouseY;
				//trace("button = " + zoomDragBtn.y);
				//trace("mouse = " + mouseY);
				
				// establish distance from mouse
				zoomDragY = mouseY-zoomDragBtn.y;
				// move toward mouse (gets slower as it approaches mouse);
				// changing the divisor yields different speeds
				zoomDragBtn.y += zoomDragY;
				zoomY = ZOOMBARMIDDLE - zoomDragBtn.y;
				var tempX:Number = avatarHolder.x - 380;
				var tempY:Number = avatarHolder.y - 316;
				if(zoomDragY >=0)
				{
					avatarHolder.x -= tempX/10;
					avatarHolder.y -= tempY/10;
				}
				//trace(zoomY);
				if(zoomY >=0)
				{
					avatarHolder.scaleX = 0.8 +zoomY/10;
					avatarHolder.scaleY = 0.8 +zoomY/10;
					
				}
				else
				{
					avatarHolder.scaleX = 0.8 +zoomY/55;
					avatarHolder.scaleY = 0.8 +zoomY/55;
				}
				
				
			}
		}

		private function zoomStopDragging(event:MouseEvent):void
		{
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, zoomStartDragging);
			stage.removeEventListener(MouseEvent.MOUSE_UP, zoomStopDragging);
			zoomDragBtn.addEventListener(MouseEvent.MOUSE_DOWN, zoomStartDrag);
			
		}

	}//end class
}//end package