/*
	Mediabox version 0.4.1 - John Einselen (http://iaian7.com)
	updated 7.7.07

	tested on OS X 10.4/10.3 using FireFox 2, Opera 8(qt buggy), Safari 1.5/3, and Flock 2
	loads flash, quicktime, and html content in a Lightbox-style window effect.

	based on Slimbox version 1.4 - Christophe Beyls (http://www.digitalia.be)
			 Slimbox Extended version 1.3.1 - Yukio Arita (http://homepage.mac.com/yukikun/software/slimbox_ex/)
			 Videobox Mod version 0.1 - Faruk Can 'farkob' Bilir (http://www.gobekdeligi.com/videobox/)
			(licensed same as originals, MIT-style)

	inspired by the grandaddy of them all, Lightbox v2 - Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
*/

var Mediabox = {
	init: function(options){
		this.options = Object.extend({
			resizeDuration: 240,
			resizeTransition: Fx.Transitions.sineInOut,
			initialWidth: 360,
			initialHeight: 360,
			defaultWidth: 640,				// Default width (px)
			defaultHeight: 360,				// Default height(px)
					// begin Quicktime settings
				autoplay: 'true',			// Automatically play movie, true / false
				bgcolor: 'black',			// Background color, name / hex value
				cache: 'true',				// Cache the file for reloading, true / false
				controller: 'true',			// Show controller, true / false
				kioskmode: 'false',			// Savable file, true / false
				loop: 'false',				// Loop the video, true / false / palindrome
				showlogo: 'true',			// Show the QT logo while loading, true / false
				volume: '80',				// Initial volume of the media
					// end Quicktime settings
					// begin Mediaplayer / FLVplayer settings
				playerpath: 'http://iaian7.com/js/mediaplayer.swf',	// Path to the mediaplayer.swf or flvplayer.swf file
				backcolor:  '0x777777',		// Base color for the controller, color name / hex value (0x000000)
				frontcolor: '0x000000',		// Text and button color for the controller, color name / hex value (0x000000)
				lightcolor: '0x000000',		// Rollover color for the controller, color name / hex value (0x000000)
					// end Mediaplayer settings
					// Veoh preferences
				fullscreen: 'true',
			animateCaption: false
		}, options || {});

		// IE 6 - XML prolog problem
		if(window.ie6 && document.compatMode=="BackCompat"){
			this.options.animateCaption = false;
		}

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^mediabox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		/*	Build float panel
			<div id="lbOverlay"></div>
			<div id="lbCenter">
				<div id="lbCanvas">
					<!-- img or iframe element is inserted here -->
				</div>
			</div>
			<div id="lbBottomContainer">
				<div id="lbBottom">
					<a id="lbCloseLink"></a>
					<div style="clear:both;"></div>
				</div>
			</div>
		*/

		this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);

		this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
		this.canvas = new Element('div').setProperty('id', 'lbImage').injectInside(this.center);

		this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
		this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);
		new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
		new Element('div').setStyle('clear', 'both').injectInside(this.bottom);

		/* Build effects */
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			center: this.center.effects({duration: this.options.resizeDuration, transition: this.options.resizeTransition, onComplete: nextEffect}),
			content: this.canvas.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottomContainer.effect('height', {duration: 400, onComplete: nextEffect})
		};

	},

	click: function(link){
		return this.open(link.href, link.title, link.rel);
	},

	open: function(url, title, rel){
		this.href = url;
		this.title = title;
		this.rel = rel;
		this.position();
		this.setup(true);
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
		var st = document.body.scrollTop  || document.documentElement.scrollTop;
		this.top = st + (wh / 15);
//		this.top = Window.getScrollTop() + (Window.getHeight() / 15);  // alternate version of this.top
		this.center.setStyles({top: this.top+'px', display: ''});
		this.fx.overlay.start(0.8);
		return this.changeItem(url);
	},

	position: function(){
//		this.overlay.setStyles({top: window.getScrollTop()+'px', height: window.getScrollHeight()+'px'});
		this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.getHeight()+'px'});
	},

	setup: function(open){
		var aDim = this.rel.match(/[0-9]+/g);													// videobox rel settings
		this.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;		// videobox rel settings
		this.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;	// videobox rel settings

		var elements = $A(document.getElementsByTagName('object'));								// hide page content
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});

		var fn = open ? 'addEvent' : 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		this.step = 0;
	},

	keyboardListener: function(event){
		switch (event.keyCode){
			case 27: case 88: case 67: this.close(); break;
		}
	},

	changeItem: function(url){
		this.step = 1;
		this.fx.content.hide();	// important!  hides the iframe while the div animates
		this.center.className = 'lbLoading';

		this.preload = new Object ();	// JavaScript native Object
		this.preload.src = url;

		if (url.match(/youtube\.com\/watch/i)) {
// YouTube
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.so = new SWFObject("http://www.youtube.com/v/"+this.videoID+"&autoplay=1", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/dailymotion\.com/i)) {
// DailyMotion
			this.so = new SWFObject(this.preload.src, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000").write(this.canvas);
///		} else if (url.match(/veoh\.com\/watch/i)) {
// Veoh - NOT WORKING - DISABLED
//			var videoId = url.split('/');
//			this.videoID = videoId[4];
//			this.so = new SWFObject("http://www.veoh.com/videodetails2.swf?permalinkId="+this.videoID+"&videoAutoPlay=1", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/metacafe\.com\/watch/i)) {
// Metacafe
			var videoId = url.split('/');
			this.videoID = videoId[4];
			this.so = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/google\.com\/videoplay/i)) {
// Google Video
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.so = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&autoplay=1&hl=en", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/\.swf/i)) {
// SWF
			this.so = new SWFObject(this.preload.src, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/\.flv/i)) {
// FLV
			this.so = new SWFObject(this.options.playerpath+"?file="+this.preload.src+"&autostart=true&displayheight="+this.contentsHeight+"&usefullscreen=false&backcolor="+this.options.backcolor+"&frontcolor="+this.options.frontcolor+"&lightcolor="+this.options.lightcolor, "flvvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent").write(this.canvas);
		} else if (url.match(/\.mov/i)) {
// Quicktime - NOT RECOMMENDED for SAFARI 1.5
			this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that has static id.
			this.qtObject = new Element('object').setProperties({id: this.iframeId, classid: 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', width: this.contentsWidth, height: this.contentsHeight, codebase: 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', align: 'middle'});
			this.qtEmbed = new Element('embed').setProperties({src:this.preload.src, width: this.contentsWidth, height: this.contentsHeight, align: 'middle', autoplay: this.options.autoplay, bgcolor: this.options.bgcolor, cache: this.options.cache, controller: this.options.controller, kioskmode: this.options.kioskmode, loop: this.options.loop, scale: 'aspect', showlogo: this.options.showlogo, volume: this.options.volume }).injectInside(this.qtObject).injectInside(this.qtObject);
			this.so = this.qtObject.injectInside(this.canvas);

//			this.qtObject = new Element('object').setProperties({classid: 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', width: this.contentsWidth, height: this.contentsHeight, codebase: 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', align: 'middle'});
//			this.qtEmbed = new Element('embed').setProperties({src:this.preload.src, width: this.contentsWidth, height: this.contentsHeight, align: 'middle', autoplay: 'true', bgcolor: 'black' }).injectInside(this.qtObject);
//			this.qtScript = this.qtEmbed.injectInside(this.qtObject);
//			this.so = this.qtScript.injectInside(this.canvas);
		} else {
			this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that has static id.
			this.so = new Element('iframe').setProperties({id: this.iframeId, width: this.contentsWidth, height: this.contentsHeight, frameBorder:0, scrolling:'auto', src:this.preload.src}).injectInside(this.canvas);
		}

		this.nextEffect();	//asynchronous loading?
		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.so;
			this.canvas.style.width = this.bottom.style.width = this.contentsWidth+'px';

			if (this.center.clientHeight != this.canvas.offsetHeight){
				this.fx.center.start({height: this.canvas.offsetHeight, width: this.canvas.offsetWidth, marginLeft: -this.canvas.offsetWidth/2});
				break;
			}
			this.step++;

		case 2:
			if (this.center.clientWidth != this.canvas.offsetWidth){
				this.fx.center.start({height: this.canvas.offsetHeight, width: this.canvas.offsetWidth, marginLeft: -this.canvas.offsetWidth/2});
				break;
			}
			this.step++;

		case 3:
			this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height:'0px', marginLeft: this.center.style.marginLeft, width:this.center.style.width, display: ''});
			this.fx.content.start(1);
			this.center.className = '';
			break;

		case 4:
			if (this.options.animateCaption){
				// This is not smooth animation in IE 6 with XML prolog.
				// If your site is XHTML strict with XML prolog, disable this option.
				this.fx.bottom.start(0,this.bottom.offsetHeight);
				break;
			}
			this.bottomContainer.style.height = (this.bottom.offsetHeight)+'px';

		case 5:
			this.step = 0;
		}
	},

	close: function(){
//		$(this.iframeId).remove();
		this.canvas.innerHTML = '';

		if (this.step < 0) return;	//  needed?
		this.step = -1;				//  needed?

		for (var f in this.fx) this.fx[f].stop();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		return false;
	}

};

window.addEvent('domready', Mediabox.init.bind(Mediabox));