﻿/*
 * If you have any questions or comments about this script or if you'd like to report a bug please contact ask.dev at gmail.com
 */
$(document).ready(init);
$(window).bind('resize', onResize);
//
function init() {
	initNav();
	initBg();
	
	initStart();
	initStartCatalog();
	initCatalogNav();
	
	initTitleToggleLink();
	initPressToggleLink();
	initPressForm();
	
	initCatalogCarousel();
	initCatalogItemPreview();
	
	initPopupSelect();
	initMap();
	initAddressList();
	
	initGalleryCarousel();
	initPublications();
	initSearch();
	initContentBlocks();
	initTextTable();
	initSearchForm('footer');
	initSearchForm('page');
	
	initAwardsCarousel();
	initAwardsPreview();
	initEventCarousel();
	initEventList();
	initExhibitionsCarousel();
	initCareerList();
	initHistory();
	initContacts();
	initProcess();
	initCapsule();

	initReqForm();

	initTextForm();
	initTextImageBlock(); 
	$('.catalog-filter-row a.nav-cur').live('click', function(){return false;});
	$('.filter-row a.nav-cur').live('click', function(){return false;});
	$('.press-filter-row a.nav-cur').live('click', function(){return false;});
	
	onResize();
	
	flag = false;
	$("#popup-select-show-2").click(function(){
		
		if(!flag){
			$("#alpha").remove();
			
			//скрываем регионы
			if($("#cityCategs:visible").length > 0){
				$("#popup-select-show").trigger('click');
			}
			
			$.get('/shops/alpha.php', function(data){
				html = '<div id="alpha" class="popup-select-block-2" style="height:360px">';
				html += '<div class="popup-select-queue"></div>';
				html += '<div class="popup-select-list-2">';
				html += '<div class="popup-select-col-2" id="col_1"><ul></ul></div>';
				html += '<div class="popup-select-col-2" id="col_2"><ul></ul></div>';
				html += '<div class="popup-select-col-2" id="col_3"></div>';
				html += '<div class="popup-select-col-2" id="col_4"></div>';
				
				html += '</div></div>';
				
				$("#cityCategs").after(html);
				
				$("#alpha .popup-select-list-2").show();
				$("#alpha .popup-select-col-2").show();
				
				$("#alpha").slideDown('normal', function(){
					$("#alpha").css('height', 'auto');
				});
				
				
				//заполняем алфавит
				al1 = '';
				al2 = '';
				count = 0;
				for(var key in data){
					if(count++ % 2 == 0){
						al1 += '<li><a href="#" rel="' + key + '">' + key + '</a></li>';
					} else {
						al2 += '<li><a href="#" rel="' + key + '">' + key + '</a></li>';
					}
				}
				$("#col_1").find('ul').html(al1);
				$("#col_2").find('ul').html(al2);
				
				
				
				//показываем регионы
				$("#col_1, #col_2").find('a').click(function(){
					
					$("#col_1, #col_2").find('a').removeClass('cur');
					$(this).addClass('cur');
					
					let = $(this).attr('rel');
					
					regHtml = '<ul>';
					
					for(var key in data[let]){
						regHtml += '<li><a href="#" rel="' + key + '">' + data[let][key].title + '</a></li>';
					}
					
					regHtml += '</ul>';
					$("#col_3").html(regHtml);
					$("#col_4").html('');
					
					//показываем города
					$("#col_3").find('a').click(function(){
						
						$("#col_3").find('a').removeClass('cur');
						$(this).addClass('cur');
						
						clet = $(this).attr('rel');
						
						cHtml1 = '<ul>';
						
						count = 0;
						
						for(var k in data[let][clet].cities){
							url = data[let][clet].cities[k].split('||');
							
							cHtml1 += '<li><a href="/shops/' + url[1] + '">' + url[0] + '</a></li>';
							
						}
						
						cHtml1 += '</ul>';
						
						
						
						$("#col_4").html(cHtml1);
						
						return false;
					});
					
					
					return false;
				});
				
				
				
				
			}, 'json');
			
			
			
			
			
		} else {
			$("#alpha").slideUp();
		}
		
		flag = !flag;
		
		return false;
	})
	
	
	
}

function onResize() {
	resizeNav();
	resizeBg();
	resizeStart();
	
	resizePopupSelectCol();
	resizePublications();
	resizeHistory();
resizeContacts();
	resizeProcess();
	resizeCatalogCarousel();
	resizeAwardsCarousel();
	resizeExhibitionsCarousel();
	
	resizeTextImageBlock();
}

function initStart() {
	if ($('.start').length) {
		$('#start-teasers .exclusive').gradientText({
			colors: ['#dbcd83', '#a26f1e']
		});
		resizeStart();
	}
}
function resizeStart() {
	if ($('.start #content').length) {
		$('.start #content').css({height: 'auto'});
		$('.start #content').css({height: ($('#container').height() - $('#header').outerHeight() - $('#footer').outerHeight())+'px'});
	}
}

function initStartCatalog() {
	if ($('.start-catalog').length) {
		$('.start-catalog-block li a').each(setStartCatalogTitle);
		$('.start-catalog-block img').each(setStartCatalogTitle);
		$('.start-catalog li a').hover(hoverStartCatalog, outStartCatalog);
	}
}

function setStartCatalogTitle() {
	$(this).attr('isrc', $(this).attr('title'));
	$(this).attr({title: ''});
}

function initCatalogNav() {
	if ($('.catalog-nav').length) {
		$('.catalog-nav li li:first-child').addClass('first-child');
		$('.catalog-nav li .nav-cur').append($('<i>'));
		
		$('.catalog-category-list li').each(setCatalogListTitle);
		$('.catalog-category-list li a').hover(hoverCatalogList, outCatalogList);
	}
}

function hoverStartCatalog() {
	var parent = $(this).parents('.start-catalog-block');
	var image = parent.find('img');
	image.attr({src: $(this).attr('isrc')});
}
function outStartCatalog() {
	var parent = $(this).parents('.start-catalog-block');
	var image = parent.find('img');
	image.attr({src: image.attr('isrc')});
}

function setCatalogListTitle() {
	$(this).attr('isrc', $(this).find('img').attr('title'));
	$(this).find('img').attr('isrc', $(this).find('img').attr('src'));
	$(this).find('img').attr({title: ''});
}
function hoverCatalogList() {
	var image = $(this).parents('li').find('img');
	image.attr({src: $(this).parents('li').attr('isrc')});
}
function outCatalogList() {
	var image = $(this).parents('li').find('img');
	image.attr({src: image.attr('isrc')});
}

var bgShadowTopH = 805, bgShadowBottomH = 806;
function initBg() {
	if (!$.browser.msie || $.browser.version > 6) {
		$('#container')
		.append(
			$('<div>').addClass('bg-shadow').addClass('bg-shadow-left')
		)
		.append(
			$('<div>').addClass('bg-shadow').addClass('bg-shadow-right')
		);
		$('.bg-shadow-left')
			.append($('<i>').addClass('t'))
			.append($('<i>').addClass('b'))
			.append($('<i>').addClass('c'));
		$('.bg-shadow-right')
			.append($('<i>').addClass('t'))
			.append($('<i>').addClass('b'))
			.append($('<i>').addClass('c'));
		resizeBg();
	}
}
function resizeBg() {
	if (!$.browser.msie || $.browser.version > 6) {
		$('.bg-shadow').css({height: 'auto'});
		$('.bg-shadow i').css({height: '0px'});
		var cHeight = $('#container').height();
		var sWidth = parseInt(($(window).width() - parseInt($('#container').css('maxWidth')))/2);
		if (sWidth < 0) sWidth = 0;
		if (sWidth > 30) sWidth = 30;
		$('.bg-shadow-left').css({left: '-'+sWidth+'px', width: sWidth+'px', height: cHeight+'px'});
		$('.bg-shadow-right').css({right: '-'+sWidth+'px', width: sWidth+'px', height: cHeight+'px'});
		
		var bgCH = 0, bgTH = bgShadowTopH, bgBH = bgShadowBottomH;
		if (cHeight > bgShadowTopH+bgShadowBottomH) {
			bgCH = (cHeight-bgShadowTopH-bgShadowBottomH);
		} else {
			bgTH = parseInt(cHeight/2);
			bgBH = cHeight-bgTH;
		}
		
		$('.bg-shadow .t').css({height: bgTH+'px'});
		$('.bg-shadow .b').css({height: bgBH+'px'});
		$('.bg-shadow .c').css({height: bgCH+'px'});
	}
}

