/**
 * @author Nathan Kelly - http://www.nathan-kelly.com/
 *  my email address is my first name @nathan-kelly.com
 * @copyright 2009 Nathan Kelly
 * @package nk-lightbox
 * @version 1.0.3
 * @url http://projects.nathan-kelly.com/nlightbox/
 * @dependencies 
 * 	prototype.js 1.6.0.2+ (http://www.prototypejs.org/)
 *	scriptaculous.js 1.8.1+ (http://script.aculo.us/)
 * @license
 *	Creative Commons Attribution 2.5 Australia License
 *	http://creativecommons.org/licenses/by/2.5/au/
 * @credits (and much deserved too please read):
 *	Based on Lightbox v2.04
 *	Original Author: Lokesh Dhakar - http://www.lokeshdhakar.com
 *  http://lokeshdhakar.com/projects/lightbox2/
 */

//
//  Configuration
//
nLightboxOptions = Object.extend({
	// set the base url to your nLightbox "Interface Images" directory here
	// eg: http://www.mysite.com/images/nlightbox/ (be sure to include the trailing slash)
	// Note: this is not the directory for images that are displayed withinin the nlightbox
	// this is the directory for your navigation, loading throbber, background images etc.
	// By adding these images here they are placed in the preload queue to minimize
	// any delay when the nlightbox is activated.
	//baseUrl: 'http://www.aafonline.com.au/design/aaf/images/nlightbox/',
	baseUrl: 'http://www.aaf.net.au/design/aaf/images/nlightbox/',
	// if you use images in your nlightbox interface list them here for preloading
	// make sure you add your throbber (loading image) so that it is preloaded before
	// the nlightbox is opened otherwise it may not show up when the nlightbox is first activated.
	interfaceImages: [
		'ui-throbber.gif',
		'ui-nlightbox-nav.png',
		'ui-nlightbox-container-bg.png'
	],
	// define the image that will be used for your loading throbber
	throbber: 'ui-throbber.gif',
	// the text for your image data (navigation and image count)
	// do not change the labels, place the required text inside the ['']	
	imageDataLabels: {
		'labelPrev':	['Previous'],
		'labelClose':	['Close'],
		'labelNext':	['Next'],
		'labelRestart': ['Restart'],
		'labelImage':	['Image'],
		'labelOf':	['of']
	},
	// showImageCount [true|false], set to true if you want the image count to
	// be displayed in the image-data-container. This option is only available
	// when images are grouped, if there is only one image in a group the image
	// count is ignored regardless of this setting.
	showImageCount: true,
	// Caption Settings
	// showCaptions [true|false], pretty self explanitary, if false no captions
	// will be displayed full stop.
	// If true captions will be displayed according to extend and append caption
	// settings below.
	showCaptions: true,
	// extendedCaptions [true|false], if true enables ability to append
	// HTML elements to the "Regular Caption" or replace the "Regular Caption".
	// The element to be matched is a div with the class "nlbext-caption" this
	// div must be contained within the same parent node as the nlightbox image link
	// and it must be the nextSibling, for example:
	// <li>
	// 	<a href="#" title="Regular Caption" rel="nlightbox">
	// 		<img src="#" alt="#" />
	//	</a>
	//	<div class="nlbext-caption">This is an Extended Caption that can contain HTML elements</div>
	// </li>
	extendedCaptions: true,
	// Append Captions [true|false] default [false], extendedCaptions must be true
	// for appendCaptions to have any effect. if true the "Extended Caption"
	// will be appended to the "Regular Caption" as in the above example. If
	// false only the "Extended Caption" will be used and the "Regular Caption"
	// will be ignored.
	// If extendedCaptions "and" appendCaptions are true the following output will be produced:
	// 	Regular Caption
	// 	This is an Extended Caption that can contain HTML elements
	// If appendCaptions is false the following output will be produced:
	// 	This is an Extended Caption that can contain HTML elements
	appendCaptions: true,
	// End Caption Settings
	//
	// nlightbox start size, the default size that the nlightbox should always starts at
	// start size is in pixels so (150 = 150px)
	nlightboxStartSize: 150,
	// controls transparency of the overlay 0.0 = invisible, 1.0 = solid
	overlayOpacity: 0.9,
	// toggles resizing animations
	// leave this set to true in this version as it is not fully supported
	animate: true,
	 // controls the speed of the image resizing animations (1=slowest and 10=fastest)
	resizeSpeed: 8,
	 //if you adjust the nlightbox container padding in the CSS, you will need
	 // to update this variable to match.
	borderSize: 10
},window.nLightboxOptions || {});

