
$(document).ready(function(){

	//$("#main").css('min-height', $(window).height()-260);

	var $link=$('nav a.current');
	$link.hide();
	var id=$link.attr('id');
	$link.attr('id',null);
	$link.after('<span class="a_currend_sp">&nbsp;</span>'
		+'<a href="'+$link.attr('href')+'" class="current_link" id="'+id+'">'+$link.text()+'</a>');

	if($link.attr('href')=='/')
		$(".a_currend_sp").addClass('navNoFirst');

//Опускаем footer на коротких страницах
window.correctFooter.correct();

$(window).resize(function() {
		location.reload();
});

//раскрытие новостей на главной
window.newsExpand.bindClicks('a.newsfull,a.newsarrow');

//Красивенький вид для больших картинок
$(".lightview").fancybox({
	hideOnContentClick:true
});


window.portmenu.setMenu();

//раздвигаем картинки в портфолио
if($(".portfoliofirst").length){
	//TODO
}





	/*Прокрутка галереи*/
	var show_in_time=4;//сколько картинок умещается на экране

	var $scroller = $("#gallery_scroller");
	if($scroller.length){
		var $range=$("#gallery_range");
		var img_cnt = $('img', $scroller).length;
		var w=$range.innerWidth();
		var img_w=213-1;//2-border. $('img:first', $scroller).outerWidth()+2;
		while(img_w * show_in_time>w)
			show_in_time-=1;
		img_w+=(show_in_time-1);//коррекция border-а

		if(show_in_time>1){//если больше - кина не будет!
			var img_margin=(w - (show_in_time*img_w))/(show_in_time-1);
			$('img', $scroller).each(function(){
				$(this).css('margin-right',img_margin);
				$(this).css('margin-left',0);
			});

			$scroller.css('width', img_cnt * (img_w+img_margin));
			window.galleryMove.scroller_zero=parseInt($scroller.position().left);
			window.galleryMove.img_cnt=img_cnt;
			window.galleryMove.image_step=img_w+img_margin;//приращение при скролле галереи
			//Крайнее левое положение (правая картинка видна)
			window.galleryMove.scroller_min=window.galleryMove.scroller_zero-(img_cnt*window.galleryMove.image_step) + (show_in_time*window.galleryMove.image_step)
			//Крайнее правое положение (левая картинка видна)
			window.galleryMove.scroller_max=window.galleryMove.scroller_zero;

			window.galleryMove.$scroller=$scroller;
			window.galleryMove.show_in_time=show_in_time;

			window.galleryMove.leftRange=window.galleryMove.show_in_time-window.galleryMove.img_cnt;
			window.galleryMove.rightRange=0;

			$("#gal_right").bind('click', function(){
				return false;
			});
			$("#gal_left").bind('click', function(){
				return false;
			});

			$("#gal_right").mousehold(500, function(i){
				window.galleryMove.reset();
				window.galleryMove.sliceShow(-1);
				window.galleryMove.mover(-1);
			});

			$("#gal_left").mousehold(500, function(i){
				window.galleryMove.reset();
				window.galleryMove.sliceShow(1);
				window.galleryMove.mover(1);
			});


			//скролл по mouseover-ам на активных зонах
			$("#scroll_gallery").bind('mouseover', function(e){
				//clearInterval(window.galleryMove.interval);
				window.galleryMove.reset();

				//влево
				if(e.pageX>$("#gallery_range").offset().left){
					window.galleryMove.mover(-1);
				}

				//вправо
				else if(e.pageX<$("#gallery_range").offset().left+$("#gallery_range").outerWidth()){
					window.galleryMove.mover(1);
				}
			});

			$("#scroll_gallery").bind('mouseout', function(){
				clearInterval(window.galleryMove.interval);
				window.galleryMove.reset();
			});
		}

		// clone image
		$('#gallery_scroller img').each(function(){
			window.galleryMove.toGrayscale(this);
		});

		//store size
		$('#full_gallery_img').css('width', $('#full_gallery_img').outerWidth());
		$('#full_gallery_img').css('height', $('#full_gallery_img').outerHeight());

		// Fade image
		$('#gallery_scroller img').click(function(e){
			window.galleryMove.smallHovered(this,e);
		})
	}

});


