Shadowbox.init({
	language: 'ru',
	adapter: 'mootools',
	skipSetup: true,
	players:  ['img']
});

var Scroller = new Class({

	Implements: [Events, Options],

	options: {
		area: 20,
		velocity: 1,
		onChange: function(x, y){
			this.element.scrollTo(x, y);
		},
		fps: 50,
		horizontal: true, //v3 modified
		vertical: true
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = document.id(element);
		this.listener = ($type(this.element) != 'element') ? document.id(this.element.getDocument().body) : this.element;
		this.timer = null;
		this.bound = {
			attach: this.attach.bind(this),
			detach: this.detach.bind(this),
			getCoords: this.getCoords.bind(this)
		};
		// v3 modified
		this.justhit = {x: true, y: true};
	},

	start: function(){
		this.listener.addEvents({
			mouseenter: this.bound.attach, //v3 modified
			mouseleave: this.bound.detach
		});
	},

	stop: function(){
		this.listener.removeEvents({
			mouseenter: this.bound.attach,
			mouseleave: this.bound.detach
		});
		this.detach();
		this.timer = $clear(this.timer);
	},

	attach: function(){
		this.listener.addEvent('mousemove', this.bound.getCoords);
	},

	detach: function(e){
		var node = this;
		this.detachTimer = (function() {
			node.listener.removeEvent('mousemove', node.bound.getCoords);
			node.timer = $clear(node.timer);
		}).delay(50);
	},

	getCoords: function(event){
		this.page = (this.listener.get('tag') == 'body') ? event.client : event.page;
		if (!this.timer) this.timer = this.scroll.periodical(Math.round(1000 / this.options.fps), this);
	},

	scroll: function(){
		var size = this.element.getSize(),
			scroll = this.element.getScroll(),
			pos = this.element.getOffsets(),
			scrollSize = this.element.getScrollSize(),
			change = {x: 0, y: 0};

		// v3 modified
		if (!this.options.horizontal) delete this.page.x;
		if (!this.options.vertical) delete this.page.y;

		for (var z in this.page){
			if (this.page[z] < (this.options.area + pos[z]) && scroll[z] != 0)
				change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity;
			else if (this.page[z] + this.options.area > (size[z] + pos[z]) && scroll[z] + size[z] != scrollSize[z])
				change[z] = (this.page[z] - size[z] + this.options.area - pos[z]) * this.options.velocity;
		}

		// v3 modified - math.round
		change.x = Math.round(change.x);
		change.y = Math.round(change.y);

		if (change.y || change.x) {
			var newx = scroll.x + change.x;
			var newy = scroll.y + change.y;
			this.fireEvent('change', [newx, newy]);

			// v3 modified - firing edge?
			hitargs = {};
			movedfromargs = {};

			if (this.options.vertical) {
				if (newy >= (scrollSize.y - size.y) || newy <= 0) {
					hitargs.y = newy;
					this.justhit.y = true;
				} else if (this.justhit.y) {
					movedfromargs.y = newy;
					this.justhit.y = false;
				}
			}

			if (this.options.horizontal) {
				if (newx >= (scrollSize.x - size.x) || newx <= 0) {
					hitargs.x = newx;
					this.justhit.x = true;
				} else if (this.justhit.x) {
					movedfromargs.x = newx;
					this.justhit.x = false;
				}
			}

			if (hitargs.x || hitargs.y) {
				this.fireEvent('hitedge', hitargs);
			}
			if (movedfromargs.x || movedfromargs.y) {
				this.fireEvent('movedfromedge', movedfromargs);
			}


		}



	}

});

