$(document).ready(function(){

	var trig = 1;
	var filt_kind = 0; //фильтр по сфере деятельности или виду новости, 0 - показать все
	var filt_date = 0; //фильтр по году, 0 - показать все
	var maintapenewPos = 0;
	var CurSearchStr = '';
	var FromSearchFl = false;
	var no_scroll_fl = false;
	var no_scroll = false;
	var after_newSection_fl;
	var scrollAS;
	var eas = "easeInOutQuint";					
	
	$(window).hashchange( function() {
		if (location.pathname != '/')
			location.href = '/'+location.hash;
		else
			GoToPage(location.hash);
	});
	if (location.pathname != '/404.php')
		$(window).hashchange();
	
	function SetHash(a) {
		var code = a.attr('code');
		if (!code)
			code = a.attr('id'); 
		location.hash = $('#nav li a.active').attr('id').substr(2) + '/' + code;
	}

	function GoToPage(path) {
		path = path.substr(1);
		if (path) {
			var path_parts = path.split('/');
			no_scroll = no_scroll_fl;
			no_scroll_fl = false;
			var a = $('#nav li a.active');
			if (a.length)
				var code = a.attr('id').substr(2);
			else
				var code = 'none';
			if (path_parts[0] == code) {
				after_newSection_fl = false;
				newPage(path_parts[1], path_parts[2]);
			}
			else
				newSection($('#nav li a#a_' + path_parts[0]), path_parts[1], path_parts[2]);
		}
		else
			newSection($('.logo a'));
	}

	function newSection(newActive, id, empl) {
		$('#main').fadeOut(300);
		var predActive = $('#nav li a.active, .logo a.active');
		var pAfl = (predActive.length > 0);
		if (pAfl) {
			predActive.removeClass('active');
			pHref = predActive.attr('href');
			predActive.children('.corner').animate({top:'14px'}, 200);
		}
		else
			pHref = 'none';
		nHref = newActive.attr('href');
		newActive.children('.corner').animate({top:'20px'}, 200);
		newActive.addClass('active');		
		if (pHref != nHref) {
			if (pAfl)
				predActive.parent().find('.switcher').fadeOut(300, function(){
					$(this).css({'left':'-9999px'}).show();
				});
			filt_date = 0;
			filt_kind = 0;
		}
		$('.main-holder').css({
			'background-image': $('#main').css('background-image'),
			'background-color': $('#main').css('background-color')
		});
		var code = newActive.attr('id');
		if (code) {
			code = code.substr(2);
			document.title = 'CUSTIS. ' + newActive.children('span').text();
			var url = 'custom.php?code=' + code + '&fk=' + filt_kind + '&fd=' + filt_date;
			if (code == 'news' || code == 'projects') //для новостей и проектов мотаем вверх
				$(window).scrollTo(0, 0);
			else //для остальных показываем агрегирующую стр.
				$(window).scrollTo(450, 0);
			$('#footer').hide();
		}
		else {
			document.title = 'CUSTIS. Главная страница';
			var url = 'first.php';
			$('#footer').fadeIn(700);
		}
		$('.main-holder').load(url, function() {
			maintapenewPos = 0;
			$('.btn-prev-content-holder, .btn-next-content-holder').width(($('#main').width()-912)/2);
			var Switcher = newActive.parent().find('.switcher');
			if (Switcher.length) {
				Switcher.html('');
				$('.tape li').each(function(){
					Switcher.append('<em><span>&nbsp;</span></em>');
				});
				Switcher.hide().css({'left':0}).fadeIn(300);
			}
			//CUSTISSUP-1 переходы от раздела к разделу без анимации
			/*$('#main').css('right', -$(window).width() + 'px');
			$('#main').animate({'right':0}, 700, eas, function(){
				if (code)
					newPage(id, empl);
			});*/
			$('#main').css('right', '0');
			if (code) {
				after_newSection_fl = true;
				newPage(id, empl);
			}
		});
	}

	function newPage(id, empl) {
		if (id) {
			var a = $('.tape li .more#' + id);
			if (!a.length)
				a = $('.tape li .more[code="' + id + '"]');
		}
		else
			var a = $('.tape li:first .more');
		if (a.length) {
			var li = a.parent().parent();
			var code = $('#nav li a.active').attr('id').substr(2);
			if (!li.is('.active')) {
				var lis = li.siblings('li');
				var islicur = li.is('.current');
				var aCurSection = $('#nav li a.active');
				lis.removeClass('active').removeClass('current').find('.more').stop().animate({'padding-top':'0'}, 300).find('.loader').hide();
				li.addClass('active').addClass('current');
				aCurSection.parent().find('.switcher em span').hide();
				aCurSection.parent().find('.switcher em:eq(' + li.index() + ') span').show();
				a.css({'padding-top':0});
				$('.tape li .more .loader').hide();
				if (after_newSection_fl) {
					scrollAS = 0;
					if (code == 'news' || code == 'projects') //немного места под фильтры
					{
						if (!no_scroll)
							$(window).scrollTo(471, 0);
					}
					else
						$(window).scrollTo(450, 0);
				}
				else {
					var st = document.documentElement.scrollTop || document.body.scrollTop;
					if (code == 'news' || code == 'projects') //немного места под фильтры
						var pos = 431;
					else
						var pos = 410;
					if (st > pos) {
						scrollAS = pos + 40;
						$(window).scrollTo(pos, 0);
					}
					else
						scrollAS = 0;
				}
				$('#main').css({'min-height': $('#main').height()});
				$('#content-container, #footer').stop().hide();
				if (!islicur)
					scrollTape(li.index(), a, id, empl);
				else
					newPageAS(a, id, empl);
			}
			else
				CheckEmpl(id, empl);
		}
	}
	
	function newPageAS(a, id, empl) {
		var li = a.parent().parent();
		var code = $('#nav li a.active').attr('id').substr(2);
		var aid = a.attr('id');
		var loader = a.find('.loader');
		var lis = li.siblings('li');
		var indexNext = li.index();
		if (li.is('.active')) {
			a.stop().animate({'padding-top':'60px'}, 300);
			loader.show();
			if (scrollAS)
				$(window).scrollTo(scrollAS, 500);
			//========================== Загрузка детального описания ==============================
			$('#content-container').load('page.php?id=' + aid + '&code=' + code, function() {
				loader.hide();
				if (li.is('.active')) {
					$('#content-container .container').attr('id', code);
					$('#content-container span.number').attr('id', code).text(nf2(indexNext));
					$('#content-container .heading h2').html($('#content-container #el_name').html());
					if (printversion)
						$('#content-container .content-holder > .container').append('<a class="to-print" href="' + printversion + '">версия для печати</a>');
					var kc = $('#content-container #el_kc').text();
					$('#content-container .news-holder .visual').attr('class', 'visual-' + kc).html('<img src="/images/kind_' + kc + '.jpg" />');
					if (FromSearchFl) {
						FromSearchFl = false;
						$('#content-container .container').highlight(CurSearchStr);
					}
					document.title = newttl;
					$('#footer').css('opacity', 1).fadeIn(700);
					$('#content-container').css('opacity', 1).fadeIn(700, function(){
						$('#main').css({'min-height': $(window).height()-231});
						if (li.is('.active')) {
							if (code == 'projects')
								EmplH();
							CheckEmpl(id, empl);
						}
						var map_cont = document.getElementById("map-container");
						if (map_cont) {
							var map = new YMaps.Map(map_cont);
							map.setCenter(new YMaps.GeoPoint(37.592844,55.778909), 15);
							map.addControl(new YMaps.TypeControl());
							map.addControl(new YMaps.ToolBar());
							map.addControl(new YMaps.Zoom());
							map.addControl(new YMaps.MiniMap());
							map.addControl(new YMaps.ScaleLine());
							var point = new YMaps.GeoPoint(37.590677,55.780583);
							var s = new YMaps.Style();
							s.iconStyle = new YMaps.IconStyle();
							s.iconStyle.href = "/images/map_icon.png";
							s.iconStyle.size = new YMaps.Point(128, 50);
							s.iconStyle.offset = new YMaps.Point(-128, -25);
							var pm = new YMaps.Placemark(point, {style: s});
							pm.name = 'CUSTIS';
							pm.description = '127055, Москва,<br/>ул. Лесная, д. 43,<br/>6-й этаж';
							map.addOverlay(pm);
						}
					});
					//CUSTISSUP-1 убрать анимацию вида "П"
					//$(window).scrollTo(pos, 400);
				}
			});
		}
	}
	
	function CheckEmpl(id, empl) {
		if (empl) {
			if (id == 'command' || id == 'people') {
				if (id == 'command')
					var comm = '1';
				else
					var comm = '0';
				$('.peoples-popup .peoples-popup-content').empty().load('/people_detail.php?id=' + empl + '&comm=' + comm);
				$('.overlay').show();
				$('.peoples-popup .close-btn').attr('href', '#' + $('#nav li a.active').attr('id').substr(2) + '/' + id);
				$('.peoples-popup').css({"left":'50%', "top":'30%', 'position': 'fixed'}).show();
				$('.overlay').bind('mousedown', function() {
					location.hash = $('.peoples-popup .close-btn').attr('href');
				});
			}
			else if (id == 'vendor-tech')
				$('#vendor-tech li a#' + empl).click();
			else if (id == 'custis-tech')
				$('#custis-tech li a#' + empl).click();
		}
		else {
			if (id == 'custis-tech')
				$('#custis-tech li a:first').click();
			else if (id == 'vendor-tech')
				$('#vendor-tech li a:first').click();
			$('.peoples-popup').hide();
			$('.overlay').hide();
			$('.overlay').unbind('mousedown');
		}
	}

	//======================= Начальные установки ==========================
	$('#nav li').each(function(){
		$(this).css('margin-left', $('body').width()/50);
		$(this).children('.switcher').css('max-width', ($(this).width()-2) + 'px');
	});
	$('.btn-prev-content-holder, .btn-next-content-holder').width(($('#main').width()-912)/2);
	$(window).resize(function(){
		$('.btn-prev-content-holder, .btn-next-content-holder').width(($('#main').width()-912)/2);
		$('#nav li').each(function(){
			$(this).css('margin-left', $('body').width()/50);
		});
	});
	$('#main').css({'min-height': $(window).height()-231});
	
	//============================= Утилиты ================================
	//число в двухсимвольныю строку
	function nf2(index) {
		index++;
		if (index < 10)
			return '0' + index;
		else
			return index;
	}
	//выравнивание высоты блока сотрудника
	function EmplH() {
		var maxh = 0;
		$('#team-gallery .holder ul li').each(function() {
			var h = $(this).height();
			if (h > maxh)
				maxh = h;
		});
		$('#team-gallery .holder').height(maxh);
	}
	//=========================== Анимации =================================
	$('#nav li a').live('mouseenter', function(){
		if ($(this).hasClass('active')) {
			return false;
		}
		$(this).find('.corner').stop().animate({top:'20px'}, 200);
	});
	$('#nav li a').live('mouseleave', function(){
		if ($(this).hasClass('active')){
			return false;
		}
		$(this).find('.corner').stop().animate({top:'14px'}, 200);
	});
	$('.btn-prev-top-holder, .btn-prev-content-holder, .btn-prev').live('mousemove', function(e){
		$('.btn-prev').stop().css('top', e.pageY - 27);
	});
	$('.btn-next-top-holder, .btn-next-content-holder, .btn-next').live('mousemove', function(e){
		$('.btn-next').stop().css('top', e.pageY - 27);
	});
	$('.btn-prev-top-holder, .btn-prev-content-holder, .btn-next-top-holder, .btn-next-content-holder, .btn-prev, .btn-next').live('mouseleave', function(){
		$('.btn-prev, .btn-next').stop().animate({top:'325px'}, 400)
	});
	
	//======================= Кнопки "Вперед" "Назад" =====================
	$('.btn-next').live('click', function(){
		//главная страница
		if ($('#main').hasClass('first-page')){
			var maintapeWidth = $('.main-tape li').size()*$('.main-tape li').outerWidth();
			var maintapeItemWidth = $('.main-tape li').outerWidth();
			var maintapeHolderWidth = $('.main-tape-holder').outerWidth();
			$('.main-tape').stop().css({'left':maintapenewPos + 'px'});
			maintapenewPos = parseInt($('.main-tape').css('left'))-maintapeItemWidth;
			if(maintapenewPos <= -maintapeWidth + maintapeHolderWidth-24){
				maintapenewPos = -maintapeWidth + maintapeHolderWidth-24;
			}
			if(parseInt($('.main-tape').css('left'))-maintapeItemWidth <= -maintapeWidth + maintapeHolderWidth-24){
				$('.main-tape').animate({'left':-maintapeWidth + maintapeHolderWidth-24-50+'px'}, 400, eas, function(){
					$('.main-tape').animate({'left':-maintapeWidth + maintapeHolderWidth-24+'px'}, 400, eas)
				});
			}else{
				$('.main-tape').animate({'left':'-='+maintapeItemWidth+'px'}, 800, eas);
			}
			return false;
		}//страницы
		if(parseInt($('.btn-next').css('top'))>530){
			if($('.tape li.active').index() == $('.tape li').size()-1){
				return false;
			}
			SetHash($('.tape li.active').next().find('.more'));
			return false;
		}//превью страниц
		else{
			scrollTape($('.tape li.current').index() + 1);
			return false;
		}
	});
	$('.btn-prev').live('click', function(){
		//главная страница
		if ($('#main').hasClass('first-page')){
			var maintapeWidth = $('.main-tape li').size()*$('.main-tape li').outerWidth();
			var maintapeItemWidth = $('.main-tape li').outerWidth();
			var maintapeHolderWidth = $('.main-tape-holder').outerWidth();
			$('.main-tape').stop().css({'left':maintapenewPos + 'px'});
			maintapenewPos = parseInt($('.main-tape').css('left'))+maintapeItemWidth;
			if(maintapenewPos >= 0){
				maintapenewPos = 0;
			}
			if(parseInt($('.main-tape').css('left'))+maintapeItemWidth >= 0){
				$('.main-tape').animate({'left':0+50+'px'}, 400, eas, function(){
					$('.main-tape').animate({'left':0}, 400, eas)
				});
			}else{
				$('.main-tape').animate({'left':'+='+maintapeItemWidth+'px'}, 800, eas);
			}
			return false;
		}//страницы
		if (parseInt($('.btn-prev').css('top')) > 530) {
			if($('.tape li.active').index() == 0){
				return false;
			}
			SetHash($('.tape li.active').prev().find('.more'));
			return false;
		}//превью страниц
		else {
			scrollTape($('.tape li.current').index() - 1);
			return false;
		}
	});
	//=============================== К детальному с превью ==============================
	$('.tape li .holder .visual').live('click', function(){
		$(this).parents('li').find('.more').click();
	});
	$('.tape li .holder .title').live('click', function(){
		$(this).parents('li').find('.more').click();
	});
	$('.tape li .more').live('click', function(){
		no_scroll_fl = true;
		SetHash($(this));
		return false;
	});	
	//========================== Клик на сотруднике =========================
	$('.peoples-box .peoples-list li').live('click', function(){
		if($(this).hasClass('disabled'))
			return false;
		var id = $(this).attr("id");
		if ($(this).parent().is('.command'))
			location.hash = 'about/command/' + id;
		else
			location.hash = 'secret/people/' + id;
	});
	//========================== Скрол ==============================
	function scrollTape(ind, a, id, empl){
		var tape = $('.tape');
		var cnt = tape.find('li').size();
		tape.stop();
		if (ind >= cnt) {
			tape.animate({'left': (-312*(cnt - 1) - 50) + 'px'}, 400, function(){
				tape.animate({'left': (-312*(cnt - 1)) + 'px'}, 400)
			});
		}
		else if (ind < 0) {
			tape.animate({'left':'50px'}, 400, function(){
				tape.animate({'left':'0'}, 400);
			});
		}
		else {
			$('.tape li.current').removeClass('current');
			$('.tape li:eq(' + ind + ')').addClass('current');
			$('.tape li.active .more').stop().animate({'padding-top':'0'}, 300);
			tape.animate({'left': (-312*ind) + 'px'}, 800, eas, function(){
				if ($('.tape li.current').hasClass('active'))
					$('.tape li.active .more').stop().animate({'padding-top':'60px'}, 300);
				if (a)
					newPageAS(a, id, empl);
			});
		}
		return false;
	}
	//============== Ссылка на раздел в главном меню ==========================
	$('#nav li a').click(function(){
		var id = $(this).attr('id');
		if (id == 'a_news' || id == 'a_projects')
			no_scroll_fl = true;
		location.hash = $(this).attr('rel');
		return false;
	});
	//============== Ссылка на раздел на блоках главной страницы ==============
	$('.section-link').live('click', function(){
		location.hash = $('#nav li a#a_'+$(this).attr('id')).attr('href');
		return false;
	});
	//========================= Навигация клавишами ===========================
	$('*').bind('keydown', function(e) {
		if (input_focus == 0) {
			if (e.which==37){
				if($('#main').hasClass('first-page')){
					$('.btn-prev').click();
					return false;
				}else{
					if($('.tape li.active').is(':first-child')){
						return false;
					}
					$('.tape li.active').prev().find('.more').click();
					return false;
				}
			}
			if (e.which==39){
				if($('#main').hasClass('first-page')){
					$('.btn-next').click();
					return false;
				}else{
					if($('.tape li.active').is(':last-child')){
						return false;
					}
					$('.tape li.active').next().find('.more').click();
					return false;
				}
			}
		} else {
			if (e.which==13){
				$('.search-footer-box .btn-search-go').click();
				return false;
			}
		}
	});
	//============== ссылка "Наверх" ====================
	$('.top-page a').live('click', function(){
		$.scrollTo(0, 400);
		return false;
	})
	//========================= Фильтры ===============================
	$('.filters a').live('click', function(){
		$('.overlay').show();
		$('.filter-drop').hide().addClass('filter-drop-open').slideDown(300);
		return false;
	});
	$('.filter-drop .close, .overlay').live('click', function(){
		$('.filter-drop').slideUp(300, function(){
			$(this).removeClass('filter-drop-open').show();
			$('.overlay').hide();
		});
		return false;
	});
	$('.kind-col li a').live('click', function() {
		$('.filter-drop').slideUp(200);
		filt_kind = $(this).attr('id');
		newSection($('#nav li a.active'));
		return false;
	});
	$('#content .heading .bottom-box a, .holder .bottom-box a').live('click', function() {
		$('.filter-drop').slideUp(200);
		filt_date = 0;
		filt_kind = $(this).attr('id');
		newSection($('#nav li a.active'));
		return false;
	});
	$('.date-col li a').live('click', function() {
		$('.filter-drop').slideUp(200);
		filt_date = $(this).attr('id');
		newSection($('#nav li a.active'));
		return false;
	});
	$('.back-to-all').live('click', function() {
		$('.filter-drop').slideUp(200);
		filt_date = 0;
		filt_kind = 0;
		newSection($('#nav li a.active'));
		return false;
	});
	//================== Переход на страницы с поиска ================
	$('.search-result a').live('click', function() {
		$('#footer .search-footer-box .close-holder a').click();
		FromSearchFl = true;
		location.hash = $(this).attr('href');
		return false;
	});
	//============== Переход на страницы с других страниц ================
	$('#content .container a').live('click', function() {
		if ($(this).attr('href') == '#')
			return false;
	});
	//============================= Поиск ===========================
	$('#footer .btn-search').click(function(){
		$('#footer .search-footer-box').slideDown(500);
		return false;
	});
	$('#footer .search-footer-box .close-holder a').click(function(){
		$('#footer .search-footer-box').slideUp(500);
		$('.search-result').css({'right':'9999px'});
		return false;
	});

	$('.search-footer-box .btn-search-go').click(function(){
		var str = $('.search-footer-box .text input').val();
		CurSearchStr = str;
		if (str)
			$.ajax({
				url: "/search.php",
				type: "POST",
				data: 'str=' + str,
				dataType:'html',
				success : function(html){
					$('.search-result .scrollable').html(html);
					$('.search-result').css({"right":'257px'});
				}
			});
		return false;
	});
	var input_focus = 0;
	$('.search-footer-box .text input').focus(function(){
		input_focus = 1;
	})
	.blur(function(){
		input_focus = 0;
	});
	
	jQuery.fn.highlight = function (str) {
		var regex = new RegExp(str, "gi");
		return this.each(function () {
		    var a = $(this);
		    a.html(a.html().replace(regex,
				function (matched) {
				    return '<font class="ss">' + matched + '</font>';
				}));
		});
	};
	
	$('.secret-ingr ul li').live('click', function() {
		location.href = $(this).find('a').attr('href');
	});

});

