var Mediabox = {
	init: function(options){
		this.options = Object.extend({
			resizeDuration: 240,
			resizeTransition: Fx.Transitions.sineInOut,
			topDistance: 15,			// Divisor of the total visible window height, higher number = higher Mediabox placement
										// If you wish to change this to an absolute pixel value, scroll down to lines 107 and 108 and swap the commenting slashes one for the other
			initialWidth: 360,
			initialHeight: 360,
			defaultWidth: 640,			// Default width (px)
			defaultHeight: 360,			// Default height(px)
		// Quicktime and Windows Media settings
			autoplay: 'true',			// Automatically play movie, true / false
			bgcolor: 'black',			// Background color, name / hex value
			controller: 'true',			// Show controller, true / false
		// Mediaplayer or FLVplayer settings
			playerpath: '/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)
			fullscreen: 'false',		// Display fullscreen button
		// Animation controls
			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 || {});

		if(window.ie6 && document.compatMode=="BackCompat"){ this.options.animateCaption = false; }	// IE 6 - XML prolog problem

		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.onKeyDown = function(){alert()}
		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);
		this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
		new Element('div').setStyle('clear', 'both').injectInside(this.bottom);

		/* Build effects */
		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay:new Fx.Tween(this.overlay,{ duration: 500 }),
center:new Fx.Tween(this.center,{duration: this.options.resizeDuration, link:'chain', transition: this.options.resizeTransition, onChainComplete:nextEffect}),
			content: new Fx.Tween(this.canvas,{ duration: 500, onComplete: nextEffect }),
			
			//bottom: this.bottomContainer.effect('height', {duration: 400, onComplete: nextEffect})
			bottom: new Fx.Tween(this.bottomContainer,{duration: 400})
		};
	},

	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 / this.options.topDistance);	// comment this code out and uncomment the line below to switch to absolute positioning
//		this.top = 100;										// this is the code needed for an absolute position (do not add "px", numerical only!)
		this.center.setStyles({top: this.top+'px', display: ''});
		//this.fx.overlay.start(0.8);
		this.fx.overlay.start('opacity',[0,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){
		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;
		}
	},

	loadVideo: function(url){
		this.step = 1;

			this.type = 'iframe';
			this.iframeId = "lbFrame_"+new Date().getTime();	// Safari would not update iframe content that had a static id.
			this.object = new Element('iframe').setProperties({id: this.iframeId, width: this.contentsWidth, height: this.contentsHeight, frameBorder:0, scrolling:'auto', 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';
			this.caption.innerHTML = this.title;
			if (this.center.clientHeight != this.canvas.offsetHeight){
//this.fx.center.start(this.canvas.offsetHeight);
this.fx.center.start('height',this.canvas.offsetHeight).chain(function(){this.start('width',Mediabox.canvas.offsetWidth)},function(){this.start('marginLeft',-Mediabox.canvas.offsetWidth/2)});
				break;
			} else if (this.center.clientWidth != this.canvas.offsetWidth){
this.fx.center.start('height',this.canvas.offsetHeight).chain(function(){this.start('width',Mediabox.canvas.offsetWidth)},function(){this.start('marginLeft',-Mediabox.canvas.offsetWidth/2)});
				break;
			}
			this.step++;
			
		case 2:
		//alert('case 2:'+this.step);
		//this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height:'0px', marginLeft: this.center.style.marginLeft, width:this.center.style.width, display: ''});
setTimeout(function(){Mediabox.bottomContainer.setStyles({top: (Mediabox.top + Mediabox.center.clientHeight)+'px', height:'0px', marginLeft: Mediabox.center.style.marginLeft, width:Mediabox.center.style.width, display: ''});	},800);
			this.fx.content.start('opacity',[0.3,0.9]);
			this.step++;

		case 3:
		//alert('case 3:'+this.step);
			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 = $('mediabox');
			this.center.className = '';//alert('case3'+this.step);
			break;
			this.step++;

		case 4:
			if (this.options.animateCaption){

				setTimeout(function(){Mediabox.fx.bottom.start('height','0',Mediabox.bottom.offsetHeight)},800);			
				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();	// safari needs to call Stop() to remove the object's audio stream...
			}
			if (navigator.plugins && navigator.plugins.length) {
				this.canvas.innerHTML = '';
			} else {
				if (window.ie6) {
//					this.currentObject.style.display = 'none';
					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();
		for (var f in this.fx) this.fx[f].cancel();
		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start('opacity',[0.8,0]);
		return false;
	}
};

window.addEvent('domready', Mediabox.init.bind(Mediabox));