var splashBox = {
	init: function(options){
		this.options = Object.extend({
			resizeDuration: 240,
			resizeTransition: Fx.Transitions.sineInOut,
			topDistance: 8,
			initialWidth: 360,
			initialHeight: 360,
			defaultWidth: 640,
			defaultHeight: 360,
			autoplay: 'true',
			bgcolor: 'black',
			controller: 'true',
			playerpath: '/splash-box/i/mediaplayer.swf',
			backcolor:  '0x777777',
			frontcolor: '0x000000',
			lightcolor: '0x000000',
			fullscreen: 'false',
			animateCaption: true,
			nowstatus: true
		}, options || {});

		if(window.ie6 && document.compatMode=="BackCompat"){ this.options.animateCaption = false; }

		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^splashBox/i)){
				
				if(el.getAttribute('onclick')){
					$(el).addEvent('click', this.click.pass(el, this));
					$(el).addEvent('click', function() {return false});
				} else {
					el.onclick = this.click.pass(el, this);
				}
				this.anchors.push(el);
			}
		}, this);

		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

		if(! ($('lbOverlay') && $('lbCenter') && $('lbCanvas') && $('lbBottomContainer') && $('lbBottom') && $('lbCloseLink') && $('lbCaption')) ){
			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', 'lbCanvas').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'}).injectInside(this.bottom).onclick = this.close.bind(this);
			this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
			new Element('div').setStyle('clear', 'both').injectInside(this.bottom);
		}

		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.center.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottomContainer.effect('height', {duration: 400, onComplete: nextEffect})
		};
	},

	click: function(link){
		if (this.options.nowstatus){
			this.options.nowstatus = false;
			if (link.rel.length == 8) return this.show(link.href, link.title, link.rel);
			var j, itemNumber, items = [];
			this.anchors.each(function(el){
				if (el.rel == link.rel){
					for (j = 0; j < items.length; j++) if(items[j][0] == el.href && items[j][2] == el.rel) break;
					if (j == items.length){
						items.push([el.href, el.title, el.rel]);
						if (el.href == link.href && el.rel == link.rel) itemNumber = j;
					}
				}
			}, this);
			return this.open(link.href, link.title, link.rel);
		}
	},

	open: function(url, title, rel){
		if (this.options.nowstatus){
			this.options.nowstatus = false;

			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);
			this.center.setStyles({top: this.top+'px', display: ''});
			this.fx.overlay.start(1);
			this.center.className = 'lbLoading';
			return this.changeItem(this.href, this.title, this.rel);
		}
	},

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

	setup: function(open){
		this.contentsWidth = this.matchOrDefault(this.rel, new RegExp("width:(\\d+%?)", "i"), this.options.defaultWidth);
		this.contentsHeight = this.matchOrDefault(this.rel, new RegExp("height:(\\d+%?)", "i"), this.options.defaultHeight);

		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: this.close(); break;
		}
	},

	changeItem: function(url, title, rel){
		this.step = 1;
		this.center.className = 'lbLoading';

		var url = url;
		var title = title
		var rel = rel;

		// Image Content
		if( url.match(/\.(jpe?g|png|gif|bmp)/i) && !url.match(/\.swf/i)) {
			this.type = 'image';
			this.object = new Element('img').setProperties({id: this.iframeId, width: this.contentsWidth, height: this.contentsHeight, src: url, title: title});
		}
		// Bookmark Content
		else if(url.match(/#/) ) {
			this.type = 'bookmark';
			this.prefix = url.split('#')[1];
			this.divId = this.prefix + "-wire";
			this.object = $(this.prefix);
			this.containerDiv = ( !$(this.divId) ? (new Element('div',{id: this.divId , width: this.contentsWidth, height: this.contentsHeight}).injectInside(this.object)) : $(this.divId));
		}

		// YouTube
		else if (url.match(/youtube\.com\/watch/i)) {
			this.type = 'flash';
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.dataFile = "http://www.youtube.com/v/"+this.videoID+"&autoplay=1";
		}

		// DailyMotion
		else if (url.match(/dailymotion\.com/i)) {
			this.type = 'flash';
			this.dataFile = url;
		}

		// Metacafe
		else if (url.match(/metacafe\.com\/watch/i)) {
			this.type = 'flash';
			var videoId = url.split('/');
			this.videoID = videoId[4];
			this.dataFile = "http://www.metacafe.com/fplayer/"+this.videoID+"/.swf";
		}

		// Google Video
		else if (url.match(/google\.com\/videoplay/i)) {
			this.type = 'flash';
			var videoId = url.split('=');
			this.videoID = videoId[1];
			this.dataFile = "http://video.google.com/googleplayer.swf?docId="+this.videoID+"&autoplay=1&hl=en";
		}

		// Flash .SWF
		else if (url.match(/\.(swf|\?)/i)) {
			this.type = 'flash';
			this.dataFile = url;
		}
	
		// Flash .FLV
		else if (url.match(/\.flv/i)) {
			this.type = 'flash';
			this.objectID = "flvvideo";
			this.dataFile = this.options.playerpath+"?file="+url+"&autostart=true&displayheight="+this.contentsHeight+"&usefullscreen="+this.fullscreen+"&backcolor="+this.options.backcolor+"&frontcolor="+this.options.frontcolor+"&lightcolor="+this.options.lightcolor;
		}

		// Quicktime .MOV
		else if (url.match(/\.mov/i)) {
			this.type = 'qt';
			if (this.options.controller=='true') {this.contentsHeight = (this.contentsHeight*1)+16};
			if (navigator.plugins && navigator.plugins.length) {
				this.object = '<object id="splashBox" standby="loading quicktime..." type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'"><param name="src" value="'+url+'" /><param name="scale" value="aspect" /><param name="controller" value="'+this.options.controller+'" /><param name="autoplay" value="'+this.options.autoplay+'" /><param name="bgcolor" value="'+this.options.bgcolor+'" /><param name="enablejavascript" value="true" /></object>';
			} else {
				this.object = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" standby="loading quicktime..." codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" id="splashBox"><param name="src" value="'+url+'" /><param name="scale" value="aspect" /><param name="controller" value="'+this.options.controller+'" /><param name="autoplay" value="'+this.options.autoplay+'" /><param name="bgcolor" value="'+this.options.bgcolor+'" /><param name="enablejavascript" value="true" /></object>';
			}
		}

		// Windows Media .WMV
		else if (url.match(/\.wmv/i)) {
			this.type = 'qt';
			if (this.options.controller=='true') {this.contentsHeight = (this.contentsHeight*1)+16};
			if (navigator.plugins && navigator.plugins.length) {
				this.object = '<object id="splashBox" standby="loading windows media..." type="video/x-ms-wmv" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" /><param name="src" value="'+url+'" /><param name="autoStart" value="'+this.options.autoplay+'" /></object>';
			} else {
				this.object = '<object id="splashBox" standby="loading windows media..." classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" type="video/x-ms-wmv" data="'+url+'" width="'+this.contentsWidth+'" height="'+this.contentsHeight+'" /><param name="filename" value="'+url+'" /><param name="showcontrols" value="'+this.options.controller+'"><param name="autoStart" value="'+this.options.autoplay+'" /><param name="stretchToFit" value="true" /></object>';
			}
		}

		// iFrame content
		else {
			this.type = 'iframe';
			this.iframeId = "lbFrame_" + new Date().getTime();
			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({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)+'px', marginLeft: this.center.style.marginLeft, width:this.center.style.width, display: ''});
			this.fx.content.start(1);
			this.step++;

		case 3:
			if (this.type == 'image'){
				this.object.injectInside(this.canvas);
			}
			else if (this.type == 'bookmark'){
				this.object.injectInside(this.canvas);
			}
			else if (this.type == 'iframe'){
				this.object.injectInside(this.canvas);
			}
			else if (this.type == 'flash'){
				this.swfObj = new Element('div').setProperty('id', 'swfObj').injectInside(this.canvas);
				var flashvars = {};
				var params = {};
					params.quality="best";
					params.movie = this.dataFile;
					params.menu=false;
					params.allowScriptAccess="always";
				var attributes = {};
				swfobject.embedSWF(this.dataFile, "swfObj", this.contentsWidth, this.contentsHeight, "9.0.124", false, flashvars, params, attributes);
			} else {
				this.canvas.setHTML(this.object);
			}
			this.currentObject = document.getElementById('splashBox');
			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;
		}
	},

	matchOrDefault: function(str, re, val){
		var hasQuery = str.match(re);
		return hasQuery ? hasQuery[1] : val;
	},

	close: function(){
			if( this.type == 'bookmark' ) {
				$(this.prefix).injectInside(document.body);
				//$(this.object).innerHTML="";
				//$(this.object).setHTML('');
			}
			if (this.type == 'qt' && window.webkit) {
				this.currentObject.Stop();
			}
			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;
		
		for (var f in this.fx) this.fx[f].stop();
		if (this.step < 0) return;
		this.step = -1;

		this.center.style.display = this.bottomContainer.style.display = 'none';
		this.fx.overlay.chain(this.setup.pass(false, this)).start(0);
		this.options.nowstatus = true;
		return false;
	}

};