window.addEvent('domready', function() {

	// включаем shadowbox
  var Shadowbox_options = {
    resizeDuration: 0.1,
    fadeDuration: 0.1,
    marginDuration: 0.03,
    viewportPadding: 10,
    handleOversize: 'resize',
    overlayOpacity: 0.5,
    viewportPadding: 5,
    autoDimensions: true
  };

	list = $$(document.links);
  list = list.filter(function(item){
  	if (item.hasClass('no')) return false;
    return item.href.test(/\.(jpe?g|png|gif|swf)$/)
  });
  if (list && list.length) {
		Shadowbox.setup(list, Shadowbox_options);
  }

  new SmoothScroll({
  	onStart: function() {
  		if (this.oldanchor) {
  			this.oldanchor.removeClass('anchored');
  		}
  		this.oldanchor = $(this.anchor).addClass('anchored');
  	}
  });

  YmapsInit();

	new Tips($$('*[title]'), {className: 'atip'});

  // галерея
  if ($('album_list')) $$('#album_list .album').each(function(album) {

  	album.desc = album.getNext();
  	album.desc.height = album.desc.getSize().y;

  	album.container = album.getParent();

  	album.desc.setStyle('opacity', 0);
  	album.desc.set('tween', {duration: 'short'});

  	album.addEvent('mouseenter', function() {
  		album.container.tween('z-index', 100);
  		album.desc.tween('opacity', 1);

  		/*album.setStyles({
  			'height': album.desc.height,
  			'margin-bottom': 286 - album.desc.height
  		});*/

  	}).addEvent('mouseleave', function() {
  		album.container.tween('z-index', 1);
  		album.desc.tween('opacity', 0);
  	});

  });

  if ($('bigpic')) {

		swfobject.embedSWF("/images/bigpic.swf", 'bigpic_container', 1160, 409, "10.0.0", '/js/expressInstall.swf', null, {
			wmode: 'opaque',
			bgcolor: '#000000',
			allowScriptAccess: 'always'
		});

  }

  if ($('album_pic')) {

		var album_pic_container = $('album_pic');
  	var album_pic_img = album_pic_container.getFirst();
  	var album_pic_h3 = album_pic_img.getNext();

  	$$('#psprev, #psnext').each(function(item) {
  		item.set('tween', {link: 'cancel'});

  	});

		// скроллер
		var iPicScroller = $('picscroller');
  	var scroll_engine = new Scroller(iPicScroller, {
			area: 50,
			velocity: 0.06,
			vertical: true,
			horizontal: false
		});
		scroll_engine.height = iPicScroller.getScrollSize().y - iPicScroller.getSize().y;

		scroll_engine.hidden_prev = true;
		scroll_engine.hidden_next = false;

		var obj_psoverlay_top = $('psoverlay_top');
		var obj_psoverlay_bottom = $('psoverlay_bottom');

		$$(obj_psoverlay_top,obj_psoverlay_bottom).addEvent('mousemove', function(e) {
			iPicScroller.fireEvent('mouseenter', e);
			iPicScroller.fireEvent('mousemove', e);
		}).addEvent('mouseleave', function(e) {
			iPicScroller.fireEvent('mouseleave', e);
		});

		$('psprev').setStyle('opacity', 0);
		obj_psoverlay_top.setStyle('opacity', 0);

		scroll_engine.addEvent('hitedge', function(args) {
			if (args.y < 10) {
				$('psprev').tween('opacity', 0);
				obj_psoverlay_top.tween('opacity', 0);
			} else {
				$('psnext').tween('opacity', 0);
				obj_psoverlay_bottom.tween('opacity', 0);
			}
		});

		scroll_engine.addEvent('movedfromedge', function(args) {
			if (args.y < 100) {
				$('psprev').tween('opacity', 1);
				obj_psoverlay_top.tween('opacity', 1);
			} else {
				$('psnext').tween('opacity', 1);
				obj_psoverlay_bottom.tween('opacity', 1);
			}
		});

		scroll_engine.start();

		var current_pic = null;

		// нажатия на кантирку
		var manual_scroll = new Fx.Scroll(iPicScroller, {
			link: 'cancel',
			transition: 'sine:out',
			wheelStops: false
		});

		pic_first = null;
		pic_last = null;

		iPicScroller.addEvent('mousewheel', function(e) {
			e.stop();
			if (e.wheel > 0) {
				$('psprev').fireEvent('click');
			} else {
				$('psnext').fireEvent('click');
			}
		});

		$$('#picscroller a').each(function(a) {
			if (!current_pic) current_pic = a;

			a.img = a.getFirst();

			if (!pic_first) {
				a.first = true
				pic_first = a;
			}

			if (pic_last) {
				pic_last.last = false;
			}
			a.last = true;
			pic_last = a;

			a.addEvent('click', function(e) {

				var el2 = this.getPrevious();
				if (!el2 || el2.tagName != 'A') el2 = this;
				manual_scroll.toElement(el2);

				if (e) e.stop();

				if (current_pic == this) {
					return false;
				}
				current_pic.removeClass('current');
				this.addClass('current');

				current_pic = this;

				// файрим edge
				var edgeargs = {};
				var movedfromargs = {};

				if (this.first) {
					edgeargs.y = 1;
				} else {
					movedfromargs.y = 150;
				}

				if (this.last) {
					edgeargs.y = 10000;
				} else if (this.getPrevious() && this.getPrevious().first) {
					movedfromargs.y = 50;
				}

				if (edgeargs.y) {
					scroll_engine.fireEvent('hitedge', edgeargs)
				} else if (movedfromargs.y) {
					scroll_engine.fireEvent('movedfromedge', movedfromargs);
				}

				// меняем картинку
				// тут будет мелкая превьюшка, пока не загрузится большая
				var newimg = new Element('img', {
					src: this.img.src,
					width: 574,
					height: 382,
					styles: {
						opacity: 0,
						cursor: 'wait'
					}
				});
				newimg.set('tween', {link: 'cancel'});
				newimg.tween('opacity', 0.3);

				// тут будет большая картинка
				var tmpimg = new Asset.image(this.href, {
					'onload': function(z) {
						newimg.src = this.src;
						newimg.tween('opacity', 1);
						newimg.setStyle('cursor', '');
					}
				});

				// новое описание
				var newh3 = new Element('h3', {
					html: this.title,
					styles: {
						opacity: 0
					}
				});

				// убираем старую, добавляем новую
				album_pic_container.adopt(newimg, newh3);

				// при исчезновении нужно будет уничтожить старые картинки});

				album_pic_h3.set('tween', {
					onComplete: function() {
						$(this.element).destroy();
					}
				});
				album_pic_img.set('tween', {
					onComplete: function() {
						$(this.element).destroy();
					}
				});

				album_pic_img.tween('opacity', 0);
				album_pic_h3.tween('opacity', 0);

				newh3.tween('opacity', 1);

				album_pic_img = newimg;
				album_pic_h3 = newh3;


			});
		});

/*
		iPicScroller.addEvent('mouseleave', function() {
			current_pic.fireEvent('click');
		});
*/

		// кнопки
		$('psprev').addEvent('click', function() {
				var el = current_pic.getPrevious();
				if (!el || el.tagName != 'A') {
					el = current_pic;
				}
				el.fireEvent('click');

		});
		$('psnext').addEvent('click', function() {
				var el = current_pic.getNext();
				if (!el) el = current_pic;
				el.fireEvent('click');

		});

		// ctrl left-right
		var keycatcher = Browser.Engine.trident ? document.body : window;

		keycatcher.addEvent('keydown', function(e) {
			if (e.control) {
				if (e.key == 'right') $('psnext').fireEvent('click');
				else if (e.key == 'left') $('psprev').fireEvent('click');
			}

		});

  }

});