// -----------------------------------------------------------------------------------

nLightbox = Class.create({

//nLightbox.prototype = {
	_imageArray: [],
	//_activeImage: null,

	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateImageList and then
	// the function inserts html at the bottom of the page which is used to display the shadow
	// overlay and the image container.
	//
	initialize: function() {
	// first preload the interface images
	//this.preloadInterface();
		this.updateImageList();

		this.userInteraction = this.userInteraction.bindAsEventListener(this);

		if (nLightboxOptions.resizeSpeed > 10) nLightboxOptions.resizeSpeed = 10;
		if (nLightboxOptions.resizeSpeed < 1)  nLightboxOptions.resizeSpeed = 1;

		this.resizeDuration = nLightboxOptions.animate ? ((11 - nLightboxOptions.resizeSpeed) * 0.15) : 0;
		this.overlayDuration = nLightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

		// When nLightbox starts it will resize itself from
		// nLightboxOptions.nlightboxStartSize by nLightboxOptions.nlightboxStartSize
		// to the current image dimension.
		// If animations are turned off, it will be hidden as to prevent a flicker of a
		// nLightboxOptions.nlightboxStartSize by nLightboxOptions.nlightboxStartSize box.
		var size = (nLightboxOptions.animate ? nLightboxOptions.nlightboxStartSize : 1) + 'px';

		// Code inserts html at the bottom of the page that looks similar to this:
		//
		//  <div id="overlay"></div>
		//  <div id="nlightbox">
		//	  <div id="nlightbox-container">
		//		  <div id="image-container">
		//			  <img id="nlightbox-image">
		//			  <div id="loading">
		//				  <a href="#" id="loading-link">
		//					  <img src="images/loading.gif">
		//				  </a>
		//			  </div>
		//		  </div>
		//	  </div>
		//	  <div id="image-data-container">
		//		  <div id="image-data">
		//			  <div id="image-details">
		//				  <span id="caption"></span>
		//				  <span id="number-display"></span>
		//			  </div>
		//			  <ul id="bottom-nav">
		//				<li id="prev-link"><a id="prev-link-anchor" href="#"></a></li>
		//				<li id="close-link"><a id="close-link-anchor" href="#"></a></li>
		//				<li id="next-link"><a id="next-link-anchor" href="#"></a></li>
		//			  </ul>
		//		  </div>
		//	  </div>
		//  </div>


		var objBody = $$('body')[0];

		objBody.appendChild(Builder.node('div', {id:'overlay'}));

		objBody.appendChild(Builder.node('div', {id:'nlightbox'}, [
			Builder.node('div', {id:'nlightbox-container'},
				Builder.node('div', {id:'image-container'}, [
					Builder.node('img', {id:'nlightbox-image'}),
					Builder.node('div', {id:'loading'},
						//Builder.node('a', {id:'loading-link', href: '#' },
							Builder.node('img', {src: nLightboxOptions.baseUrl + nLightboxOptions.throbber})
						//)
					)
				])
			),
			Builder.node('div', {id:'image-data-container', className: 'closed'},
				Builder.node('div', {id:'image-data'}, [
					Builder.node('div', {id:'image-details'}, [
						Builder.node('div', {id:'caption'}),
						Builder.node('span', {id:'number-display'})
					]),
					Builder.node('ul', {id:'bottom-nav'}, [
				Builder.node('li', {id:'prev-link', className: 'disabled'}, [
						Builder.node('a', {id:'prev-link-anchor', href: '#' }, [
					Builder._text(nLightboxOptions.imageDataLabels.labelPrev[0])
				])
			]),
			Builder.node('li', {id:'close-link'}, [
						Builder.node('a', {id:'close-link-anchor', href: '#' }, [
					Builder._text(nLightboxOptions.imageDataLabels.labelClose[0])
				])
			]),
			Builder.node('li', {id:'next-link', className: 'disabled'}, [
						Builder.node('a', {id:'next-link-anchor', href: '#' }, [
					Builder._text(nLightboxOptions.imageDataLabels.labelNext[0])
				])
			])
					])
				])
			)
		]));
		
		$('prev-link').setOpacity(0.1);
		$('next-link').setOpacity(0.1);

		// Safari 2.0.3 back to 1.3.2 (and possibly lower) doesn't honor event.stop();
		// or event.preventDefault(); So far there is no work around that I can find
		// for this issue so for now tough luck to users of these browsers, I'm not
		// going to start browser sniffing for old browsers.
		
		$('overlay').hide();
		$('nlightbox').hide();

		//$('nlightbox-container').setStyle({ width: size, height: size });		
		
		$('nlightbox-container').setStyle({ width: size, height: size }).observe('click', (
			function(event) {
				event.stop();
			}
		).bindAsEventListener(this));
		
		$('nlightbox-image').hide();
		
		$('image-data-container').hide().observe('click', (
			function(event) {
				event.stop();
			}
		).bindAsEventListener(this));;
		
		$('prev-link-anchor').observe('click', (
			function(event) {
				this.disableInteraction();
				if ($('prev-link').className != 'disabled') {
					this.changeImage(this._activeImage - 1);
				}
				event.stop();
			}
		).bindAsEventListener(this));

		$('next-link-anchor').observe('click', (
			function(event) {
				this.disableInteraction();
				if ($('next-link').className != 'disabled') {
					if (this._imageArray.length > 1 && this._activeImage == (this._imageArray.length -1)) {
						this.changeImage(this._activeImage - this._imageArray.length + 1);
					} else {
						this.changeImage(this._activeImage + 1);
					}
				}
				event.stop();
			}
		).bindAsEventListener(this));

		// Maybe put this on a timeout so clciking it doesn't break the layout?
		//$('loading-link').observe('click', (
		//	function(event) {
		//		this.end(graceful);
		//		event.stop();
		//	}
		//).bind(this));
		
		$('close-link-anchor').observe('click', (
			function(event) {				
				this.end();
				event.stop();
			}
		).bind(this));
		
		var th = this;
		(function(){
			var ids =
				'overlay nlightbox nlightbox-container image-container nlightbox-image prev-link prev-link-anchor close-link close-link-anchor next-link next-link-anchor loading loading-link ' +
				'image-data-container image-data image-details caption number-display bottom-nav';
			$w(ids).each(function(id){ th[id] = $(id); });
		}).defer();
	},

	//
	// updateImageList()
	// Loops through anchor tags looking for 'nlightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
	//
	updateImageList: function() {
		this.updateImageList = Prototype.emptyFunction;

		document.observe('click', (
			function(event){
				//if (event && event.preventDefault) event.preventDefault();
				var target = event.findElement('a[rel^=nlightbox]') || event.findElement('area[rel^=nlightbox]');
				if (target) {				
					this.start(target);					
					event.stop();
				}					
			}
		).bind(this));
	},

	//
	//  start()
	//  Display overlay and nlightbox. If image is part of a set, add siblings to _imageArray.
	//
	start: function(imageLink) {		

		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

		// stretch overlay to fill page and fade in
		var arrayPageSize = this.getPageSize();
		$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', cursor: 'wait' });
		$('nlightbox').setStyle({ cursor: 'wait' });
		
		new Effect.Appear(this.overlay, {
			duration: this.overlayDuration,
			from: 0.0,
			to: nLightboxOptions.overlayOpacity 
		});

		this._imageArray = [];
		var imageNum = 0;
		var captionNode;		
			
		if ((imageLink.rel == 'nlightbox')){
			// Check if we are using extended captions
			if ( nLightboxOptions.showCaptions === true ){
				if ( nLightboxOptions.extendedCaptions === true ){				
					captionNode = imageLink.nextSibling;
					while ( captionNode && captionNode.nodeType == "3" ){
						captionNode = captionNode.nextSibling;
					}
					// make sure we found an extended caption
					if (captionNode && nLightboxOptions.appendCaptions === true) {
						captionNode = imageLink.title + ' ' + captionNode.innerHTML;
					} else if (captionNode && nLightboxOptions.appendCaptions === false) {
						captionNode = captionNode.innerHTML;
					} else {					
						captionNode = imageLink.title;
					}
				} else {
					captionNode = imageLink.title;	
				}
			}
			// if image is NOT part of a set, add single image to _imageArray
			this._imageArray.push([imageLink.href, captionNode]);			
		} else {
			// if image is part of a set..			
			this._imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').collect(function(anchor){
					// Check if we are using extended captions			
					if ( nLightboxOptions.showCaptions === true ){
						if ( nLightboxOptions.extendedCaptions === true ){				
							captionNode = anchor.nextSibling;
							while ( captionNode && captionNode.nodeType == "3" ){
								captionNode = captionNode.nextSibling;
							}
							// make sure we found an extended caption
							if (captionNode && nLightboxOptions.appendCaptions === true) {
								captionNode = anchor.title + ' ' + captionNode.innerHTML;
							} else if (captionNode && nLightboxOptions.appendCaptions === false) {
								captionNode = captionNode.innerHTML;
							} else {					
								captionNode = anchor.title;
							}
						} else {
							captionNode = anchor.title;
						}						
					}
					return [anchor.href, captionNode]; 
				}).uniq();			
			while (this._imageArray[imageNum][0] != imageLink.href) { imageNum++; }
		}

		// calculate top and left offset for the nlightbox
		var arrayPageScroll = document.viewport.getScrollOffsets();
		var nlightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
		var nlightboxLeft = arrayPageScroll[0];
		$('nlightbox').setStyle({ top: nlightboxTop + 'px', left: nlightboxLeft + 'px' }).show();
		this.changeImage(imageNum);
	},
	
	changeImage: function(imageNum) {
		this._activeImage = imageNum;
		var imgPreloader = new Image();
		if ($('image-data-container').className.match(/closed/)) {
			new Effect.Parallel(
			[
				new Effect.Appear( 'loading', {
					sync: true,
					duration: this.resizeDuration
				}),
				new Effect.Fade( 'nlightbox-image', {
					sync: true,
					duration: this.resizeDuration
				})
			],
			{
				duration: this.resizeDuration,
				afterFinish: (function() {
					imgPreloader.onload = (function(){
						$('nlightbox-image').src = this._imageArray[this._activeImage][0];
						// workaround for Safari - make sure the image dimentions are set
						$('nlightbox-image').setStyle({ width: imgPreloader.width + 'px', height: imgPreloader.height + 'px' });				
						this.resizeImageContainer(imgPreloader.width, imgPreloader.height);					
					}).bind(this);
					imgPreloader.src = this._imageArray[this._activeImage][0];
				}).bind(this)
			});
		} else {
			new Effect.Parallel(
			[
				new Effect.Appear( 'loading', {
					sync: true,
					duration: this.resizeDuration
				}),
				new Effect.Fade( 'nlightbox-image', {
					sync: true,
					duration: this.resizeDuration
				}),
				new Effect.Fade( 'image-data-container', {
					sync: true,
					duration: this.resizeDuration
				}),
				new Effect.SlideUp( 'image-data-container', {
					sync: true,
					duration: this.resizeDuration
				})
			],
			{
				duration: this.resizeDuration,
				afterFinish: (function() {
					imgPreloader.onload = (function(){
						$('nlightbox-image').src = this._imageArray[this._activeImage][0];
						// workaround for Safari - make sure the image dimentions are set
						$('nlightbox-image').setStyle({ width: imgPreloader.width + 'px', height: imgPreloader.height + 'px' });				
						this.resizeImageContainer(imgPreloader.width, imgPreloader.height);					
					}).bind(this);
					imgPreloader.src = this._imageArray[this._activeImage][0];
				}).bind(this)
			});
		}
	},

	//
	//  resizeImageContainer()
	//
	resizeImageContainer: function(imgWidth, imgHeight) {

		// get current width and height
		var widthCurrent  = $('nlightbox-container').getWidth();
		var heightCurrent = $('nlightbox-container').getHeight();

		// get new width and height
		var widthNew  = (imgWidth  + nLightboxOptions.borderSize * 2);
		var heightNew = (imgHeight + nLightboxOptions.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;

		// this part of the script is being executed too soon, image is being
		// shown before container has finished resizing. Need to try running
		// a parallel effect and showImage() afterFinish.

		new Effect.Parallel(
		[
			new Effect.Scale('nlightbox-container', yScale, {
				scaleX: false,
				duration: this.resizeDuration,
				queue: 'front'
			}),
			new Effect.Scale('nlightbox-container', xScale, {
				scaleY: false,
				duration: this.resizeDuration,
				delay: this.resizeDuration
			})
		],
		{
			duration: this.resizeDuration,
			afterFinish: (function() {
				$('image-data-container').setStyle({ width: widthNew + 'px' });
				this.showImage();
			}).bind(this)
		});
	},
	//
	//  showImage()
	//  Display image and begin preloading neighbors.
	//
	showImage: function(){
		new Effect.Parallel(
		[
			new Effect.Fade( 'loading', {
				sync: true,
				duration: this.resizeDuration
			}),
			new Effect.Appear( 'nlightbox-image', {
				sync: true,
				duration: this.resizeDuration,
				queue: 'end'
			})
		],
		{
			duration: this.resizeDuration,
			afterFinish: (function() {
				this.updateDetails();
				this.preloadNeighborImages();
			}).bind(this)
		});
	},
	//
	//  updateDetails()
	//  Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
		// if caption is not empty
		this._imageArray[this._activeImage][1] != "" ? $('caption').update(this._imageArray[this._activeImage][1]).show() : null;
		// if image is part of set display 'Image x of x'
		if (nLightboxOptions.showImageCount === true && this._imageArray.length > 1){
			$('number-display').update( nLightboxOptions.imageDataLabels.labelImage[0] + ' ' + (this._activeImage + 1) + ' ' + nLightboxOptions.imageDataLabels.labelOf[0] + '  ' + this._imageArray.length).show();
		}

		new Effect.Parallel(
		[
			new Effect.SlideDown( 'image-data-container', {
				sync: true,
				duration: this.resizeDuration,
				from: 0.0,
				to: 1.0,
				afterFinish: function() {
					$('image-data-container').className = 'open';
				}
			}),
			new Effect.Appear( 'image-data-container', {
				sync: true,
				duration: this.resizeDuration
			})
		],
		{
			duration: this.resizeDuration,
			afterFinish: (function() {
				// update overlay size and update nav
				var arrayPageSize = this.getPageSize();
				this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
				this.updateNav();
			}).bind(this)
		});
	},
	//
	//  updateNav()
	//  Display appropriate previous and next hover navigation.
	//
	updateNav: function() {
		// if not first image in set, display prev image button
		if(this._activeImage != 0) {
			new Effect.Appear( 'prev-link', {
				from: $('prev-link').getOpacity(),
				to: 1.0,
				duration: 0.5,
				afterFinish: (function() {
					$('prev-link').className = 'enabled';
					this.enableInteraction();
				}).bind(this)
			});
		} else {
			new Effect.Fade( 'prev-link', {
				from: $('prev-link').getOpacity(),
				to: 0.1,
				duration: 0.5,
				afterFinish: (function() {
					$('prev-link').className = 'disabled';
					this.enableInteraction();
				}).bind(this)
			});
		}
		// if last image in set, and more than one image in the set
		// display back to start image button
		if (this._imageArray.length > 1 && this._activeImage == (this._imageArray.length -1)){
			new Effect.Fade( 'next-link', {
				from: $('next-link').getOpacity(),
				to: 0.0,
				duration: 0.5,
				afterFinish: (function() {
					$('next-link').className = 'restart';
					new Effect.Appear( 'next-link', {
						from: 0.0,
						to: 1.0,
						duration: 0.5
					})
					this.enableInteraction();
				}).bind(this)
			});
		} else if(this._activeImage != (this._imageArray.length - 1)){
			// if not last image in set, display next image button
			if ($('next-link').className.match(/restart/)) {
				new Effect.Fade( 'next-link', {
					from: $('next-link').getOpacity(),
					to: 0.0,
					duration: 0.5,
					afterFinish: (function() {
						$('next-link').className = 'enabled';
						new Effect.Appear( 'next-link', {
							from: 0.0,
							to: 1.0,
							duration: 0.5
						})
						this.enableInteraction();
					}).bind(this)
				});
			} else {
				new Effect.Appear( 'next-link', {
					from: $('next-link').getOpacity(),
					to: 1.0,
					duration: 0.5,
					afterFinish: (function() {
						$('next-link').className = 'enabled';
						this.enableInteraction();
					}).bind(this)
				});
			}
		} else {
			new Effect.Fade( 'next-link', {
				from: $('next-link').getOpacity(),
				to: 0.1,
				duration: 0.5,
				afterFinish: (function() {
					$('next-link').className = 'disabled';
					this.enableInteraction();
				}).bind(this)
			});
		}
	},
	//
	//  enableInteraction()
	//
	enableInteraction: function() {
		$('overlay').setStyle({ cursor: 'default' });
		$('nlightbox').setStyle({ cursor: 'default' });
		$('overlay').observe('click', this.userInteraction);
		$('nlightbox').observe('click', this.userInteraction);
		document.observe('keydown', this.userInteraction);
	},
	//
	//  disableInteraction()
	//
	disableInteraction: function() {
		$('overlay').setStyle({ cursor: 'wait' });
		$('nlightbox').setStyle({ cursor: 'wait' });
		$('overlay').stopObserving('click', this.userInteraction);
		$('nlightbox').stopObserving('click', this.userInteraction);
		document.stopObserving('keydown', this.userInteraction);
	},	
	//
	//  userInteraction()
	//
	userInteraction: function(event) {

		if (event.keyCode) {		
			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 nlightbox
				this.end();
			} else if ((key == 'p') || (keycode == 37)){ // display previous image
				if ($('prev-link').className != 'disabled'){
					if (this._activeImage != 0){
						this.disableInteraction();
						this.changeImage(this._activeImage - 1);
					}
				} else {
					return false;
				}
			} else if ((key == 'n') || (keycode == 39)){ // display next image
				if ($('next-link').className != 'disabled'){
					if (this._imageArray.length > 1 && this._activeImage == (this._imageArray.length -1)) {
						this.disableInteraction();
						this.changeImage(this._activeImage - this._imageArray.length + 1);
					} else if (this._activeImage != (this._imageArray.length - 1)) {
						this.disableInteraction();
						this.changeImage(this._activeImage + 1);
					}
				} else {
					return false;
				}
			}
		} else {
			this.end();
			event.stop();
		}
	},
	//
	//  preloadInterface()
	//  preloads any images used as a part of the nlightbox interface including the throbber
	//
	preloadInterface: function() {
		var images = [];
		for (var i = 0; i<nLightboxOptions.interfaceImages.length; i++) {
			images[i] = new Image();
			images[i].src = nLightboxOptions.baseUrl + nLightboxOptions.interfaceImages[i];
		}
	},
	//
	//  preloadNeighborImages()
	//  Preload previous and next images.
	//
	preloadNeighborImages: function(){
		var preloadNextImage, preloadPrevImage;
		if (this._imageArray.length > this._activeImage + 1){
			preloadNextImage = new Image();
			preloadNextImage.src = this._imageArray[this._activeImage + 1][0];
		}
		if (this._activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = this._imageArray[this._activeImage - 1][0];
		}

	},
	//
	//  end()
	//
	end: function() {
		
		this.disableInteraction();

		// get current width and height
		var widthCurrent  = $('nlightbox-container').getWidth();
		var heightCurrent = $('nlightbox-container').getHeight();
		// set reverse scale dimentions
		var xScale = (nLightboxOptions.nlightboxStartSize / widthCurrent) * 100;
		var yScale = (nLightboxOptions.nlightboxStartSize / heightCurrent) * 100;

		new Effect.Parallel(
		[
			new Effect.SlideUp( 'image-data-container', {
				sync: true,
				duration: this.resizeDuration
			}),
			new Effect.Fade( 'nlightbox-image', {
				sync: true,
				duration: 0.5,
				afterFinish: (function() {
					new Effect.Parallel(
					[					
						new Effect.Scale('nlightbox-container', xScale, {
							sync: true,
							//scaleX: false,
							duration: this.resizeDuration,
							queue: 'front'
						}),
						new Effect.Scale('nlightbox-container', yScale, {
							sync: true,
							scaleY: false,
							duration: this.resizeDuration,
							delay: this.resizeDuration
						}),
						new Effect.Fade( 'nlightbox', {
							sync: true,
							duration: 0.5				
						}),
						new Effect.Fade('overlay', {
							sync: true,
							duration: 0.5
						})
					],
					{
						duration: this.resizeDuration,
						afterFinish: function() {
							// still got a couple of issues here but this is good for now
							$('nlightbox-container').setStyle({
								width: '',
								height: ''
							});
							$('prev-link').className = 'disabled';
							$('next-link').className = 'disabled';
							$('image-data-container').className = 'closed';	
						}
					})
				}).bind(this)
			})
		],
		{
			duration: this.resizeDuration
		});
		$$('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 nLightbox(); });