	// CREATIONAL
	
	// COPYRIGHT  : 2010 : CREATIONAL : WWW.CREATIONAL.NL : ALL RIGHTS RESERVED
	
	// JAVASCRIPT: Video Box Scripts
	
	// Based on Lightbox v2.04 by Lokesh Dhakar


	//
	//  Configuration
	//
	VideoboxOptions = Object.extend({
		fileLoadingImage:        '/img/vb_loading.gif',     
		fileBottomNavCloseImage: '/img/vb_closelabel.gif',
	
		overlayOpacity: 0.8,   // controls transparency of shadow videoOverlay
	
		animate: true,         // toggles resizing animations
		resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)
	
		borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable
	
		// When grouping videos this is used to write: Image # of #.
		// Change it for non-english localization
		labelVideo: "Video",
		labelOf: "of",
		labelNext: "Next"
	}, window.VideoboxOptions || {});
	
	// -----------------------------------------------------------------------------------
	
	var Videobox = Class.create();
	
	Videobox.prototype = {
		videoArray: [],
		activeVideo: undefined,
		
		// initialize()
		// Constructor runs on completion of the DOM loading. Calls updateVideoList and then
		// the function inserts html at the bottom of the page which is used to display the shadow 
		// videoOverlay and the image container.
		//
		initialize: function() {    
			
			this.updateVideoList();
			
			this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
	
			if (VideoboxOptions.resizeSpeed > 10) VideoboxOptions.resizeSpeed = 10;
			if (VideoboxOptions.resizeSpeed < 1)  VideoboxOptions.resizeSpeed = 1;
	
			this.resizeDuration = VideoboxOptions.animate ? ((11 - VideoboxOptions.resizeSpeed) * 0.15) : 0;
			this.overlayDuration = VideoboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration
	
			// When Videobox starts it will resize itself from 250 by 250 to the current image dimension.
			// If animations are turned off, it will be hidden as to prevent a flicker of a
			// white 250 by 250 box.
			var size = (VideoboxOptions.animate ? 250 : 1) + 'px';
			
	
			// Code inserts html at the bottom of the page that looks similar to this:
			//
			//  <div id="videoOverlay"></div>
			//  <div id="videobox">
			//      <div id="videoOuterContainer">
			//          <div id="videoContainer">
			//              <img id="videoboxVideo">
			
			//              <div style="" id="videoHoverNav">
			//                  <a href="#" id="videoPrevious"></a>
			//                  <a href="#" id="videoNext"></a>
			//              </div>
			
			//              <div id="videoLoading">
			//                  <a href="#" id="videoLoadingLink">
			//                      <img src="img/vb_loading.gif">
			//                  </a>
			//              </div>
			//          </div>
			//      </div>
			//      <div id="videoDataContainer">
			//          <div id="videoData">
			//              <div id="videoDetails">
			//                  <span id="videoCaption"></span>
			//                  <a id="videoNumberDisplay">
			//						<span id="videoNext"></span>
			//					</a>
			//              </div>
			//              <div id="videoBottomNav">
			//                  <a href="#" id="videoBottomNavClose">
			//                      <img src="img/vb_close.gif">
			//                  </a>
			//              </div>
			//          </div>
			//      </div>
			//  </div>
	
	
			var objBody = $$('body')[0];
	
			objBody.appendChild(Builder.node('div',{id:'videoOverlay'}));
		
			objBody.appendChild(Builder.node('div',{id:'videobox'}, [
				Builder.node('div',{id:'videoOuterContainer'}, 
					Builder.node('div',{id:'videoContainer'}, [
						Builder.node('img',{id:'videoboxVideo'}), 
						Builder.node('div',{id:'videoLoading'}, 
							Builder.node('a',{id:'videoLoadingLink', href: '#' }, 
	
								Builder.node('img', {src: VideoboxOptions.fileLoadingImage})
							)
						)
					])
				),
				Builder.node('div', {id:'videoDataContainer'},
					Builder.node('div',{id:'videoData'}, [
						Builder.node('div',{id:'videoDetails'}, [
							Builder.node('span',{id:'videoCaption'}),
							Builder.node('a',{id:'videoNumberDisplay', href: '#'},
								Builder.node('span',{id:'videoNext' })			 
							)
						]),
						Builder.node('div',{id:'videoBottomNav'},
							Builder.node('a',{id:'videoBottomNavClose', href: '#' },
								Builder.node('img', { src: VideoboxOptions.fileBottomNavCloseImage })
							)
						)
					])
				)
			]));
	
	
			$('videoOverlay').hide().observe('click', (function() { this.end(); }).bind(this));
			$('videobox').hide().observe('click', (function(event) { if (event.element().id == 'videobox') this.end(); }).bind(this));
			$('videoOuterContainer').setStyle({ width: size, height: size });
			$('videoNumberDisplay').observe('click', (function(event) { event.stop(); this.changeVideo(this.activeVideo + 1); }).bindAsEventListener(this));
			$('videoLoadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
			$('videoBottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
	
			var th = this;
			(function(){
				var ids = 
					'videoOverlay videobox videoOuterContainer videoContainer videoboxVideo videoNext videoLoading videoLoadingLink ' + 
					'videoDataContainer videoData videoDetails videoCaption videoNumberDisplay videoBottomNav videoBottomNavClose';   
				$w(ids).each(function(id){ th[id] = $(id); });
			}).defer();
		},
	
		//
		// updateVideoList()
		// Loops through anchor tags looking for 'videobox' references and applies onclick
		// events to appropriate links. You can rerun after dynamically adding images w/ajax.
		//
		updateVideoList: function() {   
			
			this.updateVideoList = Prototype.emptyFunction;
	
			document.observe('click', (function(event){
				var target = event.findElement('a[rel^=videobox]') || event.findElement('area[rel^=videobox]');
				if (target) {
					event.stop();
					this.start(target);
				}
			}).bind(this));
		},
		
		//
		//  start()
		//  Display videoOverlay and videobox. If video is part of a set, add siblings to videoArray.
		//
		start: function(videoLink) {    
	
			$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
	
			// stretch videoOverlay to fill page and fade in
			var arrayPageSize = this.getPageSize();
			$('videoOverlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
	
			new Effect.Appear(this.videoOverlay, { duration: this.overlayDuration, from: 0.0, to: VideoboxOptions.overlayOpacity });
	
			this.videoArray = [];
			var videoNum = 0;       
	
			if ((videoLink.rel == 'videobox')){
				// if video is NOT part of a set, add single image to videoArray
				this.videoArray.push([videoLink.href, videoLink.title]);         
			} else {
				// if video is part of a set..
				this.videoArray = 
					$$(videoLink.tagName + '[href][rel="' + videoLink.rel + '"]').
					collect(function(anchor){ return [anchor.href, anchor.title]; }).
					uniq();
				
				while (this.videoArray[videoNum][0] != videoLink.href) { videoNum++; }
			}
	
			// calculate top and left offset for the videobox 
			var arrayPageScroll = document.viewport.getScrollOffsets();
			var videoboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
			var videoboxLeft = arrayPageScroll[0];
			this.videobox.setStyle({ top: videoboxTop + 'px', left: videoboxLeft + 'px' }).show();
			
			this.changeVideo(videoNum);
		},
	
		//
		//  changeVideo()
		//  Hide most elements and preload image in preparation for resizing image container.
		//
		changeVideo: function(videoNum) {   
			
			this.activeVideo = videoNum; // update global var
	
			// hide elements during transition
			if (VideoboxOptions.animate) this.videoLoading.show();
			this.videoboxVideo.hide();
			this.videoNext.hide();
			// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
			this.videoDataContainer.setStyle({opacity: .0001});
			this.videoNumberDisplay.hide();      
			
			var videoFlashvars = false;
			var videoWidth = 425;
			var videoHeight = 350;
	
			var url = this.videoArray[this.activeVideo][0];
			var swfURL = url;
			var pos = swfURL.indexOf('?');
			if (pos > -1) { 
				swfURL = swfURL.substring(0,pos); 
				var videoFlashvars = url.toQueryParams();
				if (videoFlashvars['width']) { videoWidth = 1*videoFlashvars['width']; }
				if (videoFlashvars['height']) { videoHeight = 1*videoFlashvars['height']; }
			}

			this.resizeVideoContainer(videoWidth, videoHeight);
			
			//var imgPreloader = new Image();			
			// once image is preloaded, resize image container	
			//imgPreloader.onload = (function(){
			//	this.videoboxVideo.src = this.videoArray[this.activeVideo][0];
			//	this.resizeVideoContainer(imgPreloader.width, imgPreloader.height);
			//}).bind(this);
			//imgPreloader.src = this.videoArray[this.activeVideo][0];
		},
	
		//
		//  resizeVideoContainer()
		//
		resizeVideoContainer: function(videoWidth, videoHeight) {
	
			// get current width and height
			var widthCurrent  = this.videoOuterContainer.getWidth();
			var heightCurrent = this.videoOuterContainer.getHeight();
	
			// get new width and height
			var widthNew  = (videoWidth  + VideoboxOptions.borderSize * 2);
			var heightNew = (videoHeight + VideoboxOptions.borderSize * 2);

			// scalars based on change from old to new
			var xScale = (widthNew  / widthCurrent)  * 100;
			var yScale = (heightNew / heightCurrent) * 100;
	
			// calculate size difference between new and old image, and resize if necessary
			var wDiff = widthCurrent - widthNew;
			var hDiff = heightCurrent - heightNew;
	
			if (hDiff != 0) new Effect.Scale(this.videoOuterContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
			if (wDiff != 0) new Effect.Scale(this.videoOuterContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 
	
			// if new and old image are same size and no scaling transition is necessary, 
			// do a quick pause to prevent image flicker.
			var timeout = 0;
			if ((hDiff == 0) && (wDiff == 0)){
				timeout = 100;
				if (Prototype.Browser.IE) timeout = 250;   
			}
	
			(function(){
				//this.videoPrevious.setStyle({ height: videoHeight + 'px' });
				//this.videoNext.setStyle({ height: videoHeight + 'px' });
				this.videoDataContainer.setStyle({ width: widthNew + 'px' });
	
				//this.showVideo();
				
				new Effect.Appear(this.videoboxVideo, { 
					duration: this.resizeDuration, 
					queue: 'end', 
					afterFinish: (function(){ this.showVideo(); }).bind(this) 
				});
				
			}).bind(this).delay(timeout / 1000);
		},
		
		//
		//  showVideo()
		//  Display video and begin preloading neighbors.
		//
		showVideo: function(){

			var videoFlashvars = false;
			var videoParams = false;
			var videoWidth = 425;
			var videoHeight = 350;

			var url = this.videoArray[this.activeVideo][0];
			var swfURL = url;
			var pos = swfURL.indexOf('?');
			if (pos > -1) { 
				swfURL = swfURL.substring(0,pos); 
				videoFlashvars = url.toQueryParams();
				if (videoFlashvars['width']) { videoWidth = 1*videoFlashvars['width']; }
				if (videoFlashvars['height']) { videoHeight = 1*videoFlashvars['height']; }
				if (videoFlashvars['cm_fullscreenbutton']) { videoParams.allowfullscreen = true; }
				if (this.videoArray.length > 1) { videoParams.wmode = 'transparent'; }
			}
			
			this.videoLoading.hide();
			
			swfobject.embedSWF(swfURL, this.videoboxVideo.id, videoWidth, videoHeight, "8.0.0", "expressInstall.swf",videoFlashvars,videoParams);
			
			this.updateDetails();
		},
		
	
		//
		//  updateDetails()
		//  Display videoCaption, image number, and bottom nav.
		//
		updateDetails: function() {
		
			// if videoCaption is not null
			if (this.videoArray[this.activeVideo][1] != ""){
				this.videoCaption.update(this.videoArray[this.activeVideo][1]).show();
			}
			
			// if image is part of set display 'Video x of x' 
			if (this.videoArray.length > 1){
				this.videoNumberDisplay.update( VideoboxOptions.labelVideo + ' ' + (this.activeVideo + 1) + ' ' + VideoboxOptions.labelOf + '  ' + this.videoArray.length + ' <span id="' + this.videoNext.id +'">' + VideoboxOptions.labelNext +'</span').show();
			}
	
			new Effect.Parallel(
				[ 
					new Effect.SlideDown(this.videoDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
					new Effect.Appear(this.videoDataContainer, { sync: true, duration: this.resizeDuration }) 
				], 
				{ 
					duration: this.resizeDuration, 
					afterFinish: (function() {
						// update videoOverlay size and update nav
						var arrayPageSize = this.getPageSize();
						this.videoOverlay.setStyle({ height: arrayPageSize[1] + 'px' });
						this.updateNav();
					}).bind(this)
				} 
			);
		},
	
		//
		//  updateNav()
		//  Display appropriate previous and next hover navigation.
		//
		updateNav: function() {
	
			//this.videoHoverNav.show();               
	
			// if not first image in set, display prev image button
			//if (this.activeVideo > 0) this.videoPrevious.show();
	
			// if not last image in set, display next image button
			if (this.activeVideo < (this.videoArray.length - 1)) this.videoNext.show();
			
			this.enableKeyboardNav();
		},
	
		//
		//  enableKeyboardNav()
		//
		enableKeyboardNav: function() {
			document.observe('keydown', this.keyboardAction); 
		},
	
		//
		//  disableKeyboardNav()
		//
		disableKeyboardNav: function() {
			document.stopObserving('keydown', this.keyboardAction); 
		},
	
		//
		//  keyboardAction()
		//
		keyboardAction: function(event) {
			var keycode = event.keyCode;
	
			var escapeKey;
			if (event.DOM_VK_ESCAPE) {  // mozilla
				escapeKey = event.DOM_VK_ESCAPE;
			} else { // ie
				escapeKey = 27;
			}
	
			var key = String.fromCharCode(keycode).toLowerCase();
			
			if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close videobox
				this.end();
			} else if ((key == 'p') || (keycode == 37)){ // display previous video
				if (this.activeVideo != 0){
					this.disableKeyboardNav();
					this.changeVideo(this.activeVideo - 1);
				}
			} else if ((key == 'n') || (keycode == 39)){ // display next video
				if (this.activeVideo != (this.videoArray.length - 1)){
					this.disableKeyboardNav();
					this.changeVideo(this.activeVideo + 1);
				}
			}
		},
	
		//
		//  preloadNeighborImages()
		//  Preload previous and next images.
		//
		preloadNeighborImages: function(){
			var preloadNextImage, preloadPrevImage;
			if (this.videoArray.length > this.activeVideo + 1){
				preloadNextImage = new Image();
				preloadNextImage.src = this.videoArray[this.activeVideo + 1][0];
			}
			if (this.activeVideo > 0){
				preloadPrevImage = new Image();
				preloadPrevImage.src = this.videoArray[this.activeVideo - 1][0];
			}
		
		},
	
		//
		//  end()
		//
		end: function() {
			this.disableKeyboardNav();
			this.videobox.hide();
			new Effect.Fade(this.videoOverlay, { duration: this.overlayDuration });
			$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
		},
	
		//
		//  getPageSize()
		//
		getPageSize: function() {
				
			 var xScroll, yScroll;
			
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			
			var windowWidth, windowHeight;
			
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
		
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
	
			return [pageWidth,pageHeight];
		}
	}
	
	document.observe('dom:loaded', function () { new Videobox(); });