PopupGallery = Class.create();
PopupGallery.prototype = {
	defaultImageWidth: 980,
	previous: null,
	next: null,
	items: [],

	controller: null,

 	initialize: function(itemClass) {
		this.items = $('main').getElementsByClassName(itemClass);
		
		if (this.items.length>0) {
			this.createPopup();
			this.setImageAttributes();
		}

		if (location.hash) {
			var initial = location.hash.substring(location.hash.indexOf('#')+1, location.hash.length);
			if (initial=='demo') this.showDemo();
		}
	},

 	createPopup: function() {
		this.closeBtn = Builder.node('a', {href:'#close', 'class':'close'}, 'Close');
		Event.observe(this.closeBtn, 'click', this.close.bindAsEventListener(this), false);

		this.popupimg = Builder.node('img', {'class':'popupimg', border:0});
		this.descriptionPanel = Builder.node('div', {'class':'description'});
		this.displayPanel = Builder.node('div', {'class':'movie'});
		this.controllerPanel = Builder.node('div', {'class':'moviecontroller'});
		var middle = [this.popupimg, this.descriptionPanel, this.displayPanel, this.controllerPanel];
		
 		this.popup = Builder.node('div', {id:'popup'}, [
 			Builder.node('div', {'class':'topleft'}),
 			Builder.node('div', {'class':'top'}, [
	 			Builder.node('div', {'class':'topmiddlecap'}, [this.closeBtn]),
	 			Builder.node('div', {'class':'topleftcap'}),
	 			Builder.node('div', {'class':'toprightcap'})
 			]),
 			Builder.node('div', {'class':'topright'}),
 			Builder.node('div', {'class':'left'}),
 			Builder.node('div', {'class':'middle'}, middle),
 			Builder.node('div', {'class':'right'}),
 			Builder.node('div', {'class':'bottomleft'}),
 			Builder.node('div', {'class':'bottom'}),
 			Builder.node('div', {'class':'bottomright'})
 		]);

 		document.body.appendChild(this.popup, document.body.firstChild);
 	},

 	setImageAttributes: function() {
 		for (var i=0; i<this.items.length; i++) {
 			this.items[i] = this.items[i].getElementsByTagName('a')[0];
 			var item = this.items[i]; 

 			if (item.href.indexOf('.mov')>0) {
				item.movieUrl = item.href;
				item.description = item.parentNode.getElementsByClassName('description')[0];
				var posterFrameSpan = item.parentNode.getElementsByClassName('posterFrame')[0];
 				item.posterFrameUrl = posterFrameSpan.innerHTML.match(/src="(.*)"/)[1];
 			} else {
 				item.img = new Image();
				item.img.src = item.href;
			}

 			this.setEvent(item, i);
 		}
	},

 	setEvent: function(item, i) {
		Event.observe(item, 'click', this.onClick.bindAsEventListener(this, item, i), false);
	},

	windowSize: function() {
		var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
		var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
		var x = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
		var y = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
		
		if(AC.Detector.isiPhone()) {
			width = parseInt(980);
			height = parseInt(1212);
		}

		return {'width':width, 'height':height, 'x':x, 'y':y}
	},

 	showDemo: function() {
 		for (var i=0; i<this.items.length; i++) {
 			if (Element.hasClassName(this.items[i].parentNode, 'demo')) {
 				var index = i;
 				var item = this.items[i];
 			}
 		}

		// store the small size and position for later
		this.width = 50;
		this.left = this.windowSize().x+(this.windowSize().width/2);
		this.height = 50;
		this.top = this.windowSize().y+(this.windowSize().height/2)

		// do the movie or the image
 		if (item.movieUrl && item && typeof(index)=='number') {
			this.popMovie(null, item, index);
 		}
 	},

 	onClick: function(evt, item, i) {
 		// store the small size and position for later
		this.width = (item.offsetWidth>80) ? 80 : item.offsetWidth;
		this.left = evt.pageX || evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		this.left -= this.width/2;
		this.height = item.offsetHeight;
		this.top = evt.pageY || evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
		this.top -= this.height/2;

		// stop the default event
 		Event.stop(evt);

		// unset the click events
		this.resetMovie();
		this.afterClose();

		// do the movie or the image
 		if (item.movieUrl) {
 			this.popMovie(evt, item, i);
 		} else {
 			this.popImage(evt, item, i);
 		}
 	},

 	popMovie: function(evt, item, i) {
 		// reset the image stuff
 		this.popup.onclick = '';

		// we're the movie so look like it
 		Element.addClassName(this.popup, 'video');
 		
		// movie size
		var width = 980;
		this.padleft = (this.popup.offsetWidth-width);
		var height = 488;
		this.padtop = (this.popup.offsetHeight-height);

		// if we're Opera, use the standard movie controller, otherwise attach movie controller
		var movieheight = 416;
		if (AC.Detector.isFirefox() || AC.Detector.isOpera()) {
			var controllerstatus = true;
			movieheight += 16;
	 		this.displayPanel.style.height = movieheight+'px';
		} else {
			var controllerstatus = false;
		}

		// initalize the movie
		if (!AC.Detector.isiPhone() && AC.Detector.isQTInstalled()) {
			this.movieController = new AC.QuicktimeController();
		}

		// set up what we're going to do after the effect
		var after = function() {
			Element.removeClassName(this.popup, 'isanim');
			Element.addClassName(this.popup, 'popped');
			// set the description
			this.descriptionPanel.innerHTML = item.description.innerHTML;

			if (AC.Detector.isQTInstalled()) {
				var movie = AC.Quicktime.packageMovie('movie', item.movieUrl, {
						width: 672,
						height: movieheight,
						posterFrame: item.posterFrameUrl,
						controller: controllerstatus,
						showlogo: false,
						cache: true
				});

				this.displayPanel.appendChild(movie);
	
				if (!AC.Detector.isFirefox() && !AC.Detector.isOpera()) { this.movieController.render(this.controllerPanel); }
				this.movieController.attachToMovie(movie);
				this.movieController.monitorMovie();
				
				var movie = null;
			} else {
				this.displayPanel.innerHTML = '<a href="/quicktime/download/"><img src="http://images.apple.com/macosx/leopard/images/popup_quicktimerequired20070611.gif" alt="QuickTime 7 Required." width="672" height="438" border="0" class="getquicktime"></a>';
			}
		}.bind(this)

		// set the position of the image according to the height/width we just found
		var left = this.windowSize().x+(this.windowSize().width-width)/2;
		if (left<this.closeBtn.offsetWidth/2) left = this.closeBtn.offsetWidth/2;
		var top = this.windowSize().y+(this.windowSize().height-height)*.6;
		if (top<this.padtop/4) top = this.padtop/4;


		// call the effect
		this.pop(width, top, height, left, after);
 	},

 	popImage: function(evt, item, i) {
 		// reset the movie stuff
		this.popup.onclick = this.close.bindAsEventListener(this);

		// set the source for image in the popup
 		this.popupimg.src = item.img.src;
 		this.popupimg.alt = item.img.alt;

 		// get the ratio of that image
 		var ratio = item.img.width / item.img.height;

		// default size
		var left, top = null;
		var width = this.defaultImageWidth;
		this.padleft = (this.popup.offsetWidth-width);
		var height = Math.round(width/ratio);
		this.padtop = (this.popup.offsetHeight-height);

		// re-size functions
		var smallWidth = function() {
 			//console.log('width is small'); // width is small
	 		width = Math.round(this.windowSize().width*.8);
			height = Math.round(width/ratio);
		}.bind(this)

		var smallHeight = function() {
 			//console.log('height is small'); // height is small
			height = Math.round(this.windowSize().height*.6);
	 		width = Math.round(height*ratio);
		}.bind(this)

		// figure out if we're small or big
	 	if (this.windowSize().width<width+this.padleft && this.windowSize().height<height+this.padtop) {
 			//console.log('both are small'); // both are small
	 		if (this.windowSize().width<this.windowSize().height*ratio) {
	 			smallWidth();
	 		} else {
	 			smallHeight();
	 		}
	 	} else if (this.windowSize().width<width+this.padleft) {
	 		smallWidth();
	 	} else if (this.windowSize().height<height+this.padtop) {
	 		smallHeight();
	 	}

		var after = function() {
			Element.removeClassName(this.popup, 'isanim');
			Element.addClassName(this.popup, 'popped');
			this.popupimg.style.width = width+'px';
			this.popupimg.style.height = Math.round(width/ratio)+'px';
		}.bind(this)

		// set the position of the image according to the height/width we just found
		if (!left) left = this.windowSize().x+(this.windowSize().width-width)/2;
		if (!top) top = this.windowSize().y+(this.windowSize().height-height)*.6;
		
		// call the effect
		this.pop(width, top, height, left, after);
	},

 	pop: function(width, top, height, left, after) {
		// prep the popup for the effect
		this.popup.style.width = this.width+'px';
		this.popup.style.height = this.height+'px';
		this.popup.style.left = this.left+'px';
		this.popup.style.top = this.top+'px';

		this.popup.style.zIndex = '999';
 		Element.setOpacity(this.popup, 0);

		// do the craziness
		new Effect.Parallel([
				new Effect.MoveBy(this.popup, top-this.top, left-this.left, { sync:true }), 
				new Effect.Scale(this.popup, (width/this.width)*100, { sync:true, scaleMode:{ originalWidth:this.width, originalHeight:this.height }, scaleY:false, scaleContent:false }),
				new Effect.Scale(this.popup, (height/this.height)*100, { sync:true, scaleMode:{ originalWidth:this.width, originalHeight:this.height }, scaleX:false, scaleContent:false }),
				new Effect.Appear(this.popup, { sync:true })
			],
			{ duration:.2, beforeStart:function() { Element.addClassName(this.popup, 'isanim'); }.bind(this), afterFinish:after }
		
		);
	},

 	close: function(evt) {
 		if (evt) Event.stop(evt);

		var width = (this.popupimg.offsetWidth) ? this.popupimg.offsetWidth : this.popup.offsetWidth - this.padleft;
		var left = this.popup.offsetLeft + this.padleft/2;
		var height = (this.popupimg.offsetHeight) ? this.popupimg.offsetHeight : this.popup.offsetHeight - this.padtop/2;
		var top = this.popup.offsetTop + this.padtop/2;

		if (!AC.Detector.isiPhone()) {
			new Effect.Parallel([
					new Effect.MoveBy(this.popup, this.top-top, this.left-left, { sync:true }), 
					new Effect.Scale(this.popup, (this.width/width)*100, { sync:true, scaleMode:{ originalWidth:width, originalHeight:height }, scaleY:false, scaleContent:false }),
					new Effect.Scale(this.popup, (this.height/height)*100, { sync:true, scaleMode:{ originalWidth:width, originalHeight:height }, scaleX:false, scaleContent:false }),
					new Effect.Fade(this.popup, { sync:true })
				],
				{ duration:.3, beforeStart:this.resetMovie.bind(this), afterFinish:this.afterClose.bind(this) });
		} else {

			this.resetMovie();
			this.afterClose();
		}
	},

 	resetMovie: function(evt) {
 		Element.addClassName(this.popup, 'isanim');
 		Element.removeClassName(this.popup, 'popped');

		if (this.movieController) {
			this.movieController.Stop();
			this.movieController.detachFromMovie();
		}

		this.displayPanel.style.display = 'none';
		this.displayPanel.innerHTML = '';
		this.displayPanel.style.display = '';
		this.descriptionPanel.innerHTML = '';
		this.controllerPanel.innerHTML = '';
 	},

 	afterClose: function(evt) {
		// reset everything
		this.popup.style.width = '';
		this.popup.style.height = '';
		this.popup.style.left = '';
		this.popup.style.top = '';
		this.popup.className = '';

		this.popup.style.display = 'none';
		this.popup.style.zIndex = '-10';
		this.popup.style.display = '';
		this.popup.style.visibility = '';
		Element.setOpacity(this.popup, '');
		
		if (AC.Detector.isWebKit()) {
			if (!this.scrollTo) this.scrollTo = 1;
			window.scroll(this.windowSize().x+this.scrollTo, this.windowSize().y+this.scrollTo);
			this.scrollTo = -this.scrollTo;
			window.scroll(this.windowSize().x+this.scrollTo, this.windowSize().y+this.scrollTo);
			this.scrollTo = -this.scrollTo;
		}
		
		this.resetVar();
 	},

 	resetVar: function(evt) {
		this.width, this.padleft, this.left, this.height, this.padtop, this.top, this.movieController = null;
 	}

}

Event.observe(window, 'load', function() {
	var images = [
		'http://images.apple.com/macosx/leopard/images/popup_bgbottom20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgbottomleft20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgbottomright20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgleft20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgright20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgtop20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgtopleft20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_bgtopright20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_movie_bg20070611.png',
		'http://images.apple.com/macosx/leopard/images/popup_movie_bgtrack20070611.gif',
		'http://images.apple.com/macosx/leopard/images/popup_movie_playpause20070611.gif',
		'http://images.apple.com/macosx/leopard/images/popup_movie_pointer20070611.gif'
	];
	for (var i=0; i<images.length; i++) {
		var image = new Image();
		image.src = images[i];
	}
	new PopupGallery('galleryitem');
}, false);

