 /*
	Slightly modified version of Mediabox 0.6.5 - John Einselen (http://iaian7.com)
	Added Flash support for MP3 Playback with image preview
	Modified iFrame properties to better display images
	Removed support for WMV and Quicktime
	
	Tested OS X 10.4 / 10.3 using FireFox 2, Flock 2, Opera 9, Safari 2, and Camino 1.5
	Tested Windows XP / Vista using Internet Explorer 6, Internet Explorer 7, FireFox 2, and Opera 9
	Loads SWF, FLV, MP3 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/)
	DM_Moviebox.js - Ductchmonkey (http://lib.dutchmoney.com/)
	Licensed same as originals, MIT-style

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

	Distributed under the MIT license, terms:
	Copyright (c) 2007 dutchmoney llc
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
 */

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)
			
					// Mediaplayer Settings
			playerpath: '../player/player.swf',	 // Path to the mediaplayer.swf or flvplayer.swf file
			preview: 'preview.jpg',    // Path to the preview image 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)
			animateCaption: true		     // This is not smooth animation in IE 6 with XML prolog. If your site is XHTML strict with XML prolog, disable this option.
			
		}, 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);
		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.center.setStyles({top: this.top+'px', display: ''});
		this.fx.overlay.start(0.8);
		this.center.className = 'lbLoading';
		return this.loadVideo(url);
	},

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

	setup: function(open){
		  // Videobox Rel Settings
		var aDim = this.rel.match(/[0-9]+/g);
		this.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;
		this.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;
		
	  // Hide Page Content
		var elements = $A(document.getElementsByTagName('object'));
		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;
		}
	},

	loadVideo: function(url){
		this.step = 1;

// YouTube
		if (url.match(/youtube\.com\/watch/i)) {
			this.type = 'flash';
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.object = new SWFObject("http://www.youtube.com/v/"+this.videoID+"&autoplay=1", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// DailyMotion
		} else if (url.match(/dailymotion\.com/i)) {
			this.type = 'flash';
			this.object = new SWFObject(url, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000");
			
// Metacafe
		} else if (url.match(/metacafe\.com\/watch/i)) {
			this.type = 'flash';
			var videoId = url.split('/');
			this.videoID = videoId[4];
			this.object = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// Google Video
		} else if (url.match(/google\.com\/videoplay/i)) {
			this.type = 'flash';
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.object = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&autoplay=1&hl=en", "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// Flash SWF
		} else if (url.match(/\.swf/i)) {
			this.type = 'flash';
			this.object = new SWFObject(url, "sfwvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// Flash Video FLV
		} else if (url.match(/\.flv/i)) {
			var str = url;
			this.type = 'flash';
   this.options.preview = (str.replace(/flv/, "jpg"));
			this.object = new SWFObject(this.options.playerpath+"?file="+url+"&autostart=true&displayheight="+this.contentsHeight+"&usefullscreen=false&backcolor="+this.options.backcolor+"&frontcolor="+this.options.frontcolor+"&lightcolor="+this.options.lightcolor+"&image="+this.options.preview, "flvvideo", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// Flash Audio MP3
		} else if (url.match(/\.mp3/i)) {
			var str = url;
			this.type = 'flash';
   this.options.preview = (str.replace(/mp3/, "jpg"));
			this.object = new SWFObject(this.options.playerpath+"?file="+url+"&autostart=true&displayheight="+this.contentsHeight+"&usefullscreen=false&backcolor="+this.options.backcolor+"&frontcolor="+this.options.frontcolor+"&lightcolor="+this.options.lightcolor+"&image="+this.options.preview, "flvaudio", this.contentsWidth, this.contentsHeight, "9", "#000000", "wmode", "transparent");
			
// iFrame Content
		} else {
			this.type = 'iframe';
			this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that has a static ID.
			this.object = new Element('iframe').setProperties({id: this.iframeId, noresize:'noresize', frameBorder:0, marginwidth:0, marginheight:0, width: this.contentsWidth, height: this.contentsHeight, scrolling:'no', src:url});
		}
		
		this.nextEffect();
		return false;
	},

	nextEffect: function(url){
		switch (this.step++){
		case 1:
			this.canvas.style.width = this.bottom.style.width = this.contentsWidth+'px';
			this.canvas.style.height = this.contentsHeight+'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;
			} else 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 2:
			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.step++;

		case 3:
			if (this.type == 'flash'){
				this.object.write(this.canvas);
			} else if (this.type == 'iframe'){
				this.object.injectInside(this.canvas)
			} else {
				this.canvas.setHTML(this.object);
			}
			this.currentObject = document.getElementById('mediabox');
			this.center.className = '';
			break;
			this.step++;

		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.start(0,this.bottom.offsetHeight);
				break;
			}
			this.bottomContainer.style.height = (this.bottom.offsetHeight)+'px';

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

	close: function(){
			if (this.type == 'qt' && window.webkit) {
				this.currentObject.Stop();	// For Safari to remove the object's audio stream
			}
			if (navigator.plugins && navigator.plugins.length) {
				this.canvas.setHTML('');
			} else {
				if (window.ie6) {
					this.canvas.innerHTML = '';
				} else {
					this.canvas.innerHTML = '';
				}
			}
			this.currentObject = null;
			this.currentObject = Class.empty;
			this.type = false;

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

		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));
