LOVEDirector = new Class({

	initialize: function(){
		this.currentScene;              
        this.previousScene;
		this.name = 'Director';

		// GLOBALS
		// TODO: use a singleton / separate class instead?
		GLOBAL = [];
 		GLOBAL['zcounter'] = 0;

 		this.Scenes = [];
		this.versions = ['Full','Low'];
		this.version = 'Full';//by default
        this.creditGIFarray = [];
		spinner = undefined;
		this.isSwirling = false;
		
		$('overlay').set('morph', {
			duration: 1250,
			link: 'cancel'
		});

	},



/*

BEGIN APP 
PRELOAD CONTENT THEN SHOW

*/


	startApp: function() {
 
		// initialise all controllers
		EventController = new LOVEEventController(this.version);
		LogoController = new LOVELogoController(this.version);
 		Scene_Feature = new LOVEFeatureController(this.version);
		Scene_Wall = new LOVESceneController(this.version);
		Scene_Cover = new LOVECoverController(this.version);
		Scene_Post = new LOVEScenePostController(this.version);
		Scene_Archive = new LOVEArchiveController(this.version);
		Scene_Search = new LOVESearchController(this.version);
 		(Browser.Platform.ios)? iosController = new LOVEIOSController(this.version): iosController='';
 
 
  		this.Scenes = {
			Feature : Scene_Feature,
			Wall : Scene_Wall,
			Cover: Scene_Cover,
			Post:Scene_Post,
			Archive: Scene_Archive,
			updateVersion : function(version){
				var Scenes = Director.Scenes;
				for(scene in Scenes) {
					if(typeOf(Scenes[scene])!="function") Scenes[scene].directorDidChangeVersionControl(version);
				}
			}
		};
  		this.preloadSplash();
		
		if(Browser.Platform.ios){
			$('featured').destroy();
			$('mainNav-versioning').view('hide');
		}else if(Browser.firefox3 || Browser.ie7 || Browser.ie6 || Browser.safari4 || Browser.opera){
			$('mainNav-versioning').view('hide');
			this.userDidChangeVersionControl();
		}else{ $('mainNav-versioning').view('show'); }
	 
	},



	preloadSplash: function() {
		var myImages = Asset.images(['img/spinner.gif', 'img/logo/logo_love.png', 'img/logo/love_exploding.gif', 'img/nav/navbits.png?new'], {
			onComplete: function() {
					spinner = new Spinny;
 					// show splash screen
					this.showSplash();
 					// preload flowplayer
					Scene_Feature.loadFlowPlayer();

			}.bind(this)
  
		});
	},
 

	showSplash: function() {
   		LogoController.showInitial();
 		spinner.setSpin('middle',{x: 0, y:100});
		spinner.show();
		$('love-logo').view('in');
	},

	hideSplash: function() {
  		spinner.hide();
 	},



	flowPlayerDidLoadAtLaunchHandler: function(){
	
  		Scene_Feature.showsubScene(Scene_Feature.subScene_BACKGROUND);
		
	},
	
	iosFirstImageDidLoadAtLaunchHandler: function(){
	
		Scene_Feature.showsubScene(Scene_Feature.subScene_BACKGROUND);
		Director.firstVideoHasStarted();
		iosController.presentiosBackgroundGallery();

	},
	
	
	firstVideoHasStarted: function() {
		
		//Called when a Video has started playing (only once!)
 		Scene_Feature.VideoController.hasStarted = true;
 		// fade in video
		$('video-container').morph({
			opacity: [0, 1]
		});

		// wait before removing splash / resuming app as normal
		setTimeout(function() {
 			// hide splash
			this.hideSplash();
 			// this will get called when video controls and swf is loaded
			this.hashChangeHandler(document.location.hash);

		}.bind(this), 2000);
	},	
	
	
 
	videoDidStartHandler: function() {
 
 		var hash = document.location.hash;
		var lastIndex = hash.lastIndexOf("=");
		if (lastIndex > 0) {
			var hashID = hash.substr(lastIndex+1);
			// strip ID from hash
			hash = hash.substr(0, lastIndex+1);
		}
 
		switch(hash.toLowerCase()) {
		
			case LovePages.PAGE_SEARCH:
 			break;

			case LovePages.PAGE_ISSUE_6:
 			break;

			case LovePages.POSTS:
 			break;

 			default:
                $f("Feature_Video").stop();
				$f("Feature_Video").play();
			break;
			
 		}
	},
	
	
	

/*

SO BEFORE THIS POINT THE VIDEO, SPINNER + LOGO ARE PRESENTED AND PLAYING
WAIT 2000 BEFORE INTERPRETING SCENE

*/
 	/**
	 * Called when the browser URL hash changes
	 */

	hashChangeHandler: function(hash) {
 
		var scene;
		/*if(!hash.contains('#')) hash = "#"+ hash;
 		// determine trailing IDs
		var lastIndex = hash.lastIndexOf("=");
		if (lastIndex > 0) {
			var hashID = hash.substr(lastIndex+1);

			// strip ID from hash
			hash = hash.substr(0, lastIndex+1);
		}*/
		
				
		// get first URL segment (after hash)
		var page_fragment;

		if (hash) {
			page_fragment = hash.split("/")[1];
		} else {
			// no hash found, default to daily
			page_fragment = '';
		}
 
		switch(page_fragment.toLowerCase()) {

			case LovePages.PAGE_ARCHIVE:

				scene = Scene_Archive;
				this.swapScenes(scene);

				// resume video
				Scene_Feature.resumeFeature();

				Scene_Wall.updateNav(LovePages.PAGE_ARCHIVE);

				break;

			case LovePages.PAGE_BACKSTAGE:

				scene = Scene_Wall;

				this.swapScenes(scene);
 					Scene_Wall.fetchPostsByTag('lveBoo');
 
				// resume video
				Scene_Feature.resumeFeature();

				Scene_Wall.updateNav(LovePages.PAGE_BACKSTAGE);

				break;

			case LovePages.PAGE_FEATURED:

				scene = Scene_Feature;

				this.swapScenes(scene);

				Scene_Wall.updateNav(LovePages.PAGE_FEATURED);

				break;

			case LovePages.PAGE_INSTANT:

				scene = Scene_Wall;

				this.swapScenes(scene);
//				if (Scene_Wall.currentFilterTag != 'lveInstant') {
					Scene_Wall.fetchPostsByTag('lveInstant');
//				}

				// resume video
				Scene_Feature.resumeFeature();

				Scene_Wall.updateNav(LovePages.PAGE_INSTANT);

				break;

			case LovePages.POST:
				scene = Scene_Post;
				// strip first URL fragment
				var firstFragment = "#!/" + LovePages.POST;

				// obtain post ID
				var secondFragment = location.hash.split("/")[2];
				var hashID = secondFragment;
				Scene_Post.showPost(hashID);
				// only swap if the scene has changed
				if(Director.currentScene && Director.currentScene.name == 'Wall') {
					this.swapScenes(scene);
				}
 
				// pause video
				Scene_Feature.pauseFeature();

				Scene_Wall.updateNav(LovePages.POST);

				break;

			case LovePages.PAGE_ISSUE_6:

				scene = Scene_Cover;
				this.swapScenes(scene);

				// pause video
				Scene_Feature.pauseFeature();

				Scene_Wall.updateNav(LovePages.PAGE_ISSUE_6);

				break;

			case LovePages.PAGE_SEARCH:

				scene = Scene_Search;

				this.swapScenes(scene);

				// pause video
				Scene_Feature.pauseFeature();

				Scene_Wall.updateNav(LovePages.PAGE_SEARCH);

				break;

			case LovePages.PAGE_SEARCH_RESULTS:
				if (Scene_Search.resultsNum > 0) {
					scene = Scene_Wall;

					this.swapScenes(scene);

  					// resume video
					Scene_Feature.resumeFeature();
				} else {
					// redirect to search page
					this.loadPage(LovePages.PAGE_SEARCH);
				}

				Scene_Wall.updateNav(LovePages.PAGE_SEARCH_RESULTS);
				break;


			case LovePages.PAGE_DAILY:
			  
				scene = Scene_Wall;
				this.swapScenes(scene);
				Scene_Wall.fetchPostsByTag('lveDaily');
				Scene_Feature.resumeFeature();
				Scene_Wall.updateNav(LovePages.PAGE_DAILY);
				break;
				
			default:
				scene = Scene_Wall;
				this.swapScenes(scene);
 				Scene_Feature.resumeFeature();
 				break;
	 
		}
	},
	
	
		
	
	loadPage: function($targetPage) {

		// TODO: replace this with proper implementation
		switch ($targetPage) {

			case "":
				scene = Scene_Wall;

				this.swapScenes(scene);
				if (Scene_Wall.currentFilterTag != 'lveDaily') {
					Scene_Wall.fetchPostsByTag('lveDaily');
				}

				break;

			case LovePages.PAGE_ARCHIVE:
				window.sethash("!/"+LovePages.PAGE_ARCHIVE);
				//window.location.hash=("!/"+lovePages.PAGE_BACKSTAGE);
				break;
                
			case LovePages.PAGE_BACKSTAGE:
				window.sethash("!/"+LovePages.PAGE_BACKSTAGE);
				//window.location.hash=("!/"+lovePages.PAGE_BACKSTAGE);
				break;

			case LovePages.PAGE_DAILY:
				window.sethash("!/"+LovePages.PAGE_DAILY);
				//window.location.hash=("!/"+lovePages.PAGE_DAILY);
				break;

			case LovePages.PAGE_INSTANT:
				window.sethash("!/"+LovePages.PAGE_INSTANT);
				//window.location.hash=("!/"+lovePages.PAGE_INSTANT);
				break;

			case LovePages.PAGE_SEARCH:
				window.sethash("!/"+LovePages.PAGE_SEARCH);
				//window.location.hash=("!/"+lovePages.PAGE_SEARCH);
				break;

			case LovePages.PAGE_SEARCH_RESULTS:
				window.sethash("!/"+LovePages.PAGE_SEARCH_RESULTS);
				//window.location.hash=("!/"+lovePages.PAGE_SEARCH_RESULTS);
				break;
 
  
		}
	},

	loadPost: function($postID, $postTitle) {
		if(Scene_Post.isAnimating) return;
 		if(!$postTitle) $postTitle ='';
		window.sethash("!/"+LovePages.POST+"/"+$postID+"/"+$postTitle);
 	},
	
		
			


	loadLastPage: function($scene) {

        if($scene){
            if($scene == Scene_Archive){
                window.sethash("!/"+LovePages.PAGE_ARCHIVE);
                Scene_Post.closeScene();
             return;
            }
            if($scene == Scene_Feature){
                window.sethash("!/"+LovePages.PAGE_FEATURED);
                Scene_Post.closeScene();
             return;
            }
        
        }
        
 		if (Scene_Wall.currentFilterTag) {
			switch (Scene_Wall.currentFilterTag) {
				case "lveInstant":
					Director.loadPage(LovePages.PAGE_INSTANT);
					break;
				case "lveBoo":
					Director.loadPage(LovePages.PAGE_BACKSTAGE);
					break;
				case "lveDaily":
					Director.loadPage(LovePages.PAGE_DAILY);
					break;
			}
		} else {
			Director.loadPage(LovePages.PAGE_DAILY);
		}
        if(!this.currentScene) Scene_Post.closeScene();
 	},
	
	
	
	

	swapScenes: function($scene) {
		

		// Close the current scene and pass in who closed in
		if (this.currentScene && this.currentScene != $scene) { 
  			(this.currentScene).closeScene($scene); 
		}
        this.previousScene = this.currentScene;
		// show new scene
        // if (this.currentScene) console.warn("*** LOVEDirector.swapScenes() current scene: "+this.currentScene.name);
        if (!this.currentScene || this.currentScene != $scene) { 
            
            (this.currentScene) = $scene;
            (this.currentScene).PresentScene($scene);
            // update logo
            LogoController.PresentScene($scene);
        }
	},
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	/**
	 * EVENT HANDLERS
	 */

	archiveCloseHandler: function() {
  
		this.loadLastPage();
	},

 

	coversCloseHandler: function() {
		// load last tag page
		this.loadLastPage();
	},

	featureCloseHandler: function() {
		// load last tag page
		this.loadLastPage();
	},

	postCloseHandler: function() {
         Director.loadLastPage(Director.currentScene);
	},

 
	searchCloseHandler: function() {
 
		this.loadLastPage();
	},

	searchHandler: function() {
 
		// load new page and have it managed by hash change handler
		this.loadPage(LovePages.PAGE_SEARCH_RESULTS);
	},
 
 
 

 
 










































/*

EXTRA COMMON FUNCTIONS

*/


 
 


	resizeStartHandler: function() {
	
		// show overlay
		if(Browser.Platform.ios ) return;
		$('overlay').set('morph', {
			duration: 750,
			link: 'cancel'
		});
		$('overlay').setStyles({
			'opacity': 1.0,
			'display': 'block'
		});

		// pause video
		Scene_Feature.VideoController.pauseVideo();
	},



	resizeHandler: function() {
		// Center the preloader
		if(spinner)spinner.center();
	},



	resizeCompleteHandler: function() {
  
		// fade out overlay
 
		if( ! Browser.Platform.ios )
		{
			$('overlay').morph({
				'opacity': 0.0
			}).chain(function() {
				$('overlay').view('hide');
			});
			Scene_Wall.directorDidRequestResize();
			Scene_Feature.directorDidRequestResize();
			Scene_Post.directorDidRequestResize();
			Scene_Archive.directorDidRequestResize();
			Scene_Search.directorDidRequestResize();
			Scene_Cover.directorDidRequestResize();
			// resume video
			Scene_Feature.VideoController.resumeVideo();
		
		}
	},


	resizeCompleteHandler_ios: function()
	{
		$('overlay').view('show');
  		Scene_Wall.directorDidRequestResize();
		Scene_Feature.directorDidRequestResize();
		Scene_Post.directorDidRequestResize();
		Scene_Archive.directorDidRequestResize();
		Scene_Search.directorDidRequestResize();
		Scene_Cover.directorDidRequestResize();
		iosController.directorDidRequestResize();
		$('overlay').view(0);
 	 
	},
 
 
 	// FOOTER LINKS
	PresentFooterLink: {
		Credit: {
			start: function() {
				var gify =  new LOVEExtraController();
				Director.creditGIFarray.push(gify);
				$('Credits-close').view(1);
 			},
			
 			close : function() {
				var a = Director;
				a.creditGIFarray.each(function(item,index){
					item.popMe.delay(index*100, {'self':item});
				});
				setTimeout(function(){
					a.creditGIFarray.empty();
					a.creditGIFarray = [];
				}, a.creditGIFarray.length *101);
				$('Credits-close').view(0);
   			}
 		}
	},
	
	
		
	focusHandler: function() {
		// TODO: only resume video on certain sections
		// e.g. if the video is paused
 
		switch (this.currentScene) {
			case Scene_Wall:
 
				break;
		}

		// resume video
		Scene_Feature.VideoController.resumeVideo();
	},
	blurHandler: function() {

 
		// pause video
		Scene_Feature.VideoController.pauseVideo();

 
	},
					

	//VERSIONING
     userDidChangeVersionControl : function(event){
        if(event) event.preventDefault();
        Director.versions.reverse();
        Director.version = Director.versions[0];
        $('mainNav-versioning').set('html',Director.versions[1]+' version');
        Director.Scenes.updateVersion(this.version);
     },



	 

	//EFFECTS AND TRYOUTS//
 
	setup_swirl_effect : function() {
		Director.isSwirling = true;
		R=0; x1=.1; y1=.05; x2=.25; y2=.24; x3=1.6; y3=.24; x4=300; y4=200; x5=300; y5=200;  
        swirlspacing = 200;
		$$('img').set('class','');
		$$('.Covers-imagesContainers').destroy();

		$('love-logo').inject('love_body','bottom').setStyles({'z-index':90000,'display':'inline-block','position':'absolute','margin-left':-200});
		$$('img').inject('love_body','bottom').setStyles({'z-index':90000,'display':'inline','position':'absolute'});
		$$('.post-item-container').destroy();
		DI = document.getElementsByTagName("img"); 
		DIL = DI.length;
		setInterval('Director.make_swirl_effect()',5);
		
		
		document.onmousemove = function(e) {
			var event = e || window.event;
			window.mouseY = event.clientY;
			window.mouseX = event.clientX;
 
		};
		
	},
	

	make_swirl_effect : function()
	{
	
		// x4 = window.mouseX;
		// x5 = window.mouseX;
		// y5 = window.mouseY;
		 for(i=0; i-DIL; i++){
             DIS=DI[ i ].style;
             //DIS.position='absolute'; 
             DIS.left=((Math.sin(R*x1+i*x2+x3)*x4+x5)  + (swirlspacing*2))+"px"; 
             DIS.top=((Math.cos(R*y1+i*y2+y3)*y4+y5) + swirlspacing)+"px"
         }
         R++		  
		 void(0);
	}
});
