/* 
Galeria.js by Dario Soccio
darek at progressiva.pl
all rights reserved
instructions:
1. Append Galeria.js <script language="javascript" type="text/javascript" src="js/Galeria.js"></script>
2. Create img tags:
echo '<img src="images/thumbs/'.$filename.'" border="0" gal="1" onclick="showGal(this)" galFolder="images" galBig="images/big/otherfilename.jpg" galTitle="'.htmlspecialchars('Title with special chars',ENT_QUOTES).'" />';
gal="1" => same number for all images in one gallery - will be displayed together in one lightbox. Different numbers are for creating several galleries on one webpage at the same time
onclick="showGal(this)" => do not change that, it populates gallery class with data coming from imgs with same gal number
galFolder="images" /optional/ => normally the class takes the img src without the 'thumbs/' part for the big image. If the folder is different you have to put it here, filename has to be the same
galBig="images/big/otherfilename.jpg" /optional/ => same as above, but additionally with other img filename
galTitle="Title" /optional/ => title, displayed in the lightbox

showGalNo(uint) => if you want to start some gallery use this function
*/
var Galeria = Class.create({
	initialize: function() {
		this.els = [];//elementy HTML z thumbsami
		this.galFotos = [];
		this.aktFoto = 0;//pozycja aktualnego obrazka w tablicy
		this.aktGal = 0;//id aktualnej galerii
		this.thumbsOn = false;
		this.thumbs = [];
		this.bigDim = {width:0,height:0};
		
		//settings
		this.thumbsPos = 0;
		this.thumbsStep = 300;//odległość, o jaką przesuna sie miniatury
		this.minMarginX = 110;//minimalny margines zdjęcie/krawędź viewportu - poziom
		this.minMarginY = 160;//minimalny margines zdjęcie/krawędź viewportu - pion
	},
	
	//inicjacja galerii na podstawie kliknietego elementu img (thmumbnail)
	initGal: function(thEl) {
		thEl = $(thEl);
		var galId = thEl.readAttribute('gal');
		if(galId!=this.aktGal) this.populateGal(galId);
		for(var i=0;i<this.els.length;i++) {
			if(thEl==this.els[i]) this.aktFoto = i;
		}
		this.startGal(thEl);
	},
	
	//inicjacja galerii na podstawie id, aktywne bedzie pierwsze zdjecie
	initGalNo: function(galId) {
		if(galId!=this.aktGal) this.populateGal(galId);
		this.aktFoto = 0;
		var thEl = this.els[0];
		this.startGal(thEl);
	},
	
	//start galerii na postawie jednego aktywnego elementu
	startGal: function(thEl) {
		$('bigFotoContainer').show();
		$('bigFotoInside').show();
		$('bigFotoImg').onclick = null;
		$('bigFotoImg').setStyle({cursor:'default'});
		$('bigFotoPrev').onclick = null;
		$('bigFotoPrev').stopObserving('click');
		$('bigFotoPrev').observe('click',this.prevFoto.bind(this));
		$('bigFotoNext').onclick = null;
		$('bigFotoNext').stopObserving('click');
		$('bigFotoNext').observe('click',this.nextFoto.bind(this));
		$('bigFotoClose').onclick = null;
		$('bigFotoClose').stopObserving('click');
		$('bigFotoClose').observe('click',this.closeGal.bind(this));
		this.boundHandlerMethod = this.keyHandler.bind(this);
		Event.observe(document, 'keypress', this.boundHandlerMethod);
		if(this.thumbsOn) this.showThumbs();
		this.showPhoto(thEl);
	},
	
	//pobranie danych wszystkich elementów z danej galerii
	populateGal: function(gId) {
		var els = $$('img[gal='+gId+']');
		this.els = els;
		this.aktGal = gId;
	},
	
	//przygotowuje zdjecie do wyswietlenia i uruchamia proces wyswietlania (onload)
	showPhoto: function(thEl) {
		var thSrc = thEl.readAttribute('src');
		var fileName = thSrc.replace('thumbs/','');
		var bigWidth = thEl.readAttribute('bigWidth');
		var bigHeight = thEl.readAttribute('bigHeight');
		if(bigWidth&&bigHeight) this.bigDim = {width:bigWidth,height:bigHeight};
		else this.bigDim = {width:0,height:0};
		
		var galFolder = thEl.readAttribute('galFolder');
		if(galFolder!=''&&galFolder!=undefined) {
			fileName = galFolder+'/'+basename(fileName);
		}
		
		var galBig = thEl.readAttribute('galBig');
		if(galBig!=''&&galBig!=undefined) fileName = galBig;
		
		$('bigFotoInside').hide();
		$('fotoWait').update('<img src="images/imgloading.gif" border="0" />');
		$('fotoWait').show();
		//$('fotoWait').setStyle({top:'0px'});
		//$('fotoWait').update('<img src="images/_konkurs_logo.gif" border="0" />');
		if($('galLogo')) $('galLogo').hide();
		this.img = new Element('img');
		this.img.id = 'theImage';
		this.img.observe('load', this.showImg.bind(this));
		this.img.observe('click',this.nextFoto.bind(this));
		this.img.setStyle({cursor:'pointer'});
		this.img.src = fileName;
		$('bigFotoImg').show();
		this.fotoNav();
	},
	
	//pokazuje zdjecie po zaladowaniu
	showImg: function(evt) {
		$('fotoWait').update('');
		$('fotoWait').hide();
		//$('fotoWait').setStyle({top:'-100px'});
		//$('fotoWait').update('');
		if($('galLogo')) $('galLogo').show();
		$('bigFotoImg').hide();
		$('bigFotoImg').update(this.img);
		$('bigFotoImg').appear({duration:.5});
		$('bigFotoInside').appear({duration:.01, delay:.01});
		//$('bigFotoInside').show();
		
		var dim = viewportDims();
		var fotoDim = [];
		if(this.bigDim.width>0&&this.bigDim.height>0) fotoDim = this.bigDim;
		else fotoDim = $('bigFotoImg').getDimensions();

		if(fotoDim.width>dim.width-this.minMarginX||fotoDim.height>dim.height-this.minMarginY) {
			var new_size = image_small_maker(fotoDim.width, fotoDim.height, dim.width-this.minMarginX, dim.height-this.minMarginY)
			this.img.setStyle({'width':new_size[0]+'px','height':new_size[1]+'px'});
		}
		var title = this.els[this.aktFoto].readAttribute('galTitle');
		if(title==null) title = '';
		if($('fotoTitle')) $('fotoTitle').update(title);
	},
	
	//ustawia nawigacje do zdjec - wlacza/wylacza strzalki lewo/prawo
	fotoNav: function() {
		if($('bigFotoPrev')) {
			if(this.aktFoto>0) $('bigFotoPrev').show();
			else $('bigFotoPrev').hide();
		}
		if($('bigFotoNext')) {
			if(this.aktFoto<this.els.length-1) $('bigFotoNext').show();
			else $('bigFotoNext').hide();
		}
	},
	
	//wyswietla poprzednie zdjecie
	prevFoto: function() {
		if(this.aktFoto<=0) return;
		this.aktFoto--;
		this.showPhoto(this.els[this.aktFoto]);
	},
	
	//wyswietla nastepne zdjecie
	nextFoto: function() {
		if(this.aktFoto>this.els.length-1) return;
		this.aktFoto++;
		if(this.aktFoto>this.els.length-1) this.aktFoto = 0;
		this.showPhoto(this.els[this.aktFoto]);
	},
	
	//pokazuje miniatury
	showThumbs: function() {
		if(this.els.length<2) return;
		$('galThumbs').update('');
		var thumb;
		var thumbsW = 0;
		for(var i=0;i<this.els.length;i++) {
			thumb = new Element('img');
			thumb.id = 'thumb_'+i;
			//thumb.observe('load', this.f.bind(this));
			thumb.src = this.els[i].src;
			thumb.observe('click', this.thumbClicked.bind(this));
			thumb.setStyle({cursor:'pointer',marginRight:'6px',display:'block',float:'left'});
			this.thumbs.push(thumb);
			$('galThumbs').insert(thumb);
			thumbsW += thumb.width+6;
		}
		var dim = viewportDims();


		$('thumbsWrapperCont').setStyle({width:(dim.width-100)+'px'});
		$('thumbsWrapper').setStyle({width:(dim.width-100)+'px'});
		
		//$('thumbsWrapperCont').width = dim.width-100;		
		//$('thumbsWrapper').width = dim.width-100;
		
		$('galThumbs').setStyle({width:thumbsW+'px'});
		$('galThumbs').show();
		this.thumbNavSet();
	},
	
	//funkcja wywolana po kliknieciu miniatury
	thumbClicked: function(evt) {
		var fot = evt.findElement();
		var fotId = fot.id.substr(6);
		if(this.aktFoto==fotId) return;
		this.aktFoto = fotId;
		this.showPhoto(this.els[this.aktFoto]);
	},
	
	//inicjuje nawigacje miniatur
	thumbNavSet: function() {
		var tww = $('thumbsWrapper').getWidth();
		var thw = $('galThumbs').getWidth();
		if(tww>=thw) {
			$('thumbsLeft').hide();
			$('thumbsRight').hide();
			return;
		}
		$('thumbsLeft').show();
		$('thumbsLeft').stopObserving('click');
		$('thumbsLeft').observe('click',this.thumbsLeft.bind(this));
		$('thumbsRight').show();
		$('thumbsRight').stopObserving('click');
		$('thumbsRight').observe('click',this.thumbsRight.bind(this));
		this.thumbNavOnOff();
	},
	
	//ustawia nawigacje do miniatur - wlacza/wylacza strzalki lewo/prawo
	thumbNavOnOff: function() {
		var tww = $('thumbsWrapper').getWidth();
		var thw = $('galThumbs').getWidth();
		if(this.thumbsPos<0) $('thumbsLeft').show();
		else $('thumbsLeft').hide();
		if(this.thumbsPos>-(thw-tww)) $('thumbsRight').show();
		else $('thumbsRight').hide();
	},
	
	//przesuwa miniatury w prawo
	thumbsRight: function(evt) {
		var oldPos = this.thumbsPos;
		this.thumbsPos -= this.thumbsStep;
		var tww = $('thumbsWrapper').getWidth();
		var thw = $('galThumbs').getWidth();
		if(this.thumbsPos<-(thw-tww)) this.thumbsPos = -(thw-tww);
		//$('galThumbs').setStyle({left:this.thumbsPos+'px'});
		var actOffset = $('galThumbs').positionedOffset();
		new Effect.Move('galThumbs', { x: this.thumbsPos-actOffset[0], y: 0, mode: 'relative',duration: .6});
		this.thumbNavOnOff();
	},
	
	//przesuwa miniatury w lewo
	thumbsLeft: function(evt) {
		var oldPos = this.thumbsPos;
		this.thumbsPos += this.thumbsStep;
		if(this.thumbsPos>0) this.thumbsPos = 0;
		//$('galThumbs').setStyle({left:this.thumbsPos+'px'});
		var actOffset = $('galThumbs').positionedOffset();
		new Effect.Move('galThumbs', { x: this.thumbsPos-actOffset[0], y: 0, mode: 'relative',duration: .6});
		this.thumbNavOnOff();
	},
	
	//sprawdza przycisniety klawisz
	keyHandler: function(e) {
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		if(code==37) this.prevFoto();
		if(code==39) this.nextFoto();
		if(code==27) this.closeGal();
	}
});

//nowa galeria
var aktGal;
function showGal(el) {
	if(aktGal==null) aktGal = new Galeria()
	aktGal.initGal(el);
}
function showGalNo(galId) {
	if(aktGal==null) aktGal = new Galeria()
	aktGal.initGalNo(galId);
}

//pomocnicza funkcja do obliczania docelowej wielkości obrazka
function image_small_maker(orig_width, orig_height, max_width, max_height) {
	var xRatio = max_width / orig_width; 
	var yRatio = max_height / orig_height; 
	var new_width = 0;
	var new_height = 0;
	if ( (orig_width <= max_width) && (orig_height <= max_height) ) { 
	 new_width = orig_width; 
	 new_height = orig_height; 
	} 
	else if ((xRatio * orig_height) < max_height) { 
	 new_height = Math.ceil(xRatio * orig_height); 
	 new_width = max_width; 
	} 
	else { 
		new_width = Math.ceil(yRatio * orig_width); 
		new_height = max_height; 
		}
	var output = [];
	output.push(Math.round(new_width));
	output.push(Math.round(new_height));
	return output;
}
