﻿var photo,
	photos,
	photos_cnt=0,
	last_photo=0,
	shown=0,
	sfx;

function showPhoto(i){	
	if(!photo)
		photo=new Element('img').inject($('gallery_photo'));
		
	photos[last_photo].removeClass('active');
	photos[i].set('class','active');
	
	last_photo=i;
	$('gallery_description').set('html',(photo_data[i][0]!=''?photo_data[i][0]:'&nbsp;'));							
	photo.src=photos[i].src.replace(gallery_path,gallery_path+'/orig');
	
	if(shown==0){
		$$('html').setStyle('overflow','hidden');
		_alpha=$('alpha')?$('alpha'):new Element('div',{'id':'alpha'}).inject($('gallery'));
		s_h=window.getScrollSize().y;
		s_t=window.getScroll().y;
		_alpha.setStyles({
			display:'block',
			height:s_h,
			opacity:.5
		});
		$('shaddowbox_holder').setStyles({
			top:s_t
		});
		shown=1;
	}
	s=112*last_photo;
	if(!sfx)
		sfx=new Fx.Scroll($('gallery_thumbs_box'));
	sfx.set(s,0);
}

function closeGallery(){
	$('shaddowbox_holder').setStyle('top','-1000px');
	$('alpha').setStyle('display','none');
	$$('html').setStyle('overflow','auto');
	shown=0;
}

function cyclePhotos(dir){
	dir=='-'&&last_photo>0?showPhoto(last_photo-1):((dir=='+'&&last_photo<(photos_cnt-1))?showPhoto(last_photo.toInt()+1):'');
}

function gallery_init(){
	var _gal=$('gallery');
	_gal.getElements('img').each(function(o,i){
		o.addEvents({
			'click':function(event){
				showPhoto(i);	 	
			}.bind(i),
			'mouseover':function(event){
				this.tween('opacity',.7,1);						 	
			}
		});
	});
	
	var _thumbs=_gal.clone();

	_thumbs.setProperty('id','gallery_thumbs');
	$('gallery_thumbs_box').setStyle('overflow-x','scroll');
	$('gallery_thumbs_box').grab(_thumbs);
	
	photos=$('gallery_thumbs').getElements('img');	
	photos.each(function(o,i){
		o.addEvents({
			'click':function(event){
				showPhoto(i);						 	
			}.bind(i),
			'mouseover':function(event){
				this.tween('opacity',.7,1);						 	
			}
		});
	});
	photos_cnt=photos.length;
	
	$('gallery_previous').addEvent('click',function(){cyclePhotos('-');});
	$('gallery_next').addEvent('click',function(){cyclePhotos('+');});
	$('gallery_close').addEvent('click',function(){closeGallery();});
	
	$$('html').addEvent('keydown',function(event){
		param=event.key=='left'?'-':event.key=='right'?'+':'';
		if(param!='')
			cyclePhotos(param);
		if(event.key=='esc'&&shown==1)
			closeGallery();
		event.preventDefault();
	});	
}
						
window.addEvent('domready',function(){
	if($('gallery'))
		gallery_init();
});
