﻿/////////////////////////////////////////
// ur001 Gallery for Futurico (www.futurico.ru)
// v1.2
// use  with Mootools library:
//	window.addEvent('domready', function(){
//		Gallery.init(<Gallery ID>, <Next Button ID>, <Back Button ID> , <Thimb Size>);
//	}); 
////////////////////////////////////////

/*Блокировка/разблокировка ссылки*/
Element.extend({
	setLinkEnabled: function(enabled){
		if(this.Enabled==null) this.Enabled=true;
		
		if(this.Enabled!=enabled)	
		if(enabled){
			this.Enabled=true;
			this.setOpacity(1);
			this.setStyle('cursor', 'pointer');
		} else {
			this.Enabled=false;
			this.setOpacity(0.4);
			this.setStyle('cursor', 'default');
		}
		
		return this;
	}
});

var Gallery = {
	resize: function(){
		this.Size=this.Obj.getSize();
		this.Width=this.Size.size.x;
		
		// Положение кнопки "дальше" справа от края последней картинки
		this.BackBtn.setStyle('right', (this.Width % this.thSize-23)+'px');
		// Кол-во колонок
		this.Cols=Math.floor(this.Width / this.thSize);
		// Номер верхнего ряда
		this.Row=this.Size.scroll.y / this.thSize;
		
		if(this.Imgs.length-this.Row*this.Cols<this.Cols*3){
			// Перекрутить на последнюю строку, если при увеличении размера последняя оказалась не последней :)
			this.Row=(Math.ceil(this.Imgs.length/this.Cols)-3);
			if(this.Row<0)this.Row=0;
			this.scroll.toElement(this.Imgs[this.Row*this.Cols]);
			//this.Obj.scrollTo(0,this.thSize*row);
		}	

		this.checkButtons();
	},
	
	checkButtons: function(){
		this.BackBtn.setLinkEnabled(this.Row>0);
		this.NextBtn.setLinkEnabled(this.Imgs.length-this.Row*this.Cols>this.Cols*3);
	},

	init: function(ID, NextID, BackID, thSize){
		this.thSize=thSize;
		this.Obj=$(ID);
		this.NextBtn=$(NextID);
		this.BackBtn=$(BackID);	

		this.scroll = new Fx.Scroll(ID, {
			wait: false,
			duration: 600,
			offset: {'x': 0, 'y': 0},
			transition: Fx.Transitions.Quad.easeInOut
		});
		
		this.Imgs = $$('#'+ID+' a.th');
		
		window.addEvent('resize',this.resize.bind(this));
		this.resize();
		this.NextBtn.onclick=this.next.bindWithEvent(this);
		this.BackBtn.onclick=this.back.bindWithEvent(this);
	},
	
	next: function(event){
		event.stop();
		// TODO: Блокировать кнопку!!!
		if(this.NextBtn.Enabled){
			this.scroll.toElement(this.Imgs[(++this.Row)*this.Cols]);	
			this.checkButtons();
		}
	},
	
	back: function(event){
		event.stop();
		if(this.BackBtn.Enabled){
			this.scroll.toElement(this.Imgs[(--this.Row)*this.Cols]);
			this.checkButtons();
		}
	}
}