$(function(){

	var mapContainer = $('div.b-map__wrap');
	if (mapContainer.length > 0) {
		map(mapContainer);
	}

	var galleryContainer = $('div.b-photo-gallery');
	if (galleryContainer.length > 0) {
		new gallery(galleryContainer);
	}

});

function map(container){

	container.preload(function(){
		$(this).show();
	});

	container.delegate('.marker_info .handler', 'click', function(){
		$(this).parent().addClass('marker_active');
	});

	container.delegate('.marker_info .close', 'click', function(){
		$(this).closest('.marker').removeClass('marker_active');
	});

}

function gallery(container){

	var self = this;

	this.container = container;
	this.big = this.container.find('.b-photo-gallery__left img');
	this.thumbs = this.container.find('.b-photo-gallery__thumbs');
	this.items = this.thumbs.children();
	this.pages = this.container.find('.b-photo-gallery__pages');
	this.visible = 8;

	this.generateThumbs();
	this.generatePages();

	this.thumbs.delegate('li', 'click', function(){
		self.open(this);
	});

	this.pages.delegate('li', 'click', function(){
		self.changePage(this);
	});

	this.items.eq(0).addClass('act');

}

gallery.prototype = {
	container: null,
	big: null,
	thumbs: null,
	items: null,
	pages: null,
	visible: null,
	latest: null
};

gallery.prototype.generateThumbs = function(){

	for (var i = 0; i < this.visible; i++) {
		this.items.eq(i).show();
	}

};

gallery.prototype.generatePages = function(){

	var html = '',
		pages = Math.ceil(this.items.length / this.visible);

	for (var i = 0; i < pages; i++) {
		html += '<li class="g-dib" data-page="' + i + '"></li>';
	}

	this.pages.html(html);
	this.pages.children(':first').addClass('act');

};

gallery.prototype.changePage = function(handler){

	handler = $(handler);

	var page = handler.data('page'),
		from = page * this.visible,
		to = from + this.visible;

	this.items
		.hide()
		.slice(from, to).show();

	handler
		.addClass('act')
		.siblings().removeClass('act');

};

gallery.prototype.open = function(handler){

	handler = $(handler);

	var self = this,
		href = handler.children()[0].href;

	this.latest = href;

	handler
		.addClass('act')
		.siblings().removeClass('act');

	$.preload(href, function(){
		self.loaded(href);
	});

};

gallery.prototype.loaded = function(href){

	if (href !== this.latest) {
		return;
	}

	this.big.attr('src', href);

};
