/*
	Gallery script is heavily based on lightbox by
	by Lokesh Dhakar - http://www.lokeshdhakar.com
	
	Reworked and modified to work on this site

*/

var cns_Lightbox = Class.create({
	gallerys: [],
	galleryIds: [],
	activeGallery: undefined,
	activeGalleryPos: undefined,
	currentHeight: 200,
	currentWidth: 200,
	
	initialize: function(){
		$$('.galleryList').each((function (node) {
									var id = node.getAttribute('id');
									this.gallerys[id] = { size: 0, images: new Array(), id: id };
									this.galleryIds[this.galleryIds.length] = id;
									node.select('.pgSlide').each((function (id, node) {
																	this.gallerys[id].images[this.gallerys[id].images.length] = {id: node.getAttribute('id').split("_")[1]};
																	this.gallerys[id].size++;
																	node.observe('click', this.showLightbox.bind(this));
									}).bind(this, id));
								}).bind(this));

		var nBody = $$('body')[0];
		
		nBody.appendChild(Builder.node('div', { id:'overlay', style: 'display: none;' } ));
		
		nBody.appendChild(Builder.node('div', { id:'lightbox', style: 'display: none;' },  [
						Builder.node('div', { id: 'lbImage' }, [
							Builder.node('a', { href: '#', title: 'Click to close image', id: 'loadingImg' }, [
								Builder.node('img', { src: '/design/imgs/loading.gif', alt: 'Loading'})
							]),
							
							Builder.node('a', { href: '#', title: 'Click to close image', id: 'lbImgLink', style: 'display: none;' }, [
								Builder.node('img', { id: 'lbImg', alt: 'Lightbox'})
							]),
						]),
						
						Builder.node('div', { id: 'lbNav', style: 'display: none;' }, [
							Builder.node('a', { href: '#', title: 'Click to go to the previous image', id: 'navPrev', style: 'display: none;' }, [ Builder.node('strong', ['<'] ), ' Prev' ] ),
							Builder.node('a', { href: '#', title: 'Click to go the the next image', id: 'navNext', style: 'display: none;' }, [ 'Next', Builder.node('strong', ['>'] ) ] ), 
							Builder.node('a', { href: '#', title: 'Click to close image', id: 'navClose' }, [ 'Close', Builder.node('strong', ['X'] ) ] ) 
						])
					]));
		
		$('navClose').observe('click', this.hideLightbox);
		$('lbImgLink').observe('click', this.hideLightbox);
		$('overlay').observe('click', this.hideLightbox);
		$('overlay').observe('click', this.hideLightbox);
		
		$('navNext').observe('click', this.nextImage.bind(this));
		$('navPrev').observe('click', this.prevImage.bind(this));
	},
		
	showLightbox: function(e) {
		var id = e.findElement('li').getAttribute('id').split('_');
		var galId = id[0];
		var picId = id[1];
		this.activeGallery = this.gallerys[galId];
		
		var imgNum = 0;
		while(this.activeGallery.images[imgNum].id != picId) { imgNum++; }
		this.activeGalleryPos = imgNum;
		
		this.changeImage(picId);
		e.stop();
	},
		
	hideLightbox: function (e) {
		$('lightbox').hide();
		$('overlay').fade({ duration: 0.3});
		this.currentHeight = 200;
		this.currentWidth = 200;
		$('lightbox').setStyle({ height: this.currentHeight + 'px', width: this.currentWidth + 'px' });
		
		(function () {
			$('overlay').hide();
			$('loadingImg').show();
			$('lbImgLink').hide();
			$('lbNav').hide();
		}).delay(0.4);
		
		e.stop();
	},
		
	nextImage: function(e) {
		if(this.activeGalleryPos < (this.activeGallery.size - 1)) {
			var nextImgNo = this.activeGalleryPos + 1;
			var nextImg = this.activeGallery.images[nextImgNo].id;
			this.activeGalleryPos = nextImgNo;
			
			$('lbImg').hide();
			$('loadingImg').show();
			
			this.changeImage(nextImg);
		} else if(this.galleryIds.indexOf(this.activeGallery.id) < (this.galleryIds.length - 1)) {
			var nextGal = this.galleryIds[this.galleryIds.indexOf(this.activeGallery.id) + 1];
			this.activeGallery = this.gallerys[nextGal];
			this.activeGalleryPos = 0;
			
			$('lbImg').hide();
			$('loadingImg').show();			
			
			this.changeImage(this.activeGallery.images[0].id);
		}
		
		e.stop();
	},
		
	prevImage: function(e) {
		if(this.activeGalleryPos > 0) {
			var nextImgNo = this.activeGalleryPos - 1;
			var nextImg = this.activeGallery.images[nextImgNo].id;
			this.activeGalleryPos = nextImgNo;
			
			$('lbImg').hide();
			$('loadingImg').show();
			
			this.changeImage(nextImg);
		} else if(this.galleryIds.indexOf(this.activeGallery.id) > 0) {
			var nextGal = this.galleryIds[this.galleryIds.indexOf(this.activeGallery.id) - 1];
			this.activeGallery = this.gallerys[nextGal];
			this.activeGalleryPos = this.activeGallery.size - 1;
			
			$('lbImg').hide();
			$('loadingImg').show();			
			
			this.changeImage(this.activeGallery.images[this.activeGalleryPos].id);
		}
		
		e.stop();
	},
	
	changeImage: function(picId) {
		var imgNum = this.activeGalleryPos;
				
		if(imgNum > 0) {
			if($('navPrev').innerHTML != '<strong>&lt;</strong> Prev') $('navPrev').update('<strong>&lt;</strong> Prev');
			$('navPrev').show();
			var preLoadPrev = new Image();
			preLoadPrev.src = '/paintings/'+this.activeGallery.images[imgNum-1].id+'.jpg';
		} else if(this.galleryIds.indexOf(this.activeGallery.id) > 0) {
			var nextGal = this.galleryIds[this.galleryIds.indexOf(this.activeGallery.id) - 1];
			$('navPrev').update('<strong>&lt;</strong>' + nextGal.truncate(nextGal.indexOf('Gallery'), '').capitalize()).show();
		} else $('navPrev').hide();	
		
		if(imgNum < (this.activeGallery.size - 1)) {
			if($('navNext').innerHTML != 'Next <strong>&gt;</strong>') $('navNext').update('Next <strong>&gt;</strong>');
			$('navNext').show();
			var preLoadNext = new Image();
			preLoadNext.src = '/paintings/'+this.activeGallery.images[imgNum+1].id+'.jpg';
		} else if(this.galleryIds.indexOf(this.activeGallery.id) < (this.galleryIds.length - 1)) {
			var nextGal = this.galleryIds[this.galleryIds.indexOf(this.activeGallery.id) + 1];
			$('navNext').update(nextGal.truncate(nextGal.indexOf('Gallery'), '').capitalize() + ' <strong>&gt;</strong>').show();
		} else $('navNext').hide();	
		
		var dim = this.getPageSize();
		if(!$('overlay').visible()) {
			$('overlay').setStyle({ width: dim[0]+'px', height: dim[1]+'px'});
			$('overlay').appear({ duration: 0.3, from: 0.0, to: 0.9 });
		}
		if(!$('lightbox').visible()) {
			var topLeft = this.getTopLeft(this.currentHeight / 2, this.currentWidth / 2);
			$('lightbox').setStyle({ top: Math.round(topLeft[0]) + 'px', left: Math.round(topLeft[1]) + 'px' }).show();
		}
		
		var imgPreloader = new Image();
	
		imgPreloader.onload = (function(parent) {
									$('lbImg').src = this.src;
									parent.resizeLightbox(this.width, this.height);
								}).curry(this);
		imgPreloader.src = '/paintings/'+picId+'.jpg';
	},
	
	resizeLightbox: function(newWidth, newHeight){
		this.currentWidth = $('lbImage').getWidth();
		this.currentHeight = $('lbImage').getHeight();
		var hDiff = (newHeight - this.currentHeight) + 10;
		var wDiff = (newWidth - this.currentWidth) + 20;
		
		var topLeft = this.getTopLeft((this.currentHeight / 2), (this.currentWidth / 2));
		if(wDiff != 0) {
			var offset = topLeft[1] - (wDiff / 2);
			new Effect.Parallel([
				new Effect.Morph('lightbox', { style: 'left: '+Math.round(offset)+'px;', sync: true}),
				new Effect.Morph('lightbox', { style: 'width: '+Math.round(newWidth)+'px;', sync: true})
				], {duration: 0.4} );
		}
		
		if(hDiff != 0) {
			var offset = topLeft[0] - (hDiff / 2);
			new Effect.Parallel([
				new Effect.Morph('lightbox', { style: 'top: '+Math.round(offset)+'px;', sync: true}),
				new Effect.Morph('lightbox', { style: 'height: '+Math.round(newHeight)+'px;', sync: true})
				], {duration: 0.4, queue: 'end'} );
		}
		
		if ((hDiff == 0) && (wDiff == 0)) $('loadingImg').fade({ duration: 0.1, from: 1, to: 0});
		else $('loadingImg').fade({ duration: 0.4, from: 1, to: 0});
		
		if($('lbImg').visible() == false) {
			new Effect.Parallel([
				new Effect.Appear('lbImg', { sync: true })
				], { duration: 0.1, queue: 'end' } );
		} else {
			new Effect.Parallel([
				new Effect.Appear('lbImgLink', { sync: true }),
				new Effect.BlindDown('lbNav', { sync: true })
			], { duration: 0.3, queue: 'end' } );
		}
	},
	
	getTopLeft: function(y, x){
		var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + ((document.viewport.getHeight() / 2) - y);
        var lightboxLeft = arrayPageScroll[0] + ((document.viewport.getWidth() / 2) - x);
		return [lightboxTop, lightboxLeft];
	},
	
	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 cns_Lightbox(); });