function see_and_hidde_byid(el){
	var temp=document.getElementById(el).style.display;
	if(temp=="none"){document.getElementById(el).style.display="block";}
	if(temp=="block"){document.getElementById(el).style.display="none";}
}

var consoleDebug = false;
var isiPad = navigator.userAgent.match(/iPad|iPhone/i) != null;
var W = $(window),
	content = null;
var gridStep = 126,
	gridsAtPage = 6;


//ЂдоваЯ формула когда-то написана мною длЯ вычислениЯ процента увеличениЯ изображениЯ длЯ вписываниЯ в некоторую область.
//‚ нашем случае эта область - весь экран
function getScale(e){

	var sw = W.width();
	var sh = W.height();
	var iw = $(e).width();
	var ih = $(e).height();

	//—то тут далее происходит непонимаю даже Я сам, это сильно свЮтрнутаЯ формула
	var hi = (sh / ih);
	var wi = (sw / iw);
	var ns = (sw > hi * iw) ? wi : hi;

	return sw > sh ? ih > iw ? wi : ns : ih < iw ? sw > wi * ih ? hi : wi : ns;
}
//---------------------------------------------------------------------------

$.fn.imageSetCenter = function(){

	var o = $(this);
	var w = o.width();
	var h = o.height();


	return o.css({marginLeft: -w/2, marginTop: -h/2});
}
//---------------------------------------------------------------------------

function setImage(obj){
	var t = obj? $(obj) : $(this),
		visible = t.parent().is(':visible');
	if(!visible) t.parent().show();
	
	if(t.length){
		var scale = getScale(t);

		var wh = t.width();
		t.width(wh * scale);
		wh = t.width();

		t.css({'height': 'auto'});
		var hh = t.height();

		var css = {};
		css.left = W.width() / 2 - wh / 2;
		css.top = W.height() / 2 - hh / 2;

		t.css(css);
	}
	if(!visible) t.parent().hide();
}
//---------------------------------------------------------------------------

$.fn.setImg = function(){
	setImage(this);
	return $(this);
}
//---------------------------------------------------------------------------

var scrollbarWidth = -1;
function getScrollbarWidth() {	// from: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php
	var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
	// Append our div, do our calculation and then remove it
	$('body').append(div);
	var w1 = $('div', div).width();
	div.css('overflow-y', 'scroll');
	var w2 = $('div', div).width();
	$(div).remove();
	return (w1 - w2);
}
//---------------------------------------------------------------------------

var content_resize = function(){
	var ws = $('#workslides').find('img');

	if(ws.length){
		ws.each(function(){
			$(this).setImg();
		});
	}

	var pr = $('.p-mask-right'),
		border = 55,
		wh = content.width() - (gridStep / 2) - border;
	if(pr.length){
		gridsAtPage = Math.floor((wh / gridStep));
		if(gridsAtPage > 1) gridsAtPage--;
		var l = wh % gridStep;
		l = wh - l + 17;
		pr.css({left: l});
		var w = wh - l;
		/*if(scrollbarWidth == -1) {
			scrollbarWidth = getScrollbarWidth();
		}*/
		var arrowsWidth = w + (gridStep / 2) + border - 20;
		pr.width(arrowsWidth);
		
		// Корректируем ширину прокрутки, дабы выровнять стрелки листалки (что справа) для крайней правой позиции
		var grid = $('.p-pline .p-grid'),
			item = grid.find('.p-o:last'),
			maxXpoint = item[0].offsetLeft + item.width(),
			gridWidth = maxXpoint + arrowsWidth - border + 6;
		grid.width(gridWidth);
	}
}
//---------------------------------------------------------------------------

$(window).load(function(){
	content_resize();	// Для хрома и оперы недостаточно выполнения данной функции в document.ready
})

