/*
	Videobox v0.7 - The ultimate lightweight videobox
	by Frank Teunisse of Dijksman.com (http://www.dijksman.com) - MIT-style license.
	Plays files from youtube or with local installed JW player
	Based on Slimbox v1.41 by Christophe Beyls.
*/

var videobox = {
	
	init: function(options){
		this.options = $extend({
			resizeDuration: 400,
			resizeTransition: false,	// default transition
			initialWidth: 250,
			initialHeight: 250,
			animateCaption: true,
			showCounter: true
		}, options || {});

		this.s1;
		this.anchors = [];
		this.scanAnchors();
		
		this.eventKeyDown = this.keyboardListener.bindAsEventListener(this);
		this.eventPosition = this.position.bind(this);

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

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

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

		this.caption = new Element('div', {'id': 'lbCaption'}).injectInside(this.bottom);
		this.number = new Element('div', {'id': 'lbNumber'}).injectInside(this.bottom);
		new Element('div', {'styles': {'clear': 'both'}}).injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			resize: this.center.effects($extend({duration: this.options.resizeDuration, onComplete: nextEffect}, this.options.resizeTransition ? {transition: this.options.resizeTransition} : {})),
			image: this.image.effect('opacity', {duration: 500, onComplete: nextEffect}),
			bottom: this.bottom.effect('margin-top', {duration: 400, onComplete: nextEffect})
		};

	},

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

	show: function(url, title){
		return this.open([[url, title.replace(" | ","<br />")]], 0);
	},

	open: function(images, imageNum){
		this.images = images;
		this.position();
		this.setup(true);
		this.top = window.getScrollTop() + (window.getHeight() / 15);
		this.center.setStyles({top: this.top, display: ''});
		this.fx.overlay.start(0.8);
		return this.changeImage(imageNum);
	},

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

	setup: function(open){
		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;
			if(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();
		}
	},

	changeImage: function(imageNum){

		this.step = 1;
		this.activeImage = imageNum;

		this.bottomContainer.style.display = 'none';
		this.fx.image.hide();
		
		this.center.className = 'lbLoading';
		
		this.nextEffect();
		return false;
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.center.className = '';
			this.image.setHTML('<div id="videoplayer">De video wordt geladen.<br /><sub>U heeft <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe Flash Player</a> nodig om deze video te bekijken.</sub></div>');
			
			var urlarray = this.images[this.activeImage][0].split('?v=');
			video = urlarray[urlarray.length-1];
			
			
			this.image.style.width = this.bottom.style.width = 425+'px';//this.preload.width+'px';
			this.image.style.height = 356+'px';//this.preload.height+'px';

			this.caption.setHTML(this.images[this.activeImage][1] || '');

			if (this.center.clientHeight != this.image.offsetHeight){
				this.fx.resize.start({height: this.image.offsetHeight});
				break;
			}
			this.step++;
		case 2:
			if (this.center.clientWidth != this.image.offsetWidth){
				this.fx.resize.start({width: this.image.offsetWidth, marginLeft: -this.image.offsetWidth/2});
				break;
			}
			this.step++;
		case 3:
			this.bottomContainer.setStyles({top: this.top + this.center.clientHeight, height: 0, marginLeft: this.center.style.marginLeft, display: ''});
			this.fx.image.start(1);
			break;
		case 4:
			if (this.options.animateCaption){
				this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);
				break;
			}
			this.bottomContainer.style.height = '';
		case 5:
			this.step = 0;
			//Laad het filmpje in
			if(this.images[this.activeImage][0].indexOf(".flv") == -1) //If it's a youtube movie
				{	
				var params = { allowScriptAccess: "always" };
				var atts = { id: "ytplayer" };
				swfobject.embedSWF("http://www.youtube.com/v/"+video+"&enablejsapi=1&playerapiid=ytplayer&autoplay=1","videoplayer", "425", "356", "8", null, null, params, atts); 	
				}
			else // If it's a normal file, to be played with JW player
				{
				var urlarray = video.split('/');
				video = urlarray[urlarray.length-1];
			
				s1 = new SWFObject("includes/player.swf","ply","425","356","9","#FFFFFF");
				s1.addParam("allowfullscreen","true");
				s1.addParam("allowscriptaccess","always");
				var flashvars = "file=../flv/"+video+"&backcolor=E6E6E6&fontcolor=8C4F9A&lightcolor=8C4F9A"; //+"&image=preview.jpg"
				s1.addParam("flashvars",flashvars);
				s1.write("videoplayer");
				}
		}
	},

	close: function(){
		if (this.step < 0) return;
		if((!(window.player === undefined)) && (!(window.player === null))) { player.sendEvent("STOP"); }
		
		if(!(window.ytplayer === undefined)) { 
			if(window.ytplayer.stopVideo()) {window.ytplayer.clearVideo();}
			this.image.removeChild(window.ytplayer);
			} //swfobject.unloadClip(ytplayer);
		
		if(!($('ply') === null)) { $('videoplayer').removeChild($('ply')); }
		
		
		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;
	},
	
	scanAnchors: function() {
		this.anchors = [];
		$each(document.links, function(el){
			if (el.rel && el.rel.test(/^videobox/i)){
				el.onclick = this.click.pass(el, this);
				this.anchors.push(el);
			}
		}, this);
	}
};

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

var player;
var lastbuffer = -1;

function playerReady(obj) {
	var id = obj['id'];
	var version = obj['version'];
	var client = obj['client'];
	player = document.getElementById(id);
	player.sendEvent("PLAY",true);
	player.addModelListener("STATE","modefunc");
	player.addModelListener("BUFFER","bufferfunc");

};
function bufferfunc(obj) {if((obj.percentage == 1) && (obj.percentage == lastbuffer)) videobox.close(); else lastbuffer = obj.percentage;};
function modefunc(obj) {if(obj.newstate=="COMPLETED") videobox.close(); };

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("ytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    ytplayer.setVolume(100);
    }

function onytplayerStateChange(newState) {
    if(newState==0) { videobox.close(); }
     } 