window.galleryMove = {
	current_step: 0,//текущий сдвиг (в количестве картинок)
	current_show: 0,//Текущая, отображаемая картинка
	image_step:0,//приращение при скролле
	img_cnt:0,//общее количество картинок
	scroller_current:0,//текущее положение div#gallery_scroller
	scroller_end:0,//Конечное положение div#gallery_scroller
	scroller_max:0,//Крайнее правое положение div#gallery_scroller
	scroller_min:0,//Крайнее левое положение div#gallery_scroller
	scroller_zero:0,//Положение div#gallery_scroller при старте (левая кртинка на 1-ом месте)
	$scroller:null,//DIV
	show_in_time:0,//Сколько картинок умещаются на экране
	leftRange:0,//на сколько картинок влево максимум (отрицательное число)
	rightRange:0,//на сколько картинок вправо максимум==0
	interval:null,//интервал для mouseover-скроллинга
	lock_inf_cycle:0,//блокировка скролла
	step_tab:{},

	gettab:function(i){
		i=Math.floor(i);
		if(i>=200) var res= window.galleryMove.step_tab[200];
		else if (i<=-200) res= window.galleryMove.step_tab[-200];
		else res= window.galleryMove.step_tab[i];
		return res;
	},

	filltab:function(){
		for (var j = -200; j <= 200; j++) {
			var sgn=j>0?1:-1;
			if(j==0) sgn=0;
			var abs=j*j/Math.abs(j);
			var step=sgn*Math.pow(abs, 0.333);
			if(step>window.galleryMove.image_step) step=1;
			if(Math.abs(step)<1) step = step / Math.abs(step);
			if(!step) step=-1;
			window.galleryMove.step_tab[j]=Math.round(step);
			//console.log(j," => ",window.galleryMove.step_tab[j]);
		}
	},

	mover: function(step){
		if(window.galleryMove.lock_inf_cycle) return;
		if(!window.galleryMove.step_tab.length) window.galleryMove.filltab();

		window.galleryMove.lock_inf_cycle=1;
		if(window.galleryMove.current_step+step==0){
			if(step>0) window.galleryMove.current_step=1;
			else if(step<0) window.galleryMove.current_step=-1;
		} else window.galleryMove.current_step+=step;

		if(window.galleryMove.current_step<window.galleryMove.leftRange)
			window.galleryMove.current_step=window.galleryMove.leftRange;
		else if (window.galleryMove.current_step>window.galleryMove.rightRange)
			window.galleryMove.current_step=window.galleryMove.rightRange;

		window.galleryMove.scroller_end=window.galleryMove.scroller_zero
		+ (window.galleryMove.image_step * window.galleryMove.current_step)

		window.galleryMove.moveDiv();
	},


	sliceShow:function(s){
		if(window.galleryMove.lock_inf_cycle) return;
		s=s*(-1);//Увы.
		var left_max=window.galleryMove.rightRange;
		var right_max=window.galleryMove.img_cnt-1;

		var step= window.galleryMove.current_show + s;
		if(step<left_max)	step=left_max;
		else if (step>right_max) step=right_max;
		$(".restoredcolour").each(function(e,i){
			window.galleryMove.toGrayscale($(this));
		});
		window.galleryMove.current_show=step;

		var $img=$('#gallery_scroller img').slice(step, step+1);
		window.galleryMove.restoreColor($img);
		window.galleryMove.loadBigSrc($img.attr('src'));
	},

	reset:function(){
	//Изменено направление.
	},

	moveDiv:function(){

		var step=window.galleryMove.gettab(window.galleryMove.scroller_end-window.galleryMove.scroller_current);
		var current=window.galleryMove.scroller_current+step;

		if(current<window.galleryMove.scroller_min || current>window.galleryMove.scroller_max){
			window.galleryMove.lock_inf_cycle=0;
			return ;
		}
		window.galleryMove.scroller_current=current;

		window.galleryMove.$scroller.css('left', window.galleryMove.scroller_current);

		if(window.galleryMove.scroller_current!=window.galleryMove.scroller_end)
			setTimeout(function(){
				window.galleryMove.moveDiv();
			},40);
		else window.galleryMove.lock_inf_cycle=0;
	},

	//загрузка и смена большой картинки
	loadBigSrc:function (imgSrc){
		var $img=$('#full_gallery_img');
		var $img2=window.galleryMove.hoversAddImage($img, 1)

		var imgSrc=imgSrc.replace(/thmb/gi, 'big');
		$img.attr('src', imgSrc);

		$img2.stop().animate({
			opacity:0
			}, 500,function(){
				$img2.remove();
		});

	},

	//эффект при убирании мыши - делает картинку черно-белой
	smallUnHovered:function(img){
		var $img=$(img);
		$img.unbind();
		var $img2=window.galleryMove.hoversAddImage($img,0);
		window.galleryMove.toGrayscale($img2);

		$img2.stop().animate({
			opacity:1
		}, 500);

		$img.stop().animate({
			opacity:0
			}, 500,function(){
				$img.unbind();
				$img.attr('src', $img2.attr('src')).css('opacity',1);
				$img2.remove();
				$img.mouseover(function(e){
					window.galleryMove.smallHovered(this,e);
				});
		});
	},

	//эффект при наведении мыши - делает картинку цветной
	smallHovered:function(img, e){
		var $img=$(img);
		$img.unbind();

		if(!window.galleryMove.lock_inf_cycle){
			if(e.pageX<$("body").innerWidth() / 2){
					window.galleryMove.mover(1);
			} else if(e.pageX>$("#gallery_range").innerWidth() / 2){
					window.galleryMove.mover(-1);
			}
		}

		$(".restoredcolour").each(function(){
			window.galleryMove.toGrayscale(this);
		});

		var $img2=window.galleryMove.hoversAddImage($img, 1);

		window.galleryMove.restoreColor($img);

		window.galleryMove.loadBigSrc($img.attr('src'));

		$img2.stop().animate({
			opacity:0
		}, 500,function(){
			$img2.unbind();
			$img2.remove();
//			$img.mouseout(function(e){
//				window.galleryMove.smallUnHovered(this,e);
//			});

			$img.click(function(e){
				window.galleryMove.smallHovered(this,e);
			});
		});

		//mouseout  когда анимация еще не закончена
//		$img2.mouseout(function(){
//			$img.stop();
//			$img2.stop();
//			$img.css('opacity',1);
//			$img2.unbind();
//			$img2.remove();
//			window.galleryMove.toGrayscale($img);
//			$img.mouseout(function(e){
//				window.galleryMove.smallUnHovered(this,e);
//			});
//			$img.mouseover(function(e){
//				window.galleryMove.smallHovered(this,e);
//			});
//		});
	},

	//накладывает absolute-картинку на исходную
	hoversAddImage: function($orig, opacity){
		opacity=parseFloat(opacity || 0);
		var $img2=$orig.clone()
		.css('position','absolute')
		.css('left',$orig.position().left)
		.css('top',$orig.position().top)
		.css('opacity',opacity)
		//.css('z-index',$img.css('z-index')+1)
		.insertAfter($orig);
		return $img2;
	},

	//делает img черно-белым
	toGrayscale:function(img){
		var $img=$(img);
		if(!$.hasData($img)){
			$img.data('color_source', $img.attr('src'));
			$img.data('grayscale_source', window.galleryMove.grayscale($img.attr('src')));
		}
		$img.attr('src',$img.data('grayscale_source'));
		$img.removeClass("restoredcolour");
	},

	//Восстанавливает цетную картинку для сделанной ранее ч/б
	restoreColor:function(img){
		var $img=$(img);
		$img.attr('src',$img.data('color_source'));
		$img.addClass("restoredcolour");
	},

	// Grayscale w canvas method. Original: webdesignerwall.com
	grayscale: function (src){
		try{
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			var imgObj = new Image();
			imgObj.src = src;
			canvas.width = imgObj.width;
			canvas.height = imgObj.height;
			ctx.drawImage(imgObj, 0, 0);
			var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
			for(var y = 0; y < imgPixels.height; y++){
				for(var x = 0; x < imgPixels.width; x++){
					var i = (y * 4) * imgPixels.width + x * 4;
					var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
					imgPixels.data[i] = avg;
					imgPixels.data[i + 1] = avg;
					imgPixels.data[i + 2] = avg;
				}
			}
			ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
			return canvas.toDataURL();
		} catch (e){
			return src;
		}
	}
}