var sepWidthLeft, sepWidthRight;
function initNav() {
	sepWidthLeft = parseInt($('#nav-left li').css('paddingLeft'));
	sepWidthRight = parseInt($('#nav-right li').css('paddingLeft'));
	$('div.nav').each(function() {
		initNavItem($(this));
	});
	$('#nav-sub li:first-child').addClass('first-child');
}
function initNavItem(nav) {
	var sepWidth = (nav.attr('id') == 'nav-left')?sepWidthLeft:sepWidthRight;
	var navBrdId = 'nav-brd'+nav.index();
	$('li:first-child', nav).addClass('first-child');
	if ($('.nav-cur', nav).length) {
		var cur = $('.nav-cur', nav);
		var w = cur.outerWidth();
		cur.addClass('nav-cur-i').after($('<i>').css({width: w+'px'})).after($('<div>').attr({id: navBrdId}).addClass('nav-brd').css({width: w+'px'}));
		drawNavBorder(navBrdId);
	}
}

function drawNavBorder(navBrdId) {
	var w = $('#'+navBrdId).width();
	var h = $('#'+navBrdId).height();
	var paper = Raphael(navBrdId, w, h);
	paper.clear();
	
	var x1 = -1;
	if ($.browser.msie) x1 = 0;
	var x2 = parseInt(w / 2);
	var x3 = w+1;
	var y1 = 0;
	var y2 = h-1;
	
	var path = paper.path('M'+x1+' '+y1+' L'+x2+' '+y2+' L'+x3+' '+y1+' ');
	path.attr({
		'stroke': '#00233f',//'#3e657e',
		'stroke-width': 1
	});
}

function resizeNav() {
	$('div.nav').each(function() {
		resizeNavItem($(this));
	});
}
function resizeNavItem(nav) {
	var itemWidth = 0;
	var itemLength = 0;
	$('li', nav).each(function() {
		itemWidth += $(this).width();
		itemLength++;
	});
	var sepWidth = parseInt( ((nav.find('ul').width() - 100) - itemWidth) / (itemLength - 1) );
	if (sepWidth < 15) sepWidth = 15;
	var bp = parseInt((sepWidth - 5)/2);
	$('li:not(:first-child)', nav).css({paddingLeft: sepWidth + 'px', backgroundPosition: bp+'px 10px'});
	
	if (nav.attr('id') == 'nav-left') sepWidthLeft = sepWidth; else sepWidthRight = sepWidth;
}

function initTitleToggleLink() {
	if (('.page-title-wrapper a.toggle-link').length) {
		$('.page-title-wrapper a.toggle-link').click(clickTitleToggleLink);
	}
}
function clickTitleToggleLink() {
	$('.page-title-wrapper a.toggle-link').toggleClass('toggle-link-opened');
	$('#'+$(this).attr('id')+'-block').toggleClass('toggle-block-opened');
	return false;
}

function initCatalogCarousel() {
	if ($('.catalog-subcategory-carousel').length > 0) {
		resizeCatalogCarousel();
		$('.catalog-subcategory-carousel .catalog-subcategory-list').jcarousel({
			scroll: 4,
			visible: 4,
			animation: 700
		});
		$('.catalog-subcategory-carousel .jcarousel-prev').append($('<i>'));
		$('.catalog-subcategory-carousel .jcarousel-next').append($('<i>'));
	}
}
function resizeCatalogCarousel() {
	if ($('.catalog-subcategory-carousel').length > 0) {
		$('.catalog-subcategory-carousel').css({width: '100%'});
		var w = $('.catalog-subcategory-carousel').width();
		if (w%4 > 0) {
			w = (w - (w%4));
		}
		$('.catalog-subcategory-carousel').css({width: w+'px'});
	}
}


function initCatalogItemPreview() {
	if ($('#catalog-item-thumbs').length > 0) {
		$('#catalog-item-thumbs li a').click(clickItemThumb);
		$('#catalog-item-details-switch').click(toggleItemDetails);
		$('#catalog-item-details-switch').click();
		
		$('#catalog-item-360').click(clickItem360);
	}
}
function clickItem360() {
	$('#catalog-item-thumbs li').removeClass('cur');
	$('#catalog-item-preview-img').hide();
	$('#catalog-item-preview-360').show();
}
function clickItemThumb() {
	$('#catalog-item-preview-360').hide();
	
	$('#catalog-item-thumbs li').removeClass('cur');
	$(this).parents('li').addClass('cur');
	
	//$('#catalog-item-details').hide();
	//$('#catalog-item-details-switch').removeClass('opened');
	
	var im = new Image();
	im.onload = function() {
		var imSrc = this.src;
		$('#catalog-item-preview-img').fadeOut(function() {
			$('#catalog-item-preview-img').attr({src: imSrc}).fadeIn();
		});
	}
	im.src = $(this).attr('href');
	
	
	return false;
}
function toggleItemDetails() {
	$('#catalog-item-details').toggle();
	$(this).toggleClass('opened');
}




function initPopupSelect() {
	$('.popup-select-title .ico-select').unbind('click').click(showPopupSelect);
	$('.popup-select-block').unbind('click').click(function(e){ e.stopPropagation(); });
	$('body').unbind('click').click(hidePopupSelect3);
	$('.popup-select-close').unbind('click').click(hidePopupSelect);
	
	$('.popup-select-queue li a').unbind('click').click(clickPopupSelectQueue);
	
	loadRegions();
	resizePopupSelectCol();
}



function loadRegions(){
	$('#list-select-district a, #list-select-region a').unbind('click').click(function(){
		
		//берем урл и реплейсим путь к простому макету для подгрузки разделов
		str = $(this).attr('href');
		if(str.indexOf('shops') != -1){//магазины
			str = str.split('shops').join('shops/categ');
		} else { //сервисные центры
			str = str.split('service').join('service/categ');
		}
			
		$('#cityCategs').load(str, function(){
			initPopupSelect();
			//сворачиваем/разворачиваем список регионов
			$('.popup-select-title .ico-select').trigger('click');
			$('.popup-select-title .ico-select').trigger('click');
		});
			
		return false;
	});
}

