window.addEvent('domready', function() {

	if ($chk($('menu'))){
		var lwi = 115;
		
		// Ищем активный пункт меню. Если нет, пусть это будет первый.
		var ali = $$('#menu>li.active')[0];
		//if (!$chk(ali)) ali = $$('#menu li')[0];
		
		var getBrTarget = function (el) {
			var tar = $(el);
			if (!tar) return false;
			var trx = tar.getPosition($('menuswrap')).x;
			if (Browser.Engine.trident) trx = tar.getPosition($$('#menu li')[0]).x;
			//if (!Browser.Engine.trident) trx += $$('#menu li')[0].getCoordinates().left;
			return tar.getScrollSize().x/2 - lwi/2 + trx;
		};
		
		if ($$('#menu>li .active').length > 0) {
			var par = $$('#menu>li.active ul')[0];
			par.set('persist', 1);
		}
		
		var ins = false;
		$$('#menu>li').each(function(i){
			i.addEvent('mouseover', function(e) {
				ins = true;
				e.stop();
				$('brickroll').tween('left', getBrTarget(e.target));
			});
			
			// Так, теперь делаем подменюшечки.
			var chs = i.getChildren('ul');
			if ( chs.length > 0 ) {
				var sub = chs[0];
				sub.addClass('hover').setStyle('left', (i.getScrollSize().x / 2) - (sub.getScrollSize().x / 2)).removeClass('hover').setStyle('opacity', 0);
				sub.set('morph', {duration: 'normal', onComplete: function() {
					if (this.element.getStyle('opacity') == 0) this.element.removeClass('hover');
				}});
				i.addEvents({
					'mouseenter': function(e) {
						sub.addClass('hover');
						sub.morph({
							opacity: 1
						});
					},
					'mouseleave': function(e) {
						if (!sub.get('persist'))
						sub.morph({
							opacity: 0
						});
					}
				});
				if (sub.get('persist')) i.fireEvent('mouseenter');
			}
		});
		
		$('menuswrap').adopt(new Element('div', {id: 'brickroll'})).addEvent('mouseleave', function(e){
			ins = false;
			e.stop();
			var timer = setTimeout(function() {
				if (!ins) $('brickroll').tween('left', getBrTarget( ($chk(ali) ? ali : $$('#menu li')[0]) ) );
			}, 500);
		});
		
		$('menuswrap').adopt(new Element('div', {id: 'actroll'}));
		
		//ali = $$('#menu li.active')[0];
		if ($chk(ali)) {
			$('actroll').setStyles({
				width: ali.getSize().x,
				left: ali.getPosition($$('#menu li')[0]).x,
				display: 'block'
			});
			$('brickroll').setStyle('left', getBrTarget(ali));
		}
		else {
			$('brickroll').setStyle('left', -4000);
		}
		
		
		
		
	}
	
	// Листаем колонки в портфолио
	if ($chk($('hscroller'))) {
		var HScroll = new Class({
			hscroller: $('hscroller'),
			fwrap: $('fwrap'),
			blockw: 259,
			current: 0,
			currentI: 0,
			maxI: 0,
			mover: {},
			
			hrar: $('hscr-r'),
			hlar: $('hscr-l'),
			
			//getCenter: function()
			
			pos: function(index) {
				//console.info({toIdx: index, currentI: this.currentI, strange: this.fwrap.getSize().x});
				
				// Не надо скроллить дальше границ
				if (index < 0) index = 0;
				if (index > this.maxI) index = this.maxI;
				
				this.currentI = index;
				
				// Элемент с нужным индексом ==> центр экрана
				this.current = (this.fwrap.getSize().x / 2 - 129) - (this.blockw * index);
				this.hscroller.tween('margin-left',  this.current);
				
				//Коверфлоу!!1
				var ch = this.hscroller.getChildren('.flocolumn');
				ch[this.currentI].tween('opacity', 1);
				if (this.currentI-1 >= 0)		ch[this.currentI-1].tween('opacity', 0.6);
				if (this.currentI+1 < ch.length)	ch[this.currentI+1].tween('opacity', 0.6);
				if (this.currentI-2 >= 0)		ch[this.currentI-2].tween('opacity', 0.3);
				if (this.currentI+2 < ch.length)	ch[this.currentI+2].tween('opacity', 0.3);
				
				// Прячем стрелки
				this.hlar.setStyle('display', (index == 0 ? 'none' : 'block'));
				this.hrar.setStyle('display', (index == this.maxI ? 'none' : 'block'));
			},
			
			posRel: function(n) {
				this.pos(this.currentI+n);
			},
			
			initialize: function() {
				$$('#hscroller .flocolumn').setStyle('opacity', 0.3);
				this.maxI = $$('#hscroller .flocolumn').length-1;
				
				this.hscroller.setStyle('width', 270*(this.maxI+1));
				
				// Задаём события стрелочкам-листалочкам
				this.hrar.addEvents({
					'click': function() {
						this.posRel(1);
					}.bind(this),
					
					'mouseover': function(e) {
						this.hrar.tween('opacity', 1);
					}.bind(this),
					
					'mouseout': function(e) {
						window.clearInterval(this.mover);
						this.hrar.tween('opacity', 0.5);
					}.bind(this)
				}).setStyles({
					opacity: 0.5
				});
				this.hlar.addEvents({
					'click': function() {
						this.posRel(-1);
					}.bind(this),
					
					'mouseover': function(e) {
						this.hlar.tween('opacity', 1);
					}.bind(this),
					
					'mouseout': function(e) {
						window.clearInterval(this.mover);
						this.hlar.tween('opacity', 0.5);
					}.bind(this)
				}).setStyles({
					opacity: 0.5
				});
				
				// Листаем клавиатурой
				document.addEvent('keydown', function(e) {
					switch(e.key){
						case 'right':
							e.stop();
							this.posRel(1);
							break;
						case 'left':
							e.stop();
							this.posRel(-1);
							break;
					}
				}.bind(this));
				
				// Позиционируем посимпотичнее
				this.pos ( parseInt (this.fwrap.getSize().x / this.blockw / 2) );
				
				// При нажатии на любую ссылку в блоке перед переходом будет начато центрирование её родителя
				$$('#hscroller .flocolumn a').addEvent('click', function(e){
					e.stop();
					e.target = $(e.target);
					var j = $$('#hscroller .flocolumn').indexOf(e.target.getParent('.flocolumn'));
					var hhref = $chk(e.target.get('href')) ? e.target.get('href') : e.target.getParent().get('href');
					this.pos(j);
					setTimeout(function() { window.location.href = hhref; }, 700);
				}.bind(this));
			}
		});
		
		window.hscr = new HScroll();
		
		
	}

	// Базовый контроллер галереи, пускаем только при наличии оной
	if (
	    $chk($('minigallery')) ||
	    $chk($('yaminigallery')) ||
	    $chk($('theprojgallery'))
	    ) {
		// Базовый класс. Можно расширять
		var Minigal = new Class({
			// Ссылки на элементы, чтобы не кьюрить каждый раз
			icont: $('icont'),
			thumblock: $$('#iscroll .thumbs')[0],
			loading: $('mloading'),

			// Префиксы и постфиксы урлов
			thumbpf: '-thumb',
			bwpf: '-bw',
			pathpf: 'img/cont/',
			extpf: '.jpg',

			// Это вообще должно грузиться аяксом
			iblock: $H(window.gallery_json.images),

			// Параметры морфа новой картинки
			MorphNew: {},
			
			// Объект хранит информацию об активной картинке
			active: {},

			// Загружает массив тумбнаилов this.iblock в галерею
			showBlock: function() {
				this.onIblockLoading();

				this.thumblock.empty();
				this.iblock.each(function(item, index) {
					// Грузим картинки
					var thea = new Element ('a', {href: /*this.pathpf+item.image+this.extpf*/ item.image, title: item.title, id: index }).adopt(
						new Element('img', {'class': 'tbw', src: /*this.pathpf+item.image+this.bwpf+this.extpf*/ item.thumb1}), // Чб-версия
						new Element('img', {'class': 'tcol', src: /*this.pathpf+item.image+this.thumbpf+this.extpf*/ item.thumb2}) // Цветная
					);

					thea.addEvent('click', function(e) {
						e.stop();
						this.loadImg(thea);
					}.bind(this));
					this.thumblock.adopt(thea);
				}.bind(this));

				$$('#iscroll .thumbs a').getLast().addClass('last');
			},

			// Загружает и показывает картинку, проставаляет .active для ссылок
			// a: Элемент-ссылка, который нужно обработать. Значение имеет свойство id, который ищется в this.iblock
			loadImg: function(a) {
				var iobj = this.iblock[a.id];

				this.onImageLoading(a, iobj);

				var loadHandler = function(){
					// Запись инфы об активном элементе. Пусть пока будет тут, раз больше нигде не используется.
					this.active = {
						element: a,
						iobj: iobj,
						index: $$('#iscroll .thumbs a').indexOf(a)
					};
					
					this.loading.morph({opacity: [1,0], top: [0,-30]});
					var oldi = $$('#icont img.act')[0];
					this.icont.adopt(newi);

					newi.set('morph', {onComplete: function() {
						if ($chk(oldi)) oldi.destroy();
						$$('#icont img.nact').removeClass('nact').addClass('act');
					}});
					newi.morph(this.MorphNew);

					this.onImageLoaded(a, iobj);

					$$('#iscroll .thumbs a').removeClass('active');
					a.addClass('active');
				}.bind(this)
				var newi = new Element('img', {'class': 'nact'});
				this.loading.morph({opacity: [0,1], top: [-30,0]});
				newi.addEvent('load', loadHandler);
				newi.set('src', a.get('href'));
			},

			onImageLoading: function(a, iobj) { },
			onImageLoaded: function(a, iobj) { },
			onIblockLoading: function() { },

			initialize: function() {
				// По идее this.iblock должен загружаться JSON-ревквестом в этом месте
				this.showBlock();
				this.loadImg($$('#iscroll .thumbs a')[0]); // Показываем первую картинку
			}

		});


		if ($chk($('minigallery'))) {
			// Расширяем контроллер под наши цели
			Minigal.implement({
				header: $$('#icont h3')[0],
				desc: $$('#icont .description')[0],
				
				// Высота тумбика:
				theight: 73,

				MorphNew: {
					top: 0,
					opacity: [0,1]
				},

				pathpf: 'img/cont/',


				onImageLoaded: function(a, iobj) {
					this.thumblock.tween('margin-top', + (-this.active.index + 3) * this.theight - 36);
					this.header.set('text', a.get('title'));
					this.desc.set('html', iobj.desc);
					if ($chk(iobj.link)) this.desc.adopt(new Element ('p').adopt(new Element('a', {href: iobj.link, text: 'Подробнее'})));
				}
			});
			window.minigal = new Minigal();
		}
		else if ($chk($('yaminigallery'))) {
			// Расширяем контроллер под наши цели
			Minigal.implement({
				header: $$('#yamninigallery h3')[0],

				pathpf: 'img/cont/yg/',

				MorphNew: {
					left: 0,
					opacity: [0,1]
				}

			});
			window.minigal = new Minigal();
		}
		else if ($chk($('theprojgallery'))) {
			// Расширяем контроллер под наши цели
			Minigal.implement({
				// Ширина тумбика
				twidth: 106,
				
				MorphNew: {
					top: 0,
					opacity: [0,1]
				},
				
				onImageLoaded: function(a,iobj) {
					this.thumblock.tween('margin-left', + (-this.active.index + 4) * this.twidth - 66);
					
				},
				
				onIblockLoading: function() {
					//this.thumblock.setStyle('width', this.iblock.getLength() * this.twidth);
				},

				pathpf: 'img/cont/'

			});
			window.minigal = new Minigal();
		}
	}
})