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

	activate: function() {
		Element.addClassName(this.trigger, 'active');
		var span = this.trigger.down('span');
		span.update(span.innerHTML.replace(/Play now/, 'Now playing'));
	},
	
	deactivate: function() {
		Element.removeClassName(this.trigger, 'active');
		var span = this.trigger.down('span');
		span.update(span.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(sections, panels) {
		this.loadingPanel = panels.loading;
		this.displayPanel = panels.display;
		this.controller = panels.controller;
		this.descriptionPanel = panels.description;
		this.gallerySections = sections;

		 if (!this.checkQuicktime()) {
			return;
		}
		
		var initialMovieId = this.getInitialSectionId();
		
		this.populateFrontrow(initialMovieId);
		
		// if no movie specified observe banner for start
		if (!this.requestedSpecificSection) {
			var placeholder = this.displayPanel.getElementsByClassName('poster')[0];
			placeholder = $(placeholder);

			Event.observe(placeholder, 'click', 
				this.frontrow.show.bind(this.frontrow, this.initialSection));

			var links = placeholder.getElementsBySelector('a');
			links.each(function(link) {
				link.onclick = function() {
					return false;
				}
			});
				
		} else {
			// otherwise just show the initial section
			this.frontrow.show(this.initialSection);
		}
	},
	
	order: 0,
	
	track: function(movieName, replayed) {
		if (typeof(s_gi) == 'undefined' || !s_gi) {
			return;
		}

		s = s_gi(s_account);
		
		this.order++;
		
		var replayedStatus = 'not replayed';
		if (replayed) {
			replayedStatus = 'replayed';
		}
		
		s.prop4 = '';
		s.g_prop4 = '';
		s.prop6 = '';
		s.g_prop6 = '';
		s.pageName = '';
		s.g_pageName = '';
		s.pageURL = '';
		s.g_pageURL = '';
		s.g_channel = '';
		
		// try {console.debug(this.order, movieName.toLowerCase(), replayedStatus);} catch(e) {}
		
		s.linkTrackVars='prop2,prop3,prop8';
		s.prop2 = this.order;
		s.prop3 = 'Apple Mac Movies: ' + movieName.toLowerCase();
		s.prop8 = replayedStatus;
		s.tl(this,'o','Mac Movies');
		
	},
	
	checkQuicktime: function() {
		if (!AC.Detector.isValidQTAvailable('7')) {
			this.displayPanel.innerHTML = '<a href="/go/quicktime/"><img src="http://images.apple.com/mac/home/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) 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.replace(/<\/?[^>]+>[^<]*<\/?[^>]+>/gi, '').stripTags().strip();
				var description = this.gallerySections[i].getElementsByClassName('description');
				description = (description.length>0) ? this.gallerySections[i].getElementsByClassName('description')[0] : title;
				
				// replace href of all the movielinks 
				var id = this.gallerySections[i].id.replace(/^mov-/, '');
				for (var j=0; j<movieLinks.length; j++){
					movieLinks[j].setAttribute('href', '?movie=' + id);
				}

				// create the frontrow section
				var newSection = new frontRowSection(this.gallerySections[i], 'object'+id, 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) {
					// unhighlight the old section (if it was)...
					gallery.initialSection.deactivate();

					// create the movie and controller, attach them to frontrow...
					var moviePackage = gallery.createMovie(section.movieUrl, false);
					var movie = moviePackage.movie;
					
					gallery.frontrow.currentMovie = movie;
					
					moviePackage = null; // for IE
					movie = null; // for IE
				}	

				// clear out the quicktime div (i.e. click to play)
				// TODO this is too heavy handed atm, we'll want the endstates to sit here before movie plays, don't want to lose them
				$('quicktime').innerHTML = '';

				gallery.refreshDisplay(false, section);

				// 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 = this.displayPanel.getHeight();

		// 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
		if (this.frontrow.currentController) {
			this.frontrow.currentController.Stop();
			this.frontrow.currentController.hardPaused = true;
			this.frontrow.currentController.controllerPanel.removeClassName('active');
		}
		
		var endState = $(this.frontrow.currentSection.trigger).getElementsByClassName('endstate')[0].cloneNode(true); //TODO eventually not clone this, or atl east cache something of this
		
		this.loadingPanel.addClassName('loading');

		
		if (this.displayPanel.getElementsByClassName('endstate')[0]) this.displayPanel.removeChild(this.displayPanel.getElementsByClassName('endstate')[0]);
		this.displayPanel.appendChild(endState);
		new Effect.Appear(endState);
		
		var replayButton = endState.getElementsByClassName('replay')[0];
		$(replayButton).observe('click', function(evt) {
			evt.stop();
			this.refreshDisplay(true);
		}.bind(this));
		
	},
	
	fixDisplayPanelSize: function(trigger) {
		var size = false;

		var classes = trigger.className.split(' ');
		for (var i=0; i<classes.length; i++) {
			if (!size && classes[i].match('moviesize')) var size = classes[i];
		}
		
		this.displayPanel.className = this.displayPanel.className.replace(/moviesize\d*x\d*/, '');
		this.displayPanel.className += ' '+size;
	},
	
	refreshDisplay: function(replaySection, section) {
		this.descriptionPanel.up().removeClassName('loading');
		
		if (section) {
			//section specified
			if (section.trigger.className.match('moviesize')) this.fixDisplayPanelSize(section.trigger);
			this.track(section.description, replaySection);
		} else {
			//no section specified (initial movie) or replayed
			this.track(this.frontrow.currentSection.description, replaySection);
		}
		
		var endState = this.displayPanel.getElementsByClassName('endstate')[0];
		if (endState) {
			endState.parentNode.removeChild(endState);
		}

		this.loadingPanel.removeClassName('loading');

		//if replaying, assume cached don't delay waiting for finished
		clearTimeout(this.waitingToLookForFinished);
		
		if (!this.frontrow.currentController) {
			return;
		}
		
		$(this.frontrow.currentController.controllerPanel).addClassName('active');

		if (typeof(replaySection) != 'undefined' && replaySection) {

			this.frontrow.currentController.Rewind();
			this.frontrow.currentController.Play();

		} else {

			//prevent previous movie views form having their timeouts set the finished callback
			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);
		}
	}
}


QuicktimeSwitcher = Class.create();
QuicktimeSwitcher.prototype = {
	
	displayPanel: null,
	descriptionPanel: null,
	sections: [],
	
	initialize: function(sections, panels) {
		this.displayPanel = panels.display;
		this.descriptionPanel = panels.description;
		var gallerySections = sections;
		
		this.displayPanel.innerHTML = '';
		this.descriptionPanel.setOpacity({ visibility:'hidden' });
		
		for (var i=0; i<gallerySections.length; i++) {
			var movieLink = gallerySections[i].getElementsByClassName('movielink')[0];
			var movieUrl = movieLink.href;
			movieLink.href = '#';
			
			var posterFrame = gallerySections[i].getElementsByClassName('posterFrame')[0];
			var posterFrameUrl = posterFrame.innerHTML.match(/src="(.*)"/)[1];
			
			var section = { trigger:gallerySections[i], movieUrl:movieUrl, posterFrameUrl:posterFrameUrl };
			this.sections.push(section);
			
			Event.observe(gallerySections[i], 'click', function(evt, section) {
				Event.stop(evt);
				this.showSection(section);
			}.bindAsEventListener(this, this.sections[i]));
		}
		
		this.showSection(this.sections[0]);
	},
	
	showSection: function(section) {
		// remove active state from the triggers
		var removeActiveState = function(section) {
			$(section.trigger).removeClassName('active');
		}
		this.sections.each(removeActiveState);
		
		// reset the display panel
		this.displayPanel.innerHTML = '';
		this.displayPanel.removeClassName('loading');

		// add the active state to the one we clicked on
		section.trigger.addClassName('active');

		// attach a new movie with the right movie info
		var movie = AC.Quicktime.packageMovie('galleryMovie', section.movieUrl, {
			width: this.displayPanel.getWidth(),
			height: this.displayPanel.getHeight(),
			posterFrame: section.posterFrameUrl,
			controller: false,
			showlogo: false,
			cache: true
		});
		this.displayPanel.appendChild(movie);

	}
	
}
