window.addEvent('domready', function() {
    window.ArtyGallery = new Class({
	ver: [3, 0],
	build: [4, 10, 2009],

	Implements: [Events, Options],

	options: {
	    // Ссылки на элементы, чтобы не кьюрить каждый раз
	    icont: $('icont'),
	    thumblock: $$('#iscroll .thumbs')[0],
	    iscroll: $('iscroll'),

	    // Префиксы и постфиксы урлов (частично deprecated)
	    thumbpf: '-thumb',
	    bwpf: '-bw',
	    pathpf: 'img/cont/',
	    extpf: '.jpg',

	    // Параметры морфа новой картинки
	    MorphNew: {
		top: 0,
		opacity: [0,1]
	    },

	    // Массив картинок для отображения
	    iblock: {},

	    // Движение филмстрипа
	    movestrip: {
		enabled: false,
		twidth: 0,			// На сколько прокручивать
		minus: 0,			// Минус
		cssvalue: 'margin-left',	// Какое значение менять
		initial: 0			// На место какого по счёту элемента изначально двинуть?
	    },

	    // Массив из ссылок для листания в стороны, например [ $('larr'), $('rarr') ] = [ a#larr, a#rarr ]
	    arrows: null,

	    loadIndicator: {
		enabled: false,
		morphIn: {},
		morphOut: {},
		el: {}
	    }
	},

	// Кеши элементов
	cache_thumbs: [],

	// Объект хранит информацию об активной картинке
	active: {},

	// Сколько всего картинок
	count: 0,

	/**************************************************************************************/

	initialize: function(opts) {
		this.setOptions(opts);

		// Если нам передали стрелочки — вешаем на них ивенты
		if ( $chk(this.options.arrows) ) {
		    this.options.arrows[0].addEvent('click', function(e) {
			e.stop();
			this.loadPrev();
		    }.bind(this));
		    this.options.arrows[1].addEvent('click', function(e) {
			e.stop();
			this.loadNext();
		    }.bind(this));
		}

		// ставим параметры твина в thumblock
		this.options.thumblock.set('tween', {
			duration: 300,
			transition: 'sine:out'
		});

		// По идее this.iblock должен загружаться JSON-ревквестом в этом месте
		this.showBlock();
		this.loadImg(this.cache_thumbs[0]); // Показываем первую картинку
	},

	// Загружает массив тумбнаилов this.iblock в галерею
	showBlock: function() {
		this.fireEvent('iblockLoading', this);

		this.options.thumblock.empty();
		this.options.iblock.each(function(item, index) {
			// Грузим картинки
			var thea = new Element ('a', {'class': 'no', href: item.image, title: item.title, id: index, idx: this.count }).adopt(
				//new Element('img', {'class': 'tbw', src: item.thumb1}), // Чб-версия
				new Element('img', {'class': 'tcol', src: item.thumb}) // Цветная
			);

			thea.addEvent('click', function(e) {
				e.stop();
				this.loadImg(thea);
			}.bind(this));

			this.fireEvent('beforeIblockAdopt', {
			    obj: this,
			    thea: thea,
			    index: index,
			    item: item
			});

			this.options.thumblock.adopt(thea);
			this.count++;
		}.bind(this));

		this.resetThumbCache();
		this.cache_thumbs.getLast().addClass('last');

		this.fireEvent('iblockLoaded', this);
	},

	// Загружает и показывает картинку, проставаляет .active для ссылок
	// a: Элемент-ссылка, который нужно обработать, либо порядковый номер тумбика.
	loadImg: function(a) {
		if (typeof(a) == "number")
		    a = getElByIndex(a);

		var iobj = this.options.iblock[a.id];

		this.fireEvent('imageLoading', {
		    obj: this,
		    iobj: iobj,
		    a: a
		});

		var loadHandler = function(){
			var FirstLoad = !$chk(this.active.iobj);
			// Запись инфы об активном элементе. Пусть пока будет тут, раз больше нигде не используется.
			this.active = {
				element: a,
				iobj: iobj,
				index: this.cache_thumbs.indexOf(a)
			};

			this.fireEvent('imageLoadingHandlerFired', this);

			this.options.loadIndicator.enabled && this.options.loadIndicator.el.morph(this.options.loadIndicator.morphOut);

			var oldi = this.options.icont.getElements('img.act')[0];
			this.options.icont.adopt(newi);

			var CompleteH = function() {
				if ($chk(oldi)) oldi.destroy();
				this.options.icont.getElements('img.nact').removeClass('nact').addClass('act');
			}.bind(this);

			newi.set('morph', {onComplete: CompleteH });
			if (!FirstLoad) newi.morph(this.options.MorphNew);
			else CompleteH();

			this.cache_thumbs.removeClass('active');
			a.addClass('active');

			this.options.movestrip.enabled && this.moveStrip();

			this.fireEvent('imageLoaded', {
			    obj: this,
			    iobj: iobj,
			    a: a
			});
		}.bind(this)

		var newi = new Element('img', {'class': 'nact'});

		this.options.loadIndicator.enabled && this.options.loadIndicator.el.morph(this.options.loadIndicator.morphIn);

		newi.addEvent('load', loadHandler);
		newi.set('src', a.get('href'));

		this.fireEvent('imageLoadingRequestSent', this);
	},

	getElByIndex: function(idx) {
	    return this.cache_thumbs[idx];
	},

	loadPrev: function() {
	    var target = this.active.index-1;
	    (target >= 0) && this.loadImg(this.getElByIndex(target));
	},

	loadNext: function() {
	    var target = this.active.index+1;
	    (target < this.count) && this.loadImg(this.getElByIndex(target));
	},

	resetThumbCache: function() {
	    this.cache_thumbs = this.options.iscroll.getElements('.thumbs a');
	    this.fireEvent('thumbCacheReset', this);
	},

	moveStrip: function() {
	    this.options.thumblock.tween(this.options.movestrip.cssvalue, (-this.active.index + this.options.movestrip.initial) * this.options.movestrip.twidth - this.options.movestrip.minus );
	},

	loadNewBlock: function(iblock) {
	    this.options.iblock = iblock;
	    this.showBlock();
	}
    });


    if ($chk($('thegallery'))) {
	// Расширяем контроллер под наши цели
	window.ArtyGallery.implement({
		header: $$('#thegallery h4')[0],
		posm: $$('#thegallery .meta p')[0],
		//desc: $$('#icont .description')[0],

		gchair: {},

		showGuestChair: function() {
		    this.tempa = this.active;
		    this.loadImg(this.gchair);
		},

		sdelayKakBilo: function() {
		    this.loadImg(this.tempa.element);
		}
	});

	window.minigal = new ArtyGallery({
	    iblock: $H(window.jrJSON.gallery),

	    movestrip: {
		enabled: true,
		twidth: 103,
		minus: 125,
		initial: 3
	    },

	    loadIndicator: {
		enabled: true,
		morphIn: {opacity: [0,1], top: [-30,0]},
		morphOut: {opacity: [1,0], top: [0,-30]},
		el: $('mloading')
	    },

	    arrows: [
		$('gallarr'),
		$('galrarr')
	    ],

	    onImageLoaded: function(e) {
		e.obj.header.set('html', e.a.get('title') || '&nbsp;');
		e.obj.posm.set('text', 'Фото ' + (parseInt(e.a.get('idx'))+1) + ' из ' + e.obj.count);
		if ($chk(e.iobj.link)) this.desc.adopt(new Element ('p').adopt(new Element('a', {href: e.iobj.link, text: 'Подробнее'})));
	    },

	    onBeforeIblockAdopt: function(e) {
		if (e.index == 'guest') {
		    e.obj.gchair = e.thea;
		    var newi = new Element('img', {'class': 'nact'});
		    newi.addEvent('load', function() { newi.dispose(); });
		    newi.set('src', e.thea.get('href'));
		}
	    }
	});

	// Навешиваемся на ссылочку на релейтед-товар
	if ($chk(window.minigal.gchair) && $chk($('showguest')) ) $('showguest').addEvents({
		'mouseenter': function() {
			this.showGuestChair();
		}.bind(window.minigal),

		'mouseleave': function() {
			this.sdelayKakBilo();
		}.bind(window.minigal)

	});
    }

});