frontRowSection = Class.create();
Object.extend(Object.extend(frontRowSection.prototype, AC.FrontRowSection.prototype), {

	activate: function() {
		Element.addClassName(this.trigger, 'active');
		this.trigger.innerHTML = this.trigger.innerHTML.replace(/Play now/, 'Now playing');
	},
	
	deactivate: function() {
		Element.removeClassName(this.trigger, 'active');
		this.trigger.innerHTML = this.trigger.innerHTML.replace(/Now Playing/, 'Play now');
	}
	
});

QuicktimeGallery = Class.create();
QuicktimeGallery.prototype = {
	
	displayPanel: null,
	controller: null,
	descriptionPanel: null,
	gallerySections: null,
	
	frontrow: null,
	
	initialSection: null,
	requestedSpecificSection: false,
	
	waitingToLookForFinished: null,
	
	initialize: function() {
		// DOM //TODO way too intimate with the DOM here, extract and pass in
		this.displayPanel = $('quicktime');
		this.controller = 'quicktimecontroller';
		this.descriptionPanel = $('descriptionpanel');
		this.gallerySections = $('videos').getElementsByClassName('button');

		 if (!this.checkQuicktime()) {
			return;
		}
		
		var initialMovieId = this.getInitialSectionId();
		
		this.populateFrontrow(initialMovieId);
		
		//if no movie specified observe banner for start
		if (!this.requestedSpecificSection) {
			var placeholder = Element.getElementsByClassName(this.displayPanel, 'poster')[0];
			Event.observe(placeholder, 'click', 
				this.frontrow.show.bind(this.frontrow, this.initialSection));
				
		} else {
			//otherwise just show the initial section
			this.frontrow.show(this.initialSection);
		}
	},
	
	checkQuicktime: function() {
		if (!AC.Detector.isQTInstalled()) {
			this.displayPanel.innerHTML = '<a href="/go/quicktime/"><img src="http://images.apple.com/mac/images/quicktime_required.gif" alt="QuickTime 7 Required." width="547" height="312" border="0"></a>';
			return false;
		} else {
			return true;
		}
	},

	getInitialSectionId: function() {
		var initialMovieId = document.location.search.toQueryParams()['movie'];
		
		if (!initialMovieId && defaultId) {
			initialMovieId = defaultId;  //TODO where did default id come from?
		} else {
			this.requestedSpecificSection = true;
		}
		
		return initialMovieId;
	},
		
	populateFrontrow: function(initialMovieId) {
		var sections = [];
		
		for(var i = 0; i < this.gallerySections.length; i++) {
			if (this.gallerySections[i].hasAttribute('id')) {
				var movieLinks = this.gallerySections[i].getElementsByClassName('movielink');
				var movieUrl = movieLinks[0].href;
				var title = movieLinks[0].innerHTML;
				var description = this.gallerySections[i].getElementsByClassName('description');
				description = (description.length>0) ? this.gallerySections[i].getElementsByClassName('description')[0] : title;
	
				var id = this.gallerySections[i].id.replace(/^mov-/, '');
				
				//replace href of all the movielinks 
				for (var j=0; j<movieLinks.length; j++){
					movieLinks[j].setAttribute('href', '?movie=' + id);
				};

				var newSection = new frontRowSection(this.gallerySections[i], 'object'+i, movieUrl, description);
				sections.push(newSection);


				
				//if this is the requested movie, be sure to show it first
				if (initialMovieId == id) {
					this.initialSection = newSection;
				}
			}
		}
		
		//if we couldn't find a section matching the specified id from the url
		//assume the first section
		if (!this.initialSection) {
			this.initialSection = sections[0];
		}
		
		var moviePackage = this.createMovie(this.initialSection.movieUrl, true);
		var movie = moviePackage.movie;
		var movieController = moviePackage.controller;

		var beforeStartMovieCallback = function(gallery) {
			return function(section) {
				
				if(gallery.initialSection != section) {
				
					var moviePackage = gallery.createMovie(section.movieUrl, false);
					var movie = moviePackage.movie;
					
					gallery.frontrow.currentMovie = movie;
					
					moviePackage = null;
					movie = null;
				}	
				$('quicktime').innerHTML = ""; //TODO this is too heavy handed atm, we'll want the endstates to sit here before movie plays, don't want to lose them

				gallery.refreshDisplay();

				//no need to call this again
				gallery.frontrow.options.beforeStartMovie = gallery.refreshDisplay.bind(gallery, false);
			}
		}

		var startMovieCallback = function(gallery) {
			
			return function(section) {
				
				var controller = gallery.frontrow.currentController;
				
				if (controller && !controller.movie) {
					controller.attachToMovie(gallery.frontrow.currentMovie);
					controller.monitorMovie();
				}
				
				//no need to call this again
				gallery.frontrow.options.onStartMovie = null;
				
			}
			
		}

		this.frontrow = new AC.FrontRow(movie, this.displayPanel, this.descriptionPanel, sections, {
			controller: movieController,
			
			beforeStartMovie: beforeStartMovieCallback(this),
			onStartMovie: startMovieCallback(this)});
		
		moviePackage = null;
		movie = null;
	},
	
	createMovie: function(movieUrl, createController) {

		var moviewidth = 560;
		var movieheight = 316;

		// if we're Opera, use the standard movie controller, otherwise attach movie controller
		//TODO crerating controller should probably be separate from ccreating the movie
		if (AC.Detector.isOpera()) {
			var controllerstatus = true;
			this.controller.style.display = 'none';
			movieheight += 16;
			if (createController) {
				this.displayPanel.style.width = moviewidth+'px';
			}
		} else {
			var controllerstatus = false;
			if (createController) {
				var movieController = new AC.QuicktimeController();
				movieController.render(this.controller);
			}
		}

		// package movie
		var movie = new AC.Quicktime.packageMovie('gallery-movie', movieUrl, {
			width: moviewidth,
			height: movieheight,
			autostart: true,
			controller: controllerstatus,
			showlogo: false,
			cache: true,
			bgcolor: '#f6f6f6'
		});
		
		return {movie: movie, controller: movieController};
	},
	
	showSectionEnd: function() {
		
		//assuming the user may have jogged to/past the end
		//prevent them from jogging back into movie once controller is hidden
		this.frontrow.currentController.hardPaused = true;
		
		var endState = this.frontrow.currentSection.trigger.getElementsByClassName('endstate')[0].cloneNode(true); //TODO eventually not clone this, or atl east cache something of this
		
		this.displayPanel.addClassName('loading');
		this.frontrow.currentController.controllerPanel.removeClassName('active');
		
		this.displayPanel.appendChild(endState);
		new Effect.Appear(endState);
		
		var replayButton = Element.getElementsByClassName(endState, 'replay')[0];
		replayButton.onclick = function() {
			this.refreshDisplay(true);
			return false;
		}.bind(this);
		
	},
	
	refreshDisplay: function(replaySection) {
		
		var endState = Element.getElementsByClassName(this.displayPanel, 'endstate')[0];
		if (endState) {
			endState.parentNode.removeChild(endState);
		}
		
		this.displayPanel.removeClassName('loading');
		this.frontrow.currentController.controllerPanel.addClassName('active');
		
		if (typeof(replaySection) != 'undefined' && replaySection) {
			
			//if replaying, asume cached don't delay waiting for finished
			clearTimeout(this.waitingToLookForFinished);
			
			//just rewind and play it
			this.frontrow.currentController.Rewind();
			this.frontrow.currentController.Play();
		} else {

			//prevent previous movie views form having their timeouts set the finished callback
			clearTimeout(this.waitingToLookForFinished);
			if(this.frontrow.currentController.options) {
				this.frontrow.currentController.options.onMovieFinished = null;
			}
						
			var movieFinishedCallback = this.showSectionEnd.bind(this);
			
			
			var lookForFinished = function(controller, callback) {
				return function() {
					// try {console.debug("now waiting for finished");} catch(e) {}
					controller.options.onMovieFinished = callback;
				}
			}
			
			//give the movie some time to load before asking if it's finished
			this.waitingToLookForFinished = setTimeout(lookForFinished(this.frontrow.currentController, movieFinishedCallback), 10000);
		}
	}
}

// LOCAL
Event.observe(window, 'load', function() { new QuicktimeGallery(); }, false);