var newPopupSelectId = '';
function clickPopupSelectQueue() {
	
	//Активность табов
		if($(this).parent().index() == 0){
			$(this).parents('ul').find('li:eq(2)').addClass('inactive');
			$(this).parents('ul').find('li:eq(4)').addClass('inactive');
		} else if($(this).parent().index() == 2){
			$(this).parents('ul').find('li:eq(4)').addClass('inactive');
		}
		
	
	
	if (newPopupSelectId == '') {
		var blockParent = $(this).parents('.popup-select-container');
		if (!$(this).parents('li').hasClass('inactive')) {
			newPopupSelectId = $(this).attr('rel').substr(1);
			
			$('.popup-select-queue li', blockParent).removeClass('active');
			$('.popup-select-list-active', blockParent).slideUp(finishClickSelectQueue);
		}
	}
	return false;
}
function finishClickSelectQueue() {
	$(this).removeClass('popup-select-list-active');
	$('#list-'+newPopupSelectId).slideDown(showPopupList);
}
function showPopupList() {
	$('.popup-select-queue li').each(function() {
		if ($(this).find('a').attr('rel') == '#'+newPopupSelectId) $(this).addClass('active');
	});
	$(this).addClass('popup-select-list-active');
	resizePopupSelectCol();
	newPopupSelectId = '';
}
function showPopupSelect() {
	
	if($("#alpha:visible").length > 0){
		$("#popup-select-show-2").trigger('click');
	}
	
	var blockParent, blockElem;
	blockParent = $(this).parents('.popup-select-container');
	if ($('.popup-select-block', blockParent).length > 1) {
		blockElem = $('#'+$(this).attr('id').replace('show', 'block'));
	} else {
		blockElem = $('.popup-select-block', blockParent);
	}
	
	var openIt = true;
	if ($('.popup-select-block-active', blockParent).length) {
		if (blockElem.hasClass('popup-select-block-active')) {
			openIt = false;
		}
		hidePopupSelect2(blockParent);
	}
	
	if (openIt) {
		$('.popup-select-list', blockParent).removeClass('popup-select-list-active');//
		blockElem.addClass('popup-select-block-active');
		$('.popup-select-list', blockElem).removeClass('popup-select-list-active');
		if ($('.popup-select-queue', blockElem).length) {
			var activetabs = $('.popup-select-queue li:not(.inactive) .ico-select', blockElem);
			var li = $(activetabs.get(activetabs.length - 1)).parents('li');
			var id = li.find('a').attr('rel').substr(1);
			$('#list-'+id).addClass('popup-select-list-active');
			$('.popup-select-queue li', blockElem).removeClass('active');
			li.addClass('active');
		} else {
			$('.popup-select-list', blockElem).addClass('popup-select-list-active');
		}
		blockElem.slideDown(resizePopupSelectCol);
		//resizePopupSelectCol();
		
		//$('.popup-select-victim').css({opacity: 0.3});
		togglePopupSelectVictim(blockParent, 0.3);
	}
	return false;
}
function hidePopupSelect() {
	var blockParent = $(this).parents('.popup-select-container');
	//$('.popup-select-list').removeClass('popup-select-list-active');
	$('.popup-select-col', blockParent).css({height: 'auto'});
	$('.popup-select-block', blockParent).removeClass('popup-select-block-active').slideUp();
	
	//$('.popup-select-victim').css({opacity: 1});
	togglePopupSelectVictim(blockParent, 1);
}
function hidePopupSelect2(blockParent) {
	//$('.popup-select-list').removeClass('popup-select-list-active');
	$('.popup-select-col', blockParent).css({height: 'auto'});
	$('.popup-select-block', blockParent).removeClass('popup-select-block-active').slideUp();
	
	//$('.popup-select-victim').css({opacity: 1});
	togglePopupSelectVictim(blockParent, 1);
}
function hidePopupSelect3() {
	$('.popup-select-col').css({height: 'auto'});
	$('.popup-select-block').removeClass('popup-select-block-active').slideUp();
	
	$('.popup-select-victim').css({opacity: 1});
}
function resizePopupSelectCol() {
	$('.popup-select-container').each(function() {
		var list = $('.popup-select-block-active .popup-select-list-active', $(this));
		if (list.length > 0 && list.is(':visible')) {
			if ($('.popup-select-col', list).length > 1) {
				$('.popup-select-col', list).css({height: 'auto'});
				$('.popup-select-col', list).css({height: list.outerHeight() + 'px'});
			}
		}
	});
}
function togglePopupSelectVictim(blockParent, opacity) {
	var index = -1;
	for (i=0;i<$('.popup-select-container').length;i++) {
		if ($('.popup-select-container').get(i) == blockParent.get(0)) index = i;
	}
	if (index >= 0) $($('.popup-select-victim').get(index)).css({opacity: opacity});
}



function initAddressList() {
	if ($('.address-list-container').length > 0) {
		if ($('.address-list-row').length > 20)
		{
			$('.address-list-header p').click(toggleAddressList);
			$('.address-more-button').click(loadNextAddressPage);
		}

		$('.address-list-container .toggle-link').click(toggleAdressRow);
	}
}
function toggleAddressListHelper() {
	$('.address-list-header').toggleClass('address-list-header-opened');
	$('.address-list-container').toggleClass('address-list-container-opened');
	$('.address-list-container .toggle-link').click(toggleAdressRow);
	$('.address-more-button').click(loadNextAddressPage);

	onResize();
}
function toggleAddressList() {
	var url = new String (window.location);
	var sign = url.indexOf('?') > 0 ? '&' : '?';

	if ($(this).parents('.address-list-header').hasClass('address-list-header-opened'))
	{
		$('.address-list-container').load(url + sign + 'num_13=20 #ajax-container', toggleAddressListHelper);
	}
	else
	{
		$('.address-list-container').load(url + sign + 'num_13=100000 #ajax-container', toggleAddressListHelper);
	}
}
function toggleAdressRow() {
	$(this).parents('.address-list-row').toggleClass('address-list-row-opened');
}
function loadNextAddressPageHelper() {
        $('.address-more-button').first().remove();

	var html = $('#ajax-loader-helper').html();
	$('#ajax-loader-helper').html('');

	$('#ajax-container').html($('#ajax-container').html() + html);
	
	$('.address-list-container .toggle-link').click(toggleAdressRow);
	$('.address-more-button').click(loadNextAddressPage);
	if ($('.address-more-button').length == 0) {
		$('.address-list-header').toggleClass('address-list-header-opened');
		$('.address-list-container').toggleClass('address-list-container-opened');
	}	
	onResize();
}
function loadNextAddressPage() {
	var url = $('.address-more-button a').first().attr("href");
	$(this).unbind('click', loadNextAddressPage);
	$('.address-more-button').html('<img src="/img/ajax-loader.gif">');
	$('#ajax-loader-helper').load(url + ' #ajax-rows', loadNextAddressPageHelper);
	
	return false;
}

function initGalleryCarousel() {
	if ($('.photo-gallery-carousel').length > 0) {
		$('.photo-gallery-carousel li a').click(clickGalleryCarousel);
		$('.photo-gallery-carousel .photo-gallery-list').jcarousel({
			scroll: 1
		});
		$('.photo-gallery-carousel .jcarousel-prev').append($('<i>'));
		$('.photo-gallery-carousel .jcarousel-next').append($('<i>'));
		$('.photo-gallery-carousel li:first a').click();
	}
}

function clickGalleryCarousel() {
	var carousel = $(this).parents('.photo-gallery-carousel');
	$('li a', carousel).removeClass('cur');
	$(this).addClass('cur');
	$('.photo-gallery-preview img', carousel).attr({src: $(this).attr('href')});
	return false;
}

var publicationsOpened = false, publicationsLength = 0, publicationsIndex = -1;
function initPublications() {
	if ($('#publications').length) {
		publicationsLength = $('#publications li').length;
		if (publicationsLength <= 1) {
			w = 100;
			$('#publications ul').css({width: '50%'});
		} else if (publicationsLength < 5) {
			w = parseInt(100/publicationsLength);
		} else {
			w = 25;
		}
		$('#publications li').css({width: w+'%'});
		$('#publications li a').click(clickPublication);
		
		$('body').append($('<div>').attr({id: 'publications-window'}));
			$('#publications-window').append($('<div>').attr({id: 'publications-window-image'}).append('<img>'));
			$('#publications-window').append($('<div>').attr({id: 'publications-window-close'}));
			$('#publications-window-close').live('click', closePublicationsWindow)
			$('#publications-window').append($('<div>').attr({id: 'publications-window-prev'}).addClass('publications-window-arrow'));
			$('#publications-window').append($('<div>').attr({id: 'publications-window-next'}).addClass('publications-window-arrow'));
			$('.publications-window-arrow').live('click', clickPublicationsArrow);
	}
	if ($('.press-more-button').length) {
		$('.press-more-button').click(loadNextPressPage);
	}
}
function loadNextPressPageHelper() {
	if ($('#publications-list').length)
	{
		$('.press-more-button').first().remove();

		var html = $('#ajax-loader-helper').html();
		$('#ajax-loader-helper').html('');

		$('#publications-list').html($('#publications-list').html() + html);
	}
	else if ($('#press-releases-small').length)
	{
		var html = $('#ajax-loader-helper > #ajax-container > #press-releases-small').html();
		var pager = $('#ajax-loader-helper > #ajax-container > .press-more-button').html();
		$('#ajax-loader-helper').html('');

		$('#press-releases-small').html($('#press-releases-small').html() + html);
		if (pager)
			$('.press-more-button').html(pager);
		else
			$('.press-more-button').remove();
		
	}

	$('.press-more-button').click(loadNextPressPage);

	onResize();
}
function loadNextPressPage() {
	var url = $('.press-more-button a').first().attr("href");

	$(this).unbind('click', loadNextPressPage);
	$('.press-more-button').html('<img src="/img/ajax-loader.gif">');
	$('#ajax-loader-helper').load(url + ' #ajax-container', loadNextPressPageHelper);
	
	return false;
}