//свертка / развертка новостей
window.newsExpand={
	blockSelector:'.news_article',
	announceBlock:'.news_announce',
	fullTextBlock:'.news_full_txt',
	eff_time:400,
	storedSelector:'',


	showFull:function($full,$announce){
		$full.css('position', 'absolute');
		var $b=window.newsExpand.getBothNewsBlocks($full);
		$(".newsarrow",$b[2]).toggleClass('newsarrowcurrent');
		$announce.stop().fadeIn(window.newsExpand.eff_time);
		$full.stop().fadeOut(window.newsExpand.eff_time, function(){
			$full.css('position', 'relative');
 		});
	},

	hideFull:function($full,$announce){
		$announce.css('position', 'absolute');
		var $b=window.newsExpand.getBothNewsBlocks($full);
		$(".newsarrow",$b[2]).toggleClass('newsarrowcurrent');
		$full.stop().fadeIn(window.newsExpand.eff_time);
		$announce.stop().fadeOut(window.newsExpand.eff_time, function(){
			$announce.css('position', 'relative');
		});
	},

	hideAllOther:function($current){
		$(window.newsExpand.storedSelector).each(function(){
			var blocks=window.newsExpand.getBothNewsBlocks(this);
			if($current.get(0)!=blocks[1].get(0))
				if(!$(":hidden", blocks[1]).length){
					blocks[0].css('position', 'relative');
					blocks[0].show();
					blocks[1].hide();
					$("a.newsarrow", blocks[2]).removeClass('newsarrowcurrent');
				}
		});
	},

	getBothNewsBlocks:function(elem){
			var $block = $(elem).parents(window.newsExpand.blockSelector);
			var $announce=$(window.newsExpand.announceBlock,$block);
			var $full = $(window.newsExpand.fullTextBlock,$block);
			return[$announce,$full,$block];
	},

	bindClicks:function(selector){
			window.newsExpand.storedSelector=selector;
			$(selector).bind('click', function(){

			var blocks=window.newsExpand.getBothNewsBlocks(this);
			//$("a.newsarrow", blocks[2]).removeClass('newsarrowcurrent');

			window.newsExpand.hideAllOther(blocks[1]);



			var flag=$(":hidden", blocks[1]).length;
			if(!flag){
				//$("a.newsarrow", blocks[2]).addClass('newsarrowcurrent');
				window.newsExpand.showFull(blocks[1], blocks[0]);
			} else {
				window.newsExpand.hideFull(blocks[1], blocks[0]);
			}
			return false;
		});

	}
}

//TODO
window.portmenu={

	hover:0,//мышь на подменю

	setMenu:function(){

		var p = $("#topmenu_portfolio").offset().left - $("#header").offset().left-6;

		$("#portmenu").css('left',(p+6));

		//Подменю для портфолио
		$("#topmenu_portfolio").bind('mouseover', {}, function(){
			window.portmenu.hover=1;
			$("#portmenu").show();
		});

		$("#portmenu").bind('mouseover', {}, function(){
			window.portmenu.hover=1;
		});

		$("#topmenu_portfolio").bind('mouseout', {}, function(){
			window.portmenu.hover=0;
			setTimeout(function(){
				if(window.portmenu.hover==0)
					$("#portmenu").hide();
			},300);
		});

		$("div#portmenu").bind('mouseout', {}, function(){
			window.portmenu.hover=0;
			setTimeout(function(){
				if(window.portmenu.hover==0)
					$("#portmenu").hide();
			},300);
		});
	}
}

window.correctFooter={
	winHeight:480,
	mainHeight:320,
	footerTop:720,
	correct:function(){
		this.winHeight=$(window).height();
		if(this.winHeight>800){
			this.mainHeight=$('#main').height();
			this.footerTop=$('footer').offset().top;
			if(this.footerTop<this.mainHeight)
				$('#footer').css('top', (this.mainHeight-this.footerTop)+'px');
		}
	}
}

