nestedTrigger = {};
Object.extend(nestedTrigger, Event.Listener);
Object.extend(nestedTrigger, {

	initialize: function(overlay) {
		this.setEvents($$('.OverlayPanel'));
		this.listenForEvent(AC.ViewMaster, 'ViewMasterWillShowNotification', false, this.willShow);
		this.listenForEvent(AC.OverlayPanel.overlay, 'afterClose', false, this.afterClose);
	},
	
	setEvents: function(triggers){
		triggers.each(function(trigger){
			trigger.observe('click', this._triggerClicked.bindAsEventListener(this));
		}.bind(this));
	},

	_triggerClicked: function(evt) {
		link = evt.target;
		if(!link.readAttribute('href')) link = link.up('a'); // For thumbnails with Play button overlay on top of <a> tag
		
		target = link.readAttribute('target');
		
		if (target) {
			this.initialId = target.replace(/.*#/, '');
		}
	},

	willShow: function(evt) {
		var overlay = evt.event_data.data.sender;
		var section = evt.event_data.data.incomingView;

		// if we're an overlay, set up the section
		if (overlay.overlayId == 'OverlayPanel') {
			this.overlay = overlay;
			if (section && section.id) {
				this.gallery(section);
			}
		}

		//this.initialId = null;
	},

	gallery: function(section) {
		this.overlay.overlay.addClassName('galleryoverlay');
		if (!section.gallery) {
			// add a className for non-css3 browsers
			section.content.addClassName('galleryoverlay');

			// add the className to the links
			var links = section.content.select('a');
			links.each(function(link) {
				link.addClassName(section.id+'Trigger');
			});

			// create swap view container
			var container = document.createElement('div');
			container.id = section.id+'SwapView';
			container.className = 'gallerySwapView';
			section.content.appendChild(container);
			

			// set the initialId if we don't have one
			if (!this.initialId) {
				this.initialId = links[0].href.replace(/.*#/, '');
			}

			// set this so we only do this once
			section.gallery = new AC.ViewMaster.Viewer(links, section.id+'SwapView', section.id+'Trigger', { initialId:this.initialId, silentTriggers:true, shouldAnimateContentChange:false });
		} else if (this.initialId) {
			section.gallery.show(section.gallery.sectionWithId(this.initialId), true);
		}
	},

	afterClose: function(evt) {
		var overlay = evt.event_data.data;
		
		if(AC.mediaOuterObject) {
            try {
                AC.mediaOuterObject.Stop();
            } catch(e) {}

            AC.mediaOuterObject.style.display = 'none';
            AC.mediaOuterObject = null;
		}

		// remove anything from the overlay we may have added
		overlay.overlay.removeClassName('galleryoverlay');
		if (typeof(AC.OverlayPanel.overlay.slideshows) != 'undefined') {
			AC.OverlayPanel.overlay.slideshows.each(function(slideshow) {
				slideshow.stop();
			});
		}
		//overlay.setOverlayShadowImageSrc(null);
	}

});