function clickPublication() {
	$('#publications-window').fadeIn();
	$('#publications-window-image').css({height: $('#publications-window').height()+'px'});
	publicationsOpened = true;
	publicationsIndex = $(this).parents('li').index();
	$('#publications-window img').attr({src: ''}).hide();
	var im = new Image();
	im.onload = function() {
		$('#publications-window img').attr({src: this.src}).fadeIn();
		resizePublications();
	}
	im.src = $(this).attr('href');
	checkPublicationsArrows();
	resizePublications();
	return false;
}
function clickPublicationsArrow() {
	$('#publications-window img').attr({src: ''}).hide();
	if ($(this).attr('id') == 'publications-window-next') publicationsIndex++;
	else publicationsIndex--;
	var im = new Image();
	im.onload = function() {
		$('#publications-window img').attr({src: this.src}).fadeIn();
		resizePublications();
	}
	im.src = $($('#publications li').get(publicationsIndex)).find('a').attr('href');
	checkPublicationsArrows();
	return false;
}
function closePublicationsWindow() {
	$('#publications-window').fadeOut();
	$('#publications-window img').attr({src: ''}).hide();
	$('#publications-window-image').css({height: 'auto'});
	publicationsOpened = false;
	publicationsIndex = -1;
}
function checkPublicationsArrows() {
	if (publicationsIndex <= 0) {
		$('#publications-window-prev').hide();
	} else {
		$('#publications-window-prev').show();
	}
	if (publicationsIndex >= publicationsLength-1) {
		$('#publications-window-next').hide();
	} else {
		$('#publications-window-next').show();
	}
}
function resizePublications() {
	if ($('#publications-window').length) {
		if (publicationsOpened) {
			$('#publications-window').css({height: 'auto'});
			var h1 = $('#publications-window img').height();
			var h2 = $('#container').height();
			$('#publications-window').css({width: $(window).width()+'px', height: ((h1>h2)?h1:h2)+'px'});
		}
	}
}

var map = false;
function initMap() {
	if ($('#ymap').length > 0) {
		YMaps.jQuery(window).load(function () {
			map = new YMaps.Map(YMaps.jQuery("#ymap")[0]);
			map.setCenter(new YMaps.GeoPoint(37.546946,55.830815), 11, YMaps.MapType.MAP);
			map.addControl(new YMaps.Zoom());
			map.addControl(new YMaps.ToolBar());
			YMaps.MapType.PMAP.getName = function () { return "Народная"; };
			map.addControl(new YMaps.TypeControl([
				YMaps.MapType.MAP,
				YMaps.MapType.SATELLITE,
				YMaps.MapType.HYBRID,
				YMaps.MapType.PMAP
			], [0, 1, 2, 3]));

			YMaps.Styles.add("constructor#nikaPlacemark", {
				iconStyle : {
					href : "/img/ym/placemark.png",
					size : new YMaps.Point(43,39),
					offset: new YMaps.Point(-15,-36)
				}
			});
			YMaps.Styles.add("constructor#nikaPlacemarkPartners", {
				iconStyle : {
					href : "/img/ym/placemark_partners.png",
					size : new YMaps.Point(43,39),
					offset: new YMaps.Point(-15,-36)
				}
			});

			if (typeof(shopCoordinates) != "undefined")
			{
				function createObject (type, point, style, description) {
					var allowObjects = ["Placemark", "Polyline", "Polygon"],
						index = YMaps.jQuery.inArray( type, allowObjects),
						constructor = allowObjects[(index == -1) ? 0 : index];
						description = description || "";
					
					var object = new YMaps[constructor](point, {style: style, hasBalloon : !!description});
					object.description = description;
				
					return object;
				}
 
				var map_markers = [];
				for (i=0;i<shopCoordinates.length;i++) {
					map_markers[i] = new YMaps.GeoPoint(shopCoordinates[i][1],shopCoordinates[i][2]);
					if(shopCoordinates[i][3] == 423 || shopCoordinates[i][3] == 44){
						map.addOverlay(createObject("Placemark", map_markers[i], "constructor#nikaPlacemark", shopCoordinates[i][0]));
					} else {
						map.addOverlay(createObject("Placemark", map_markers[i], "constructor#nikaPlacemarkPartners", shopCoordinates[i][0]));
					}
				}

				map.setBounds(new YMaps.GeoCollectionBounds(map_markers));
				map.setZoom(11);
			}
		});
	}
}