function YmapsInit() {

	/*
	<div class="ymap"><img alt="Адрес" src="http://static-maps.yandex.ru/1.x/?ll=37.123,37.123&amp;z=15&amp;l=map&amp;size=650,400&amp;pt=37.123,37.123,pmlbl&amp;wizard=draw&amp;key=APIKEY" width="650" height="400" /></div>
	*/
	$$('.ymap').each(function(item) {
		var img = item.getFirst();

		try {
			var params = img.src.match(/\?(.*)$/)[1].parseQueryString();
		} catch(ex) {
			return;
		}

		var rest = function() {
			params.geocenter = params.ll.match(/([^,]+),([^,]+)/);
			params.sizes = params.size.match(/([^,]+),([^,]+)/);
			params.point = params.pt.match(/([^,]+),([^,]+)/);

			item.setStyles({
				'width': params.sizes[1] + 'px',
				'height': params.sizes[2] + 'px'
			});

			var map = new YMaps.Map(item);
			map.setCenter(new YMaps.GeoPoint(params.geocenter[1], params.geocenter[2]), params.z, YMaps.MapType.MAP);


			map.addControl(new YMaps.ToolBar());
			map.addControl(new YMaps.Zoom());
			map.addControl(new YMaps.ScaleLine());
			map.addControl(new YMaps.TypeControl());


			var content = document.createElement('span');
			content.innerHTML = img.alt;

			map.openBalloon(new YMaps.GeoPoint(params.point[1], params.point[2]), content);
		}

		if (0 && !this.loaded) {
			this.apikey = params.key;
			this.loaded = true;

			var api = new Element('script');
			api.type = "text/javascript";
			api.src = "http://api-maps.yandex.ru/1.1/?key=" + this.apikey;
			$(document.body).grab(api);
		}

		rest();


	});

}