$(window).ready(function(){
	content = $('.general-content-container');
	
	var obj = this,
		time = 1200,
		body = $('body'),
		popup = $('.p-popup'),
		slide = $('.p-slide'),
		workslides = $('#workslides');

	var pfly = $('.p-fly');
	var pclose = pfly.find('.p-close');

	// Енопки переключения между слайдами проекта и между проектами
	var nextclick = $('.p-nextproj').children('a'),
		btnPrevSlide = $('.p-pprev'),
		btnNextSlide = $('.p-pnext');
	
	
	var doSrcReplace = false;
	var imgSlide = workslides.find('.w:first'),
		imgUrlList = [],
		imgSlideIndx = 0,
		imgSlideList = workslides.find('.w').each(function(indx, slide)
	{
		var slide = $(slide);
		if(consoleDebug) console.log(slide.attr('img'));
		imgUrlList[ imgUrlList.length ] = slide.attr('img');
	});
	
	/**
	* При наведении / уходе мышки на кнопки "следующий / предыдущий  проект / слайд"
	*/
	this.onBtnChangeSlide_hover = function(e){
		var current = SLIDER.current(), t = $(this), tp = t.parent();
		var side = (current.is('.first') && tp.is('.p-pprev')) || (current.is('.last') && tp.is('.p-pnext'));
		if(side && e.type == 'mouseenter'){
			t.addClass('hover');
		} else {
			t.removeClass('hover');
		}
	}
	
	var imgNum = 1, numImgsToLoad = 2,
		nextImage = workslides.find('.w:first');
	function loadNext(){
		var parent = $(nextImage).hide();
		var x = new Image;

		if(consoleDebug) console.time('load img[' + imgNum + ']');
		numImgsToLoad--;
		$(x).attr('src', parent.attr('img')).load(function(){
			$(this).attr('loaded', 1);
			parent.append(this).find('img').setImg().show();
			if(consoleDebug) console.timeEnd('load img[' + (imgNum++) + ']');
			//btnNextSlide.show();
			//switchButtons(btnNextSlide.find('a'));
			if(numImgsToLoad) loadNext();	// загрузка следующего изображения
		}).click(function(event){
			var slideCur = SLIDER.current();
			if(event.clientX < (W.width() / 2)) {
				var a =  $('.p-pprev').children('a');
				if(!popup.is(':visible') && $('.p-pprev').is(':visible')) {
					if(slideCur.is('.first')) document.location = a[0].href;
					else a.click();
				}
			}
			else {
				var a =  $('.p-pnext').children('a');
				if(!popup.is(':visible') && $('.p-pnext').is(':visible')) {
					if(slideCur.is('.last')) document.location = a[0].href;
					else a.click();
				}
			}
		}).mousemove(function(event){
			var imgHolder = $(this).parent();
			if(event.clientX < (W.width() / 2)) {
				if(btnPrevSlide.is(':visible')) imgHolder.css({'cursor': 'pointer'});
				else imgHolder.css({'cursor': 'default'});
				btnNextSlide.removeClass('p-pnext-on');
				btnPrevSlide.addClass('p-pprev-on');
				btnPrevSlide.find('a:first').trigger('mouseenter');
				btnNextSlide.find('a:first').trigger('mouseleave');
			} else {
				if(btnNextSlide.is(':visible')) imgHolder.css({'cursor': 'pointer'});
				else imgHolder.css({'cursor': 'default'});
				btnPrevSlide.removeClass('p-pprev-on');
				btnNextSlide.addClass('p-pnext-on');
				btnPrevSlide.find('a:first').trigger('mouseleave');
				btnNextSlide.find('a:first').trigger('mouseenter');
			}
		});
		parent.removeAttr('img');
		nextImage = parent.next();
	}

	if(nextImage.size()) loadNext();
	workslides.find('.w:first').show();
	W.resize(content_resize);
	content_resize();
	//****************************************************

	var SLIDER = {currentSelector:'.current', firstSelector:'.first', lastSelector:'.last'};
	SLIDER.collection = workslides.children('.w');

	//****************************************************
	SLIDER.current = function(){ return SLIDER.collection.filter(SLIDER.currentSelector); }
	SLIDER.next = function(direct){ //true -- next(), false -- previous();
		var S = SLIDER.current();
		S = direct ? S.next() : S.prev();
		//if(!S.length){ return SLIDER.collection.filter(direct ? SLIDER.firstSelector : SLIDER.lastSelector); }
		return S;
	}
	//****************************************************

	
	// функция переклчюающая состояние видимость / режим кнопопок
	var switchButtons = function(current){
		var isNext = current.parent().is('.p-pnext');
		var nextnext = isNext ? SLIDER.current().next() : SLIDER.current().prev();
			if(!nextnext.length){
				if(!nextnext.prevObject.size()) {
					if(btnPrevSlide[0].getAttribute('isfirst')) btnPrevSlide.hide();
					if(btnNextSlide[0].getAttribute('islast')) btnNextSlide.hide();
				}
				else if( nextnext.prevObject.hasClass('first') && btnPrevSlide[0].getAttribute('isfirst') ) {
					btnPrevSlide.hide();
				}
				else if( nextnext.prevObject.hasClass('last') && btnNextSlide[0].getAttribute('islast') ) {
					btnNextSlide.hide();
				}
				else {
					current.addClass('hover');
				}
			}
			return false;
	}
	nextclick.each(function(indx, btn){
		var btn = $(btn);
		btn.parent().show();
		switchButtons(btn);
	});
	// Обработчик нажатия на кнопку
	var onNextBtnClick = function(t){
		if(!pfly.hasClass('p-person') && pfly.hasClass('p-show')){ pclose.click(); }

		var isNext = t.parent().is('.p-pnext');
		var current = SLIDER.current();
		var next = SLIDER.next(isNext);
		var ese = 'easeInOut';

		nextclick.removeClass('hover');
		$('.p-pprev').fadeIn();
		if(next.length){
			current.add(next).toggleClass(SLIDER.currentSelector.substr(1));
			switchButtons(t);
			if(isNext){
				if(doSrcReplace) {
					imgSlide.find('img:first').attr('src', imgUrlList[++imgSlideIndx]);
					btnPrevSlide.show();
					return false;
				}
				
				if(next.next().attr('img')) {
					numImgsToLoad = 1;
					loadNext();
				}
				if(isiPad) {
					current.hide().css({'left': parseInt(current.css('left')) - current.width() + 'px'});
					next.css({'left': 0 + 'px'}).show();
				} else {
					current.animate({left:-current.width()}, time, 'easeInOut', function(){
						$(this).hide();
					});
					next.show().css({left:next.width()}).animate({left:0}, time, 'easeInOut', function(){
						if($(this).find('img').attr('loaded')) {
							btnNextSlide.show();
							switchButtons(btnNextSlide.find('a:first'));
						}
					});
					//btnNextSlide.hide();
				}
			} else {
				if(doSrcReplace) {
					imgSlide.find('img:first').attr('src', imgUrlList[--imgSlideIndx]);
					return false;
				}
				
				if(isiPad) {
					current.hide().css({'left': parseInt(current.css('left')) + current.width() + 'px'});
					next.css({'left': 0 + 'px'}).show();
				} else {
					current.animate({left:current.width()}, time, 'easeInOut', function(){
						$(this).hide();
					});
					next.show().css({left:-next.width()}).animate({left:0}, time, 'easeInOut');
				}
				if(!btnNextSlide.is(':visible')) btnNextSlide.show();
			}
			return false;
		}
	}
	nextclick.find('.p-f').click(function(){
		document.location = $(this).parent()[0].href;
	})
	nextclick.click(function(){
		return onNextBtnClick($(this));
	}).bind('mouseenter mouseleave', this.onBtnChangeSlide_hover);
	
	
	//****************************************************

	/**
	* Листалка картинок, испольузется в Блоге
	*/
	$('.gallery-box').each(function(){
		var t = $(this);
		var prev = t.find(".gallery-prev");
		var next = t.find(".gallery-next");
		var stat = t.find(".gallery-stat");
		var img  = t.find(".gallery-img");
		var count = img.children('img').length;
		var time = 500;

		stat.text('1 / '+count);
		img.children().each(function(i){
			$(this).attr('rel',i+1);

		});

		img.find('img').hide().filter(":first").show();
		prev.add(img.children()).add(next).click(function(e){
			var current = img.find(':visible');
			var isNext = $(this).hasClass('gallery-next') || $(this).is('img');
			var Obj = isNext ? current.next() : current.prev();

			isNext = isNext ? ':first' : ':last';
			Obj = Obj.length ? Obj : img.find(isNext);
			current.hide();
			Obj.fadeIn(time);
			img.animate({height: Obj.height()}, time);
			/*
			Obj.animate({opacity: 1}, time, function(){
			current.add(this).toggleClass('current').removeAttr('style');
			});
			*/
			stat.text(Obj.attr('rel')+' / '+count);
			return false;
		});
		
		/**
		* корректировка изначальной (при загрузке страницы) высоты блока для картинки
		*/
		var imgCur = img.find('img:visible');
		var fitImgHeight = function(){
			var $this = $(this);
			if($this.is(':visible')) img.height( $this.height() );
		}
		if(imgCur.size()) fitImgHeight.apply(imgCur[0]);
		img.find('img').load(fitImgHeight);
	});
	//****************************************************


	var pp = $('.p-p');
	function checkPP(ns){
		var prevBtn = pp.filter('.p-prev'),
			nextBtn = pp.filter('.p-next'),
			duration = 200;
		if(ns == 0){
			if(prevBtn.is(':visible')) prevBtn.stop().fadeOut(duration);
			if(!nextBtn.is(':visible')) nextBtn.stop().fadeIn(duration, function(){
				nextBtn.css({opacity: 1});
			});
		} else {
			if(ns > slide[0].scrollWidth - $(window).width()){
				if(!prevBtn.is(':visible')) prevBtn.stop().fadeIn(duration, function(){
					prevBtn.css({opacity: 1});
				});
				if(nextBtn.is(':visible')) nextBtn.stop().fadeOut(duration);
			} else {
				if(!prevBtn.is(':visible')) {
					prevBtn.stop().fadeIn(duration, function(){
						prevBtn.css({opacity: 1});
					});
				}
				if(!nextBtn.is(':visible')) {
					nextBtn.stop().fadeIn(duration, function(){
						nextBtn.css({opacity: 1});
					});
				}
			}
		}
	}

	pp.click(function(e){
		var t = $(this),
			posTo = Math.round((slide.get(0).scrollLeft + (t.hasClass('p-next')? 1 : -1) * (slide.width())) / 189) * 189,
			maxTo = slide.get(0).scrollWidth - slide.width();
		if(posTo < 0) posTo = 0;
		if(posTo > maxTo) posTo = maxTo;
		slide.stop().scrollTo(posTo + 'px', {axis:'x', easing:'easeOut', duration: time, onAfter:function(){
			checkPP(posTo);
		}});
		return false;
	});
	//****************************************************

	var deltascroll = function(e,delta){
		e.preventDefault ? e.preventDefault() : (e.returnValue=false);
		var d = delta > 0 ? -190 : 190,
			posTo = this.scrollLeft + d,
			maxTo = slide.get(0).scrollWidth - slide.width();

		if(posTo < 0) posTo = 0;
		if(posTo > maxTo) posTo = maxTo;
		$(this).stop();
		this.scrollLeft = posTo;
		checkPP(posTo);
		return false;
	}
	slide.mousewheel(deltascroll);
	//****************************************************

	pfly.find('.p-close').click(function(){
		var t = $(this).parent();
		t.find('.p-box').slideToggle(400,function(){
			pfly.addClass('p-person').toggleClass('p-show').toggleClass('p-hide');
		});
		return false;
	}).end().find('.p-more-click').click(function(){
		$(this).next().toggle();
		return false;
	});

	if(slide.size()) {
		var projListGotoCurrent = true, projListLastPos = slide[0].scrollLeft,
			currentproject = $('.current-project');
		currentproject.click(function(){
			if(currentproject.hasClass('opened')){
				projListLastPos = slide[0].scrollLeft;
				if(isiPad) popup.hide();
				else popup.stop().fadeOut(time);
				currentproject.removeClass('opened');
			} else {
				if(isiPad) popup.show();
				else popup.stop().fadeIn(time);
				currentproject.addClass('opened');
				var posTo = projListGotoCurrent? slide.find('.current') : projListLastPos + 'px';
				// Прокручиваем ленту проектов до текущего проекта
				slide.stop().scrollTo(posTo, {axis:'x'});
				// отображать кнопки прокрутки?
				setTimeout(function(){
					checkPP(slide[0].scrollLeft);
				}, 100);
				projListGotoCurrent = false;
			}
			return false;
		});
	}
	/*************************************************/
	
	body.click(function(e){
		if(typeof(currentproject) != 'undefined' && currentproject.hasClass('opened') && e.clientY > 230){
			currentproject.click();
		};
	});
	/*************************************************/

	/**
	* Линейка проектов.
	* Обработчики её прокрутки кнопками и перетаскиванием, нажатия кнопки для перетаскивания и перехода, hover on ther image mask
	*/
	var ptStart = 0, iStart = 0, iEnd = 0,
		isClick = false,// canScroll = true,
		durtime = 500;
	var ppline = $('.p-pline');
	var pkd = 0, pkm = 0;
	
	function arrowVisibility() {
		var left = ppline.get(0).scrollLeft;
		if(left == 0) $('#m-prev').css({backgroundPosition: '0 0'}); //$('#m-prev').hide();
		else $('#m-prev').css({backgroundPosition: '0 100%'}); //$('#m-prev').show();
		
		var gridWidth = ppline.find('.p-grid').width(),
			maxLeft = gridWidth - ppline.width();
		if(left >= maxLeft) $('#m-next').css({backgroundPosition: '100% 0'}); //$('#m-next').hide();
		else $('#m-next').css({backgroundPosition: '100% 100%'}); //$('#m-next').show();
	}
	//-----------------------------------------------------------------------
	
	/**
	* финализируем действие перетягивания: дотягивание/выравнивание по сетке; установка флага перехода по ссылке, если был щелчек
	*/
	var fOnPplineMouseUp = function(){
		var t = ppline,
			ptEnd = t.get(0).scrollLeft,
			newx;
		if(ptEnd > ptStart) newx = Math.ceil(t.get(0).scrollLeft / gridStep) * gridStep;
		else newx = Math.floor(t.get(0).scrollLeft / gridStep) * gridStep;

		isClick = t.get(0).scrollLeft == ptStart;
		if(!isClick) {
			t.stop().scrollTo(newx, 0, {easing:'easeInOut', duration: durtime, onAfter: function(event){
				arrowVisibility();
			}});
		}
	};
	
	// Если присутствует лента проектов
	if(ppline.size()) {
		arrowVisibility();
		W.resize(arrowVisibility);
		W.resize(fOnPplineMouseUp);
	}
	
	// Начало действия / жеста - обработчик
	var f_StartDragging = function(obj, e){
		$(obj).data('md',e.clientX);
		ptStart = ppline.get(0).scrollLeft;
	};
	// Конец действия / жеста - обработчик
	var f_EndDragging = function(obj, e){
		e.preventDefault ? e.preventDefault() : (e.returnValue = false);
		
		var ne = Math.abs($(obj).data('md') - e.clientX);
		if(ne > 10){
		} else {
			//window.location.href = $(this).attr('href').split('#')[1];
		}
	};
	
	/**
	* обработчики срабатываемые на iPhone, iPad
	*/
	var touchMoveActionTimer = null;
	ppline.find('.p-grid').bind('touchstart', function(event) {
		iStart = event.touches[0].pageX;
		iEnd = 0;
		f_StartDragging(this, event);		
	}).bind('touchmove', function(event) {
		//iEnd = event.touches[0].pageX;
		
		//if(!touchMoveActionTimer) {
		if(iEnd != event.touches[0].pageX) {
			iEnd = event.touches[0].pageX;
			// чтобы слишком часто не срабатывал обработчик события
			/*touchMoveActionTimer = window.setTimeout(function(){
				touchMoveActionTimer = null;
			}, 100);*/
			// позиционирование линейки вслед за пальцем
			var dx = iEnd - iStart,
				newX = ptStart - dx;		
			ppline.get(0).scrollLeft = newX;
		}
		event.preventDefault();
	}).bind('touchend', function(event) {
		fOnPplineMouseUp();
	});
	/*
	$(window).bind('touchmove', function(event) {
		event.preventDefault ? event.preventDefault() : (event.returnValue=false);
	});
	*/
	ppline.find('.p-grid').mousewheel(function (e, delta){
		e.preventDefault ? e.preventDefault() : (e.returnValue=false);
		var d = delta < 0 ? -1 : 1;
		var newx = Math.round((ppline.get(0).scrollLeft + d * -gridStep*2) / gridStep) * gridStep;

		if(newx < 0) newx = 0;
		ppline.stop().scrollTo(newx, 0, {easing:'easeInOut', duration: durtime, onAfter: function(event){
			arrowVisibility();
		}});
		return false;
	}).mouseup(function(e){
		f_EndDragging(this, e);
		fOnPplineMouseUp();
	}).hover(function(){}, function(event){
		fOnPplineMouseUp();
	}).mousedown(function(e){
		if(!isiPad) f_StartDragging(this, e);
	});	
	ppline.scrollview();
	
	
	var areaHovered = null;
	ppline.find('.p-grid').find('.p-o').each(function(){
		var po = $(this);
		po.css({'z-index': 800});
				
		$(this).click(function(e){
			if(!isClick) e.preventDefault ? e.preventDefault() : (e.returnValue = false);
		});
		
		var area = $(this).find('area');
		po.bind('mouseenter', function() {
			po.css({'cursor': 'pointer'});
			if(area == areaHovered) po.css({'z-index': 800});
			else po.css({'z-index': 600});
		});
		area.bind('mouseenter', function() {
			areaHovered = area;
		});
		area.bind('mouseleave', function() {
			areaHovered = null;
			po.css({'z-index': 650, 'cursor': 'move'});
		});
		po.bind('mouseleave', function() {
			po.css({'z-index': 700});
		});
	});

	$('.m-p').click(function(){
		var t = ppline;
		var d = this.id == 'm-prev' ? 1 : -1;
		var newx = Math.round((t.get(0).scrollLeft + d * -gridStep * gridsAtPage) / gridStep) * gridStep;
		
		if(newx < 0) newx = 0;
		t.stop().scrollTo(newx, 0, {easing:'easeInOut', duration: durtime * 1.5, onAfter: function(event){
			arrowVisibility();
		}});
		return false;
	});
});
	$(document).keydown(function(event) {
		if (event.which == '37') {
			if($("#p-pprev").parent().css("display") == "none")
			{
				
			} else {
				if($("#p-pprev .p-f").css("display") == "table") {
					$("#p-pprev .p-f").trigger('click');
				}
				$("#p-pprev").trigger('click');
			}
			$("#m-prev").trigger('click');
		}
		if (event.which == '39') {
			if($("#p-pnext").parent().css("display") == "none")
			{
				
			} else {
				if($("#p-pnext .p-f").css("display") == "table") {
					$("#p-pnext .p-f").trigger('click');
				}
				$("#p-pnext").trigger('click');
			}
			$("#m-next").trigger('click');
		}
	});