function initTextTable() {
	$('.text table tr').hover(
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
}

function initContentBlocks() {
	/*if ($('.content-col-r').length) {
		$('.content-col-l').css({height: 'auto'});
		if ($('.content-col-l').height() < $('.content-col-r').height()) {
			$('.content-col-l').css({height: $('.content-col-r').height()+'px'});
		}
	}*/
}


function initSearchForm(name) {
	if ($('#'+name+'-search-form').length) {
		$('#'+name+'-search-field i').click(clickSearchButton);
		inputHelper($('#'+name+'-search-query'), 'Поиск');
	}
}
function clickSearchButton() {
	if (!$(this).prev('input').hasClass('empty')) $(this).parents('form').submit();
}



function initAwardsCarousel() {
	if ($('.awards-carousel').length > 0) {
		resizeAwardsCarousel();
		$('.awards-carousel .awards-list').jcarousel({
			scroll: 3,
			visible: 3,
			animation: 700
		});
		$('.awards-carousel .jcarousel-prev').append($('<i>'));
		$('.awards-carousel .jcarousel-next').append($('<i>'));
	}
}
function resizeAwardsCarousel() {
	if ($('.awards-carousel').length > 0) {
		$('.awards-carousel').css({width: '100%'});
		var w = $('.awards-carousel').width();
		if (w%3 > 0) {
			w = (w - (w%3));
		}
		$('.awards-carousel').css({width: w+'px'});
	}
}


function initAwardsPreview() {
	$('#awards .award-preview-link').click(clickAwardsPreviewLink);
	$('#awards .award-preview-close').click(closeAwardsPreview);
	$('.award-preview-image').click(function(){
		$('#awards .award-preview-close').trigger('click');
	});
}
var awardPreviewLinkCaller;
function clickAwardsPreviewLink() {
	var im = new Image;
	im.onload = function() {
		$('#awards .award-preview-image img').attr({src: this.src});
		
		var t = 50;
		
		if (awardPreviewLinkCaller.parents('.awards-table-row').length > 0) {
		
			//var t = $('#header').height() + $('.page-title-wrapper').height();
			
			var st = $(window).scrollTop() - $('#header').height() - $('.page-title-wrapper').height();
			if (st > t) t = st;
			
			$('#awards .award-preview').css('top', '10px');
			
			var h1 = $('#awards').outerHeight(),
				h2 = t + this.height + 10,
				h = (h1>h2)?h1:h2;
			$('#awards').css({height: 'auto'});
			if (h1<h2) $('#awards').css({height: ($('#awards').height() + (h2-h1))+'px'});
			
			$('#awards .award-preview-bg').css({height: h+'px'});
			$('#awards .award-preview').show();
				$('#awards .award-preview-image').css({height: (h-t)+'px'});
			
		} else {
			
			//var t = $('#header').height() + $('.page-title-wrapper').height();
			
			var st = $(window).scrollTop() - $('#header').height() - $('.page-title-wrapper').height();
			if (st > t) t = st;
			
			$('#awards .award-preview').css('top', '10px');
			
			//var h = $('#awards .awards-carousel').height();
			var h = $('#awards').outerHeight();
			$('#awards .award-preview-bg').css({height: h+'px'});
			$('#awards .award-preview').show(); 
				$('#awards .award-preview-image').css({height: (h-t)+'px'});
			
		}
		
		$('#awards .award-preview-image').css({'padding-top': (t-50)+'px'});
		$('#awards .award-preview-close').css({top: (t-30)+'px'});
	}
	im.src = $(this).attr('href');
	awardPreviewLinkCaller = $(this);
	
	return false;
}
function closeAwardsPreview() {
	$('#awards .award-preview').hide();
	$('#awards').css({height: 'auto'});
}


/////////////////////////////////////////////////////////////////////
var eventPreviewWidth = 930, eventPreviewIndex = 0, eventPreviewLoadCount = 0, eventCarouselLength = 0, eventCarouselWidth = 0;
function initEventCarousel() {
	if ($('.event-gallery-carousel').length > 0) {
		$('.event-gallery-carousel li a').click(clickEventCarousel);
		$('.event-gallery-carousel .event-gallery-list').jcarousel({
			scroll: 1,
            animation: 700,
            itemFallbackDimension: 930
		});
		$('.event-gallery-carousel .jcarousel-prev').append($('<i>'));
		$('.event-gallery-carousel .jcarousel-next').append($('<i>'));
		
		$('.event-gallery-carousel .event-gallery-preview-arrow').click(clickEventPreviewArrow);
		
		eventPreviewWidth = $('.event-gallery-preview-wrapper').width();
		eventCarouselWidth = $('.event-gallery-carousel li').width();
		
		var im = [], index = 0, i = 0;
		eventCarouselLength = $('.event-gallery-carousel li').length;
		$('.event-gallery-carousel li').each(function() {
			index = parseInt($(this).attr('id').substr(5));
			$('.event-gallery-preview-container').append(
				$('<img>').attr({src: "img/event-photo.png", iWidth: 930, iHeight: 605, id: 'photo'+index})
			);
			im[i] = new Image();
			im[i].id = 'image'+index;
			im[i].onload = function() {
				var index = parseInt(this.id.substr(5));
				$('.event-gallery-preview-container #photo'+index).attr({src: this.src, iWidth: this.width, iHeight: this.height}).css({width: this.width+'px', height: this.height+'px'});
				eventPreviewLoadCount++;
				if (eventPreviewLoadCount == eventCarouselLength) {
					var f = function() {falseClickEventCarousel(eventPreviewIndex);};
					setTimeout(f, 20);
				}
			}
			im[i].src = $(this).find('a').attr('href');
			i++;
		});

		var thumbDefined = false;
		if (window.location.hash) {
			var index = parseInt(window.location.hash.substr(1));
			if ($('.event-gallery-carousel #thumb'+index).length > 0) {
				thumbDefined = true;
				//$('.event-gallery-carousel #thumb'+index+' a').click();
				eventPreviewIndex = index;
			}
		}
		if (!thumbDefined) {
			//$('.event-gallery-carousel li:first a').click();
			eventPreviewIndex = parseInt($('.event-gallery-carousel li:first').attr('id').substr(5));
		}
		
		//falseClickEventCarousel(eventPreviewIndex);
		
		checkEventPreviewArrows();
	}
}
function showEventPreview(anim) {
	var index = $('.event-gallery-carousel .event-gallery-preview').attr('cIndex'),
		margin = 0,
		found = false;
	
	/*
	//var len = $('.event-gallery-preview-container img').length();
	for (i = 0; i<index; i++) {
		margin += parseInt($($('.event-gallery-preview-container img').get(i)).attr('iWidth'));
	}
	*/
	$('.event-gallery-preview-container img').each(function() {
		if (!found) {
			if (index == parseInt($(this).attr('id').substr(5))) {
				found = true;
			}
		}
		if (!found) {
			margin += parseInt($(this).attr('iWidth'));
			//$('.event-gallery-carousel .jcarousel-next').click();
		}
	});
	//centering
	var w = parseInt( $('.event-gallery-preview-container #photo'+index).attr('iWidth') );
	if (w < eventPreviewWidth) {
		margin -= parseInt((eventPreviewWidth - w)/2);
	}
	if (margin < 0) margin = 0;
	
	if (anim) $('.event-gallery-preview-container').animate({marginLeft: '-'+margin+'px'}, {duration: 600, easing: 'linear'});
	else $('.event-gallery-preview-container').css({marginLeft: '-'+margin+'px'});
}
function clickEventCarousel() {
	var carousel = $(this).parents('.event-gallery-carousel');
	$('li a', carousel).removeClass('cur');
	$(this).addClass('cur');
	var index = $(this).parents('li').attr('id').substr(5);
	$('.event-gallery-preview', carousel).attr({cIndex: index});
	showEventPreview(true);
	moveEventCarousel(index, true);
	checkEventPreviewArrows();
	window.location.hash = '#'+index;
	return false;
}
function falseClickEventCarousel(index) {
	var elem = $('.event-gallery-carousel #thumb'+index),
		carousel = elem.parents('.event-gallery-carousel');
	elem.find('a').addClass('cur');
	$('.event-gallery-preview', carousel).attr({cIndex: index});
	showEventPreview(false);
	moveEventCarousel(index, false);
	checkEventPreviewArrows();
	window.location.hash = '#'+index;
}
function moveEventCarousel(index, anim) {
	var i = $('.event-gallery-carousel #thumb'+index).index()+1;
	var carousel = $('.event-gallery-carousel .event-gallery-list').data('jcarousel');
	carousel.scroll(i, anim);
}
function clickEventPreviewArrow() {
	var index = $('.event-gallery-carousel .event-gallery-preview').attr('cIndex'),
		len = eventCarouselLength,
		item;
	if ($(this).hasClass('event-gallery-preview-arrow-prev')) {
		//index--;
		//if (index == -1) index = 0;
		var item = $('.event-gallery-carousel #thumb'+index).prev('li');
		if (item.length == 1) {
			index = parseInt(item.attr('id').substr(5));
		} else {
			index = parseInt($('.event-gallery-carousel li:first').attr('id').substr(5));
		}
		$('.event-gallery-carousel .jcarousel-prev').click();
	}
	if ($(this).hasClass('event-gallery-preview-arrow-next')) {
		//index++;
		//if (index == len) index = len-1;
		var item = $('.event-gallery-carousel #thumb'+index).next('li');
		if (item.length == 1) {
			index = parseInt(item.attr('id').substr(5));
		} else {
			index = parseInt($('.event-gallery-carousel li:last').attr('id').substr(5));
		}
		$('.event-gallery-carousel .jcarousel-next').click();
	}
	//$($('.event-gallery-carousel li').get(index)).find('a').click();
	$('.event-gallery-carousel #thumb'+index).find('a').click();
	showEventPreview(true);
}
function checkEventPreviewArrows() {
	var index = $('.event-gallery-carousel .event-gallery-preview').attr('cIndex');
	var len = eventCarouselLength;
	if (len == 1) {
		$('.event-gallery-carousel .event-gallery-preview-arrow-prev').hide();
		$('.event-gallery-carousel .event-gallery-preview-arrow-next').hide();
	} else if (index == parseInt($('.event-gallery-carousel li:first').attr('id').substr(5))) {
		$('.event-gallery-carousel .event-gallery-preview-arrow-prev').hide();
		$('.event-gallery-carousel .event-gallery-preview-arrow-next').show();
	} else if (index == parseInt($('.event-gallery-carousel li:last').attr('id').substr(5))) {
		$('.event-gallery-carousel .event-gallery-preview-arrow-prev').show();
		$('.event-gallery-carousel .event-gallery-preview-arrow-next').hide();
	} else {
		$('.event-gallery-carousel .event-gallery-preview-arrow-prev').show();
		$('.event-gallery-carousel .event-gallery-preview-arrow-next').show();
	}
}
//////////////////////////////////////////////////////////////////////////////

function initEventList() {
	$('.event-more-button').click(loadNextEventPage);
}
function loadNextEventPageHelper() {
        $('.event-more-button').first().remove();

	var html = $('#ajax-loader-helper').html();
	$('#ajax-loader-helper').html('');

	$('#ajax-container').html($('#ajax-container').html() + html);
	
	$('.event-more-button').click(loadNextEventPage);
	onResize();
}
function loadNextEventPage() {
	var url = $('.event-more-button a').first().attr("href");
	$(this).unbind('click', loadNextEventPage);
	$('.event-more-button').html('<img src="/img/ajax-loader.gif">');
	$('#ajax-loader-helper').load(url + ' #ajax-container', loadNextEventPageHelper);
	
	return false;
}

function initExhibitionsCarousel() {
	if ($('.exhibitions-carousel').length > 0) {
		resizeExhibitionsCarousel();
		$('.exhibitions-carousel .exhibitions-list').jcarousel({
			scroll: 1,
			visible: 3,
			animation: 700
		});
		$('.exhibitions-carousel .jcarousel-prev').append($('<i>'));
		$('.exhibitions-carousel .jcarousel-next').append($('<i>'));
	}
}
function resizeExhibitionsCarousel() {
	if ($('.exhibitions-carousel').length > 0) {
		$('.exhibitions-carousel').css({width: '100%'});
		var w = $('.exhibitions-carousel').width();
		if (w%3 > 0) {
			w = (w - (w%3));
		}
		$('.exhibitions-carousel').css({width: w+'px'});
	}
}

function initCareerList() {
	if ($('.career-vacancies').length > 0) {
		$('.career-vacancies .career-row-title').click(toggleCareerRow);
		
		$('#career .career-mail-form b').click(function() {
			$(this).next('.career-mail-form-wrapper').slideToggle();
		});
		$('#career .career-mail-form-error b').click(function() {
			$(this).parents('.career-mail-form-error').hide().prev('.career-mail-form').fadeIn();
		});
	}
	if ($('.career-more-button').length > 0) {
		$('.career-more-button').click(clickCareerMoreButton);
	}
}
function clickCareerMoreButton() {
	if ($(this).hasClass('career-more-button-close')) {
		//$('.career-more-text').slideUp(function() { $('.career-more-button').removeClass('career-more-button-close'); });
		$(this).prev('.career-image-text').animate({height: '300px'}, 1000, function() {
			$(this).removeClass('career-image-text-opened');
			$('.career-more-button').removeClass('career-more-button-close');
		});
	} else {
		//$('.career-more-text').slideDown(function() { $('.career-more-button').addClass('career-more-button-close'); });
		$(this).prev('.career-image-text').css({height: 'auto'});
		h = $(this).prev('.career-image-text').height();
		$(this).prev('.career-image-text').css({height: '300px'}).addClass('career-image-text-opened');
		$(this).prev('.career-image-text').animate({height: h+'px'}, 1000, function() { $('.career-more-button').addClass('career-more-button-close'); });
	}
}
function toggleCareerRow() {
	if ($(this).parents('.career-row').hasClass('career-row-opened')) {
		$(this).next('.career-row-text').animate({height: '2em'}, 1000, function() {
			$(this).parents('.career-row').removeClass('career-row-opened');
		});
	} else {
		$(this).next('.career-row-text').css({height: 'auto'});
		h = $(this).next('.career-row-text').height();
		$(this).next('.career-row-text').css({height: '2em'});
		$(this).parents('.career-row').addClass('career-row-opened');
		//$(this).next('.career-row-text').slideDown(1000);
		$(this).next('.career-row-text').animate({height: h+'px'}, 1000);
	}
}

var hWindowWidth, hContainerParentWidth, hContainerWidth, hYearsLength, hYearsOffsets = [], hButtonWidth = 100;
function initHistory() {
	if ($('#history-container').length) {
		hYearsLength = $('#history-container .history-year').length;
		hContainerWidth = 25 + hButtonWidth*3;
		offset = 0;//hButtonWidth;
		lastWidth = $('#container').width() - hButtonWidth - 25;
		for (i=0;i<hYearsLength;i++) {
			w = $($('#history-container .history-year').get(i)).width();
			if (i == hYearsLength-1) {
				if (w < lastWidth) w = lastWidth;
			}
			hYearsOffsets[i] = offset;
			hContainerWidth += w;
			offset += w;
		}
		
		$('#history-container').css({padding: '0 '+hButtonWidth+'px', width: hContainerWidth+'px'});
		resizeHistory();
		
		$('#history-container').draggable({
			containment: 'parent',
			start: function(event, ui) {
			
			},
			drag: function(event, ui) {
				checkHistoryMargin();
			},
			stop: function(event, ui) {
			
			}
		});
		//$('#history-container').animate({left: '0px'});
		
		$('.history-image').hover(increaseHistoryImage, restoreHistoryImage);
		$('.history-image').mousedown( function(e) { e.stopPropagation(); e.preventDefault(); } );
		
		$.fn.disableSelection = function() {
			$(this).attr('unselectable', 'on')
				.css('-moz-user-select', 'none')
				.css('-webkit-user-select', 'none')
				.each(function() { 
					this.onselectstart = function() { return false; };
				});
		};
		
		$('#history-container').disableSelection();
		
		$('#history-wrapper').append(
			$('<div>').addClass('history-button').attr({id: 'history-button-prev'})
		);
		$('#history-wrapper').append(
			$('<div>').addClass('history-button').attr({id: 'history-button-next'})
		);
		
		$('.history-button').hover(moveHistoryWrapper, stopHistoryWrapper);
		$('#history-nav a').bind('click', clickHistoryNav);
		//$('#history-nav a:last').click();
		
		var i = hYearsLength-1;
		var left = parseInt(hContainerParentWidth - hContainerWidth - hButtonWidth*2 - hYearsOffsets[i]);
		$('#history-container').css({left: left+'px'});
		checkHistoryMargin();
		
		$('#history-container').mousedown(stopHistoryWrapper);
	}
}

var hMoveInterval, baseDuration = 1000;
function moveHistoryWrapper(e) {
	var curLeft = parseInt($('#history-container').css('left'));
	var duration = 0;
	
	if ($(this).attr('id') == 'history-button-prev') {
		duration = (hContainerParentWidth - hContainerWidth) - curLeft + baseDuration;
		$('#history-container').stop().animate({left: (hContainerParentWidth - hContainerWidth - hButtonWidth*2)+'px'}, {duration: duration, easing: 'linear', complete: stopHistoryWrapper});
		hMoveInterval = setInterval(checkHistoryMargin, 200);
	}
	if ($(this).attr('id') == 'history-button-next') {
		duration = curLeft + baseDuration;
		$('#history-container').stop().animate({left: '0px'}, {duration: duration, easing: 'linear', complete: stopHistoryWrapper});
		hMoveInterval = setInterval(checkHistoryMargin, 200);
	}
	
	e.stopPropagation();
}

function clickHistoryNav() {
	var i = 0;//$(this).index();
	var year = $(this).find('em').html();
	$('.history-year').each(function() {
		if ($(this).find('h2').html() == year) i = $(this).index();
	});
	var left = hContainerParentWidth - hContainerWidth - hButtonWidth*2 - hYearsOffsets[i];
	var curLeft = parseInt($('#history-container').css('left'));
	duration = Math.abs(left - curLeft);// + baseDuration;
	duration = parseInt(duration*0.4) + baseDuration;
	$('#history-container').stop().animate({left: left+'px'}, {duration: duration, easing: 'linear', complete: stopHistoryWrapper});
	hMoveInterval = setInterval(checkHistoryMargin, 200);
	return false;
}

var hCurIndex = -1;
function checkHistoryMargin() {
	var curIndex = -1, curLeft = hContainerParentWidth - hContainerWidth - hButtonWidth - parseInt($('#history-container').css('left'));
	for (i=0;i<hYearsLength;i++) {
		if (curLeft >= hYearsOffsets[i]) curIndex = i;
	}
	if (hCurIndex != curIndex) {
		$('#history-nav a').removeClass('nav-cur');
		$($('#history-nav a').get(curIndex)).addClass('nav-cur');
	}
	hCurIndex = curIndex;
}

function stopHistoryWrapper() {
	$('#history-container').stop();
	clearInterval(hMoveInterval);
	//kontrolny!
	checkHistoryMargin();
}

function increaseHistoryImage(e) {
	$(this).stop().animate({
		left: '-30px',
		top: '-30px',
		width: '220px',
		height: '220px'
	});
}
function restoreHistoryImage() {
	$(this).stop().animate({
		left: '0px',
		top: '0px',
		width: '160px',
		height: '160px'
	});
}

function resizeHistory() {
	if ($('#history-container').length) {
		//hWindowWidth = $(window).width();
		hWindowWidth = $('#container').width();
		
		$('#history-wrapper').css({width: hWindowWidth+'px'});
		
		hContainerParentWidth = (hContainerWidth - hWindowWidth)*2 + hWindowWidth;
		$('#history-container-parent').css({width: hContainerParentWidth+'px', marginLeft: (hWindowWidth - hContainerWidth + hButtonWidth)+'px'});
	}
}


function initContacts() {
	if ($('#contacts-blocks').length > 0) {
		redrawMap();
		$('#contacts-links .contacts-link').click(clickContactsLink);
		if ($('#contacts-blocks #contacts-form .text-form').hasClass('text-form-opened')) {
			$('#contacts-links #mail-link').click();
		} else {
			$('#contacts-links #yandex-link').click();
		}
	contactsImage.src = $('#contacts-photo img').attr('src');
	}
}
var curContactLink, contactsTimeout;
function clickContactsLink() {
	if (!$(this).hasClass('cur-contacts-link')) {
		$('#contacts-links .contacts-link').removeClass('cur-contacts-link')
		curContactLink = $(this);
		$('#contacts-blocks .contacts-block').slideUp(700);
		clearTimeout(contactsTimeout);
		contactsTimeout = setTimeout(showContactBlock, 700);
	}
	return false;
}
function showContactBlock() {
	curContactLink.addClass('cur-contacts-link');
	$('#contacts-blocks '+curContactLink.attr('href')).slideDown(700, redrawMap);
}
function redrawMap() {
	if (map)
		map.redraw();
}
var contactsImage = new Image();
function resizeContacts() {
	if (contactsImage && contactsImage.height > 0) {
		var h = (contactsImage.height > 400)?contactsImage.height:400;
		$('#contacts-blocks').css({height: h});
		$('#ymap').css({height: h});
	}
}

var processPhotosWrapperWidth = [], processPhotosContainerWidth = [], processPhotosDuration = [], processBigPhotoWidth = 609, processSmallPhotoWidth = 320;
function initProcess() {
	if ($('#process-stages').length > 0) {
		$('#process-stages li').click(clickProcessStage);
		$('#process-stages li:first').click();
	}
	if ($('.process-photos').length > 0) {
		$('.process-photos .process-photos-arrow').hover(hoverProcessPhotosArrow, outProcessPhotosArrow);
		resizeProcess();
	}
}
function resizeProcess() {
	if ($('.process-photos').length > 0) {
		var i = 0;
		$('.process-photos').each(function() {
			var i = 0;
			if ($(this).parents('.process-stage-block').length > 0) {
				i = parseInt($(this).parents('.process-stage-block').attr('id').substr(19));
			}
			len = $(this).find('li').length;
			processPhotosWrapperWidth[i] = $(this).width();
			processPhotosContainerWidth[i] = len*((i == 0)?processBigPhotoWidth:processSmallPhotoWidth);
			processPhotosDuration[i] = len*700;
			
			checkProcessPhotosArrow($(this));
		});
	}
}

function clickProcessStage() {
	var id = $(this).attr('id');
	$('#process-stages li').removeClass('cur');
	$(this).addClass('cur');
	$('.process-stage-block').hide();
	var block = $('#'+id.replace('-item', '-block'));
	block.show();
	$('.process-photos ul', block).css({marginLeft: '0px'});
	checkProcessPhotosArrow($('.process-photos', block));

	onResize();
}

var hoverProcessPhotos;
function hoverProcessPhotosArrow() {
	var elem = $(this).parents('.process-photos');
	var i = 0;
	if (elem.parents('.process-stage-block').length > 0) {
		i = parseInt(elem.parents('.process-stage-block').attr('id').substr(19));
	}
	
	var ml = ($(this).hasClass('process-photos-arrow-prev'))?0:(processPhotosWrapperWidth[i] - processPhotosContainerWidth[i]);
	$('ul', elem).animate({marginLeft: ml+'px'}, {'duration': processPhotosDuration[i], 'easing': 'linear', 'complete': function() {
		checkProcessPhotosArrow($(this).parents('.process-photos'));
	}});
	hoverProcessPhotos = elem;
	setTimeout(checkProcessPhotosArrowHover, 200);
}
function outProcessPhotosArrow() {
	var elem = $(this).parents('.process-photos');
	$('ul', elem).stop();
	hoverProcessPhotos = '';
	checkProcessPhotosArrow(elem);
}
function checkProcessPhotosArrowHover() {
	if (hoverProcessPhotos) {
		checkProcessPhotosArrow(hoverProcessPhotos);
	}
}
function checkProcessPhotosArrow(elem) {
	var i = 0;
	if (elem.parents('.process-stage-block').length > 0) {
		i = parseInt(elem.parents('.process-stage-block').attr('id').substr(19));
	}
	var ml = parseInt($('ul', elem).css('marginLeft'));
	if (processPhotosWrapperWidth[i] >= processPhotosContainerWidth[i]) {
		$('.process-photos-arrow-prev', elem).hide();
		$('.process-photos-arrow-next', elem).hide();
	} else {
		if (ml >= 0) {
			$('.process-photos-arrow-prev', elem).hide();
			$('.process-photos-arrow-next', elem).show();
		} else if (ml <= (processPhotosWrapperWidth[i] - processPhotosContainerWidth[i])) {
			$('.process-photos-arrow-prev', elem).show();
			$('.process-photos-arrow-next', elem).hide();
		} else {
			$('.process-photos-arrow-prev', elem).show();
			$('.process-photos-arrow-next', elem).show();
		}
	}
}

var capsuleCoord = {
	1: [53, 2],
	2: [63, 47],
	3: [70, 124],
	4: [93, 449],
	5: [58, 170],
	6: [88, 290],
	7: [98, 476],
	8: [0, 490],
	9: [77, 290]
},
capsuleFadeDuration = 700,
capsuleMoveDuration = 2000,
capsuleLeftStart = 240,
capsuleAnimation = false,
capsuleChangeAnimation = false;
capsuleAssembled = true;
function initCapsule() {
	changeCapsule();
	$('#capsule-block').hover(startChangeCapsule, stopChangeCapsule);	
}
function startChangeCapsule() {
	if (!capsuleChangeAnimation) {
		capsuleChangeAnimation = true;
		changeCapsule();
	}
}
function changeCapsule() {
	if (!capsuleAnimation) {
		if (capsuleAssembled) disassembleCapsule();
		else assembleCapsule();
	}
}
function stopChangeCapsule() {
	capsuleChangeAnimation = false;
}
function disassembleCapsule() {
	if (!capsuleAnimation && capsuleAssembled) {
		capsuleAnimation = true;
		for (i in capsuleCoord) {
			$('#capsule-layer'+i).css({left: (capsuleLeftStart+capsuleCoord[i][0])+'px'}).show();
		}
		moveCapsuleLayers();
	}
}
function moveCapsuleLayers() {
	for (i in capsuleCoord) {
		if (i == 1) $('#capsule-layer'+i).animate({left: capsuleCoord[i][1]+'px'}, {duration: capsuleMoveDuration, complete: showCapsuleTooltips});
		else if (!$.browser.msie && (i == 4 || i == 7)) $('#capsule-layer'+i).animate({left: capsuleCoord[i][1]+'px', opacity: 1}, {duration: capsuleMoveDuration});
		else $('#capsule-layer'+i).animate({left: capsuleCoord[i][1]+'px'}, {duration: capsuleMoveDuration});
	}
}
function showCapsuleTooltips() {
	if ($.browser.msie) {
		$('.capsule-tooltip').show();
		finishDisassembleCapsule();
	} else {
		$('.capsule-tooltip').fadeIn(capsuleFadeDuration);
		setTimeout(finishDisassembleCapsule, capsuleFadeDuration+1);
	}
}
function finishDisassembleCapsule() {
	capsuleAssembled = false;
	capsuleAnimation = false;
	if (capsuleChangeAnimation) setTimeout(changeCapsule, 2000);
}
function assembleCapsule() {
	if (!capsuleAnimation && !capsuleAssembled) {
		capsuleAnimation = true;
		if ($.browser.msie) $('.capsule-tooltip').hide();
		else $('.capsule-tooltip').fadeOut(500);
		collectCapsuleLayers();
	}
}
function collectCapsuleLayers() {
	for (i in capsuleCoord) {
		if (i == 1) $('#capsule-layer'+i).animate({left: (capsuleLeftStart+capsuleCoord[i][0])+'px'}, {duration: capsuleMoveDuration, complete: finishAssembleCapsule});
		else if (!$.browser.msie && (i == 4 || i == 7)) $('#capsule-layer'+i).animate({left: (capsuleLeftStart+capsuleCoord[i][0])+'px', opacity: 0}, {duration: capsuleMoveDuration});
		else $('#capsule-layer'+i).animate({left: (capsuleLeftStart+capsuleCoord[i][0])+'px'}, {duration: capsuleMoveDuration});
	}
}
function finishAssembleCapsule() {
	if ($.browser.msie) {
		$('#capsule-layer4').hide();
		$('#capsule-layer7').hide();
	}
	capsuleAssembled = true;
	capsuleAnimation = false;
	if (capsuleChangeAnimation) setTimeout(changeCapsule, 1000);
}





var textImageBlockWidth, textImageControlIndex;
function initTextImageBlock() {
	if ($('.text-image-big-control').length > 0) {
		resizeTextImageBlock();
		$('.text-image-big-control li').click(clickTextImageControl);
		$('.text-image-big-control li:first').click();
	}
}
function clickTextImageControl() {
	$('.text-image-big-control li').removeClass('c');
	$(this).addClass('c');
	var i = $(this).index();
    textImageControlIndex = i;
	//$('.text-image-big-list ul').animate({marginLeft: '-'+(i*textImageBlockWidth)+'px'}, {duration: 600, easing: 'linear'});
	$('.text-image-big-list ul').fadeOut('normal', function(){
   		$('.text-image-big-list ul').css('margin-left', '-'+(i*textImageBlockWidth)+'px');
   		$('.text-image-big-list ul').fadeIn();
   });
}


function resizeTextImageBlock() {
	textImageBlockWidth = $('.text-image-big-block').width();
	$('.text-image-big-list li').css({width: (textImageBlockWidth)+'px'});
	len = $('.text-image-big-list li').length;
	len = len + 1; // fix for chrome with zoom out
	$('.text-image-big-list ul').css({width: (textImageBlockWidth*len)+'px'});
	
	var i = $('.text-image-big-control li.c').index();
	//if (i > -1) $('.text-image-big-list ul').animate({marginLeft: '-'+(i*textImageBlockWidth)+'px'}, {duration: 600, easing: 'linear'});
	if (i > -1) $('.text-image-big-list ul').css({marginLeft: '-'+(i*textImageBlockWidth)+'px'});
}


function initPressToggleLink() {
	if ($('.press-toggle-link').length) {
		$('.press-toggle-link').click(clickPressToggleLink);
	}
}
function clickPressToggleLink() {
	$(this).toggleClass('press-toggle-link-opened');
	$(this).prev('.press-toggle-text').slideToggle(600);
	return false;
}


function initPressForm() {
	inputHelper($('#press-form-name'), 'Имя');
	inputHelper($('#press-form-email'), 'Эл. почта');
	inputHelper($('#press-form-site'), 'Адрес сайта');
	inputHelper($('#press-form-phone'), 'Телефон');
	inputHelper($('#press-form-edition'), 'Издание');
	inputHelper($('#press-form-message'), 'Сообщение');
	inputHelper($('#press-form-region'), 'Регион и город');
	inputHelper($('#press-form-question'), 'Ваш вопрос');
	
	$('#press-contact-form.text-form-opened').slideDown();
	$('#press-contact-button').click(clickPressFormButton);

	initFeedbackForm();
}
function clickPressFormButton() {
	$('#press-contact-form').slideToggle();
	return false;
}

function initTextForm() {
	inputHelper($('#text-form-name'), 'Имя');
	inputHelper($('#text-form-email'), 'Эл. почта');
	inputHelper($('#text-form-message'), 'Сообщение');

	initFeedbackForm();
}

function initFeedbackForm() {
	$("#feedback_form")
		.bind ('submit', function () {
		        $('[title="Это поле должно быть заполнено"]').remove();
			var error = false;

			if ($('#press-form-name').length > 0) 
			{
				$("#p_title_div").removeClass("text-form-error");
				inputIn ($('#press-form-name'), 'Имя');
				if ($('#press-form-name').val() == "")
				{
					$("#p_title_div").addClass("text-form-error");
					$("#p_title_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
					error = true;
				}
			}

			if ($('#press-form-email').length > 0) 
			{
				$("#user_f_1_div").removeClass("text-form-error");
				inputIn ($('#press-form-email'), 'Эл. почта');
				if ($('#press-form-email').val() == "" || !isValidEmail($('#press-form-email').val()))
				{
					$("#user_f_1_div").addClass("text-form-error");
					$("#user_f_1_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
					error = true;
				}
			}

			if ($('#press-form-phone').length > 0)
			{
				$("#user_f_4_div").removeClass("text-form-error");
				inputIn ($('#press-form-phone'), 'Телефон');
				if ($('#press-form-phone').val() == "" || $('#press-form-phone').val().match(/[^0-9\-\(\)\s\+]+/ig))
				{
					$("#user_f_4_div").addClass("text-form-error");
					$("#user_f_4_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
					error = true;
				}
			}

			if ($('#press-form-edition').length > 0) inputIn ($('#press-form-edition'), 'Издание');
			if ($('#press-form-message').length > 0)
			{
				$("#user_f_3_div").removeClass("text-form-error");
				inputIn ($('#press-form-message'), 'Сообщение');
				if ($('#press-form-message').val() == "")
				{
					$("#user_f_3_div").addClass("text-form-error");
					$("#user_f_3_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
					error = true;
				}
			}

			if ($('#press-form-region').length > 0) inputIn ($('#press-form-region'), 'Регион и город');
			if ($('#press-form-question').length > 0)
			{
				$("#user_f_3_div").removeClass("text-form-error");
				inputIn ($('#press-form-question'), 'Ваш вопрос');
				if ($('#press-form-question').val() == "")
				{
					$("#user_f_3_div").addClass("text-form-error");
					$("#user_f_3_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
					error = true;
				}
			}

			$("#p_captcha_div").removeClass("text-form-error");
			if ($('#p_captcha').val() == "")
			{
				$("#p_captcha_div").addClass("text-form-error");
				$("#p_captcha_div").prepend('<i title="Это поле должно быть заполнено"></i>');
	
				error = true;
			}

			if (error) return false;

			inputIn ($('#press-form-site'), 'Адрес сайта');
		})
}

function inputIn(obj, text) {
	if ($(obj).val() == text) {
		if (text != 'http://') $(obj).val('');
		$(obj).removeClass('empty');
   }
}
function inputOut (obj, text) {
	if ($(obj).val() == '' || $(obj).val() == text) {
		$(obj).val(text).addClass('empty');
	}
}	
function inputHelper(obj, text) {
	$(obj)
		.bind ('focus', function () {
			inputIn (this, text);
		})
		.bind ('blur', function () {
			inputOut (this, text);
		});
	inputOut(obj, text);
}

function initSearch() {
	if ($('.search-more-button').length) {
		$('.search-more-button').click(loadNextSearchPage);
	}
}

function loadNextSearchPageHelper() {
	if ($('#search-results').length)
	{
		$('.search-more-button').first().remove();

		var html = $('#ajax-loader-helper').html();
		$('#ajax-loader-helper').html('');

		$('#search-results').html($('#search-results').html() + html);
	}

	$('.search-more-button').click(loadNextSearchPage);

	onResize();
}
function loadNextSearchPage() {
	var url = $('.search-more-button a').first().attr("href");

	$(this).unbind('click', loadNextSearchPage);
	$('.search-more-button').html('<img src="/img/ajax-loader.gif">');
	$('#ajax-loader-helper').load(url + ' #ajax-container', loadNextSearchPageHelper);
	
	return false;
}
function isValidEmail(str)
{
    var s = $.trim(str);
    var at = "@";
    var dot = ".";
    var lat = s.indexOf(at);
    var lstr = s.length;
    var ldot = s.indexOf(dot);

    if (s.indexOf(at)==-1 ||
       (s.indexOf(at)==-1 || s.indexOf(at)==0 || s.indexOf(at)==lstr) ||
       (s.indexOf(dot)==-1 || s.indexOf(dot)==0 || s.indexOf(dot)==lstr) ||
       (s.indexOf(at,(lat+1))!=-1) ||
       (s.substring(lat-1,lat)==dot || s.substring(lat+1,lat+2)==dot) ||
       (s.indexOf(dot,(lat+2))==-1) ||
       (s.indexOf(" ")!=-1))
    {
      return false;
    }

    return true;
}

var state = [false, false];
function overlayAllSites(e, block){
    if($('#all-sites').length > 0 || $('#all-sites-2').length > 0){
        
        elToShow = block == 1 ? '-2' : '';
        elState = block == 1 ? '1' : '0';
        
        if((!state[elState])){
        	if (!e) e = window.event.target;
	        $('#all-sites' + elToShow).show().css({
	            left: $(window).width()/2 - $('#all-sites' + elToShow).width()/2,
	            top: $(e).offset().top - $('#all-sites' + elToShow).height() - 25
	        });
	        state[elState] = !state[elState];
        } else {
        	$(".close" + elToShow + " a").trigger('click');
        }
        
        if(block == 1){
        	$(".close a").trigger('click');
        } else {
        	$(".close-2 a").trigger('click');
        }
        
        
    }
}

function overlayClose(e, block){
	
	elToShow = block == 1 ? '-2' : '';
	elState = block == 1 ? '1' : '0';
	
    $('#overlays' + elToShow + '>*').hide();
    state[elState] = false;
}

function initReqForm(){
    $('form.form input:text, form.form input:password, form.form textarea').each(function(){
        $(this).bind('focus', function(){
                if($(this).hasClass('required')){
                    $(this).removeClass('required').addClass('required-done');
                }
        }).bind('blur', function(){
            if($(this).val().length == 0){
                if($(this).hasClass('required-done')){
                    $(this).removeClass('required-done').addClass('required');
                }
            }
        });
    });
}

