$(document).ready(function(){
	C.init();
});
$(window).bind('scroll resize',function(evt){
	C.books.wideReset(evt);
	C.technics.wideReset(evt);
})

var C={
	animation: {
		time: 500,
		process: false
	},

	init: function(){
		C.books.init();
		C.technics.init();
	},

	books: {
		widebox_min: 767,
		widebox_bg: 952,
		widebox_top: 70,
		widepages: {},
		path_infos: {},
		current_book: null,
		scroll_bak: [],

		init: function(){
			C.books.smls();
			C.books.wide();
		},
	
		currentBookIsFirst: function(){
			for(var i in C.books.widepages){
				if(i==C.books.current_book){
					return true;
				}else{
					return false;
				}
			}
		},

		currentBookIsLast: function(){
			var i;
			for(i in C.books.widepages){}
			if(i==C.books.current_book){
				return true;
			}else{
				return false;
			}
		},
		
		changeCurrentBook: function(direction){
			var current_book_index;
			var current=0;
			var indexes=[];
			for(var i in C.books.widepages){
				indexes.push(i);
				if(i==C.books.current_book){
					current_book_index=current;
				}
				current++;
			}
			C.books.current_book=indexes[current_book_index+direction];
		},

		smls: function(){
			var $book_box=$('#bookBox');
			if($book_box.length){
				var $sml_box=$book_box.find('div.sml');
				var $thmb_box=$book_box.find('div.thumbnails');
				//меняем <b> на <a class="active">
				var $active_th=$thmb_box.find('b');
				if($active_th.length){
					var $img=$active_th.children();
					$active_th.parent().empty().
						append($(document.createElement('a')).attr({href:'#'}).addClass('active').
							append($img));
				}
				//пробегаем по ссылкам и добавляем им обработчики
				if($sml_box.length && $sml_box.children().length && $thmb_box.length && $thmb_box.children().length){
					$thmb_box.children().each(function(i){
						var $a=$(this).find('a');
						if($a.length){
							$a.bind('click',function(evt){
								evt.preventDefault();
								C.books.smlsToggle(i);
							})
						}
					})
				}
			}
		},

		smlsToggle: function(new_i){
			var $book_box=$('#bookBox');
			var $sml_box=$book_box.find('div.sml');
			var $thmb_box=$book_box.find('div.thumbnails');
			var old_i=null;
			for(var i=0; i<$sml_box.children().length; i++){
				if($sml_box.children().eq(i)[0].offsetHeight>0){
					old_i=i;
					break;
				}
			}
			if(typeof old_i=='undefined' || new_i==old_i){return false;}
			$thmb_box.children().eq(old_i).children('a').removeClass('active');
			$thmb_box.children().eq(new_i).children('a').addClass('active');
			$sml_box.children().eq(new_i).css({opacity: 0, display: 'block'}).animate({opacity:1},C.animation.time);
			$sml_box.children().eq(old_i).animate({opacity:0},C.animation.time,function(){
				$sml_box.children().eq(old_i).css({opacity: 1, display: 'none'});
			});
		},
		
		wide: function(){
			var $book_box=$('#bookBox');
			if(!$book_box.length){return;}
			//добавляем обработчики клика по лид-тексту и sml
			$book_box.find('div.sml').css({cursor:'pointer'}).bind('click',function(evt){
				evt.preventDefault();
				C.books.wideStart();
			})
			// на странице слайдов рисуем картинки и добавляем эскизики
			var $wide_box=$('#wideBox');
			var $thumbnails_p=$(document.createElement('p')).appendTo($wide_box.find('div.thumbnails'));
			C.books.wideCreateThumbnailsAndImages($thumbnails_p,$wide_box);
			var widepages=C.books.widepages[C.books.current_book];
			// делаем прозрачными кнопки влево вправо и закрыть
			$wide_box.find('div.arr, div.close').css({opacity:0});
			// обработчик a.close
			$wide_box.find('div.close').bind('click',function(evt){
				evt.preventDefault();
				C.books.wideClose();
			})
			// обработчики клика по стрелочкам
			$wide_box.find('div.arr a').bind('click',function(evt){
				evt.preventDefault();
				if($(evt.target).parents('div.arr').attr('className').indexOf('prev')>=0){
					hash={prev:true};
				}else{
					hash={next:true};
				}
				C.books.wideToggle(hash);
			})
		},
		
		wideCreateThumbnailsAndImages: function($thumbnails_p,$wide_box,new_i){
			var widepages=C.books.widepages[C.books.current_book];
			if(!widepages){return;}
			for(var i=0; i<widepages.length; i++){
				if(widepages[i].html){
					$wide_box.children('div.center').children('div.images').
						append($(document.createElement('div')).addClass('page').html(widepages[i].html));
				}else{
					$wide_box.children('div.center').children('div.images').
						append($(document.createElement('div')).addClass('image').
							append($(document.createElement('img')).attr({src: widepages[i].src, width: widepages[i].width, height: 620})));
				}
				if(widepages[i].thumbnail){
					$thumbnails_p.
						append($(document.createElement('span')).
							append($(document.createElement('a')).attr({href:'#'}).
								append($(document.createElement('img')).attr({src: widepages[i].thumbnail, width: 25, height: 25}))));
				}
			}
			// возможно среди картинок есть превьюшка для видео
			if($wide_box.find('div.images div.flv').length){
				$wide_box.find('div.images div.flv').each(function(i){
					var flv_preview=$(this).find('div.lcol img').attr('src');
					var flv_height=$(this).find('div.lcol img').attr('rel');
					var flv_uri=$(this).find('div.lcol div').attr('rel');
					var $box=$(this).find('div.lcol div');
					var s1 = new SWFObject('/u/media/mediaplayer/player.swf','player','475',(32 + parseInt(flv_height)),'8');
					s1.addParam('allowfullscreen','true');
					s1.addParam('flashvars','file='+flv_uri+'&image='+flv_preview+'&skin=/u/media/Modieus_Slim/stylish_slim.swf&allowFullscreen=true&icons=false&backcolor=#cccccc');
					s1.write($box.attr('id'));
				})
			}
			// пробегаем по эскизикам, добавляем обработчики
			$thumbnails_p.width(widepages.length*(25+4));
			$thumbnails_p.find('a').each(function(i){
				if(typeof new_i!='undefined' && new_i==i){
					$(this).addClass('active');
				}
				$(this).bind('click',function(evt){
					evt.preventDefault();
					var hash={new_i:i}
					C.books.wideToggle(hash);
				})
			})
		},
		
		wideReset: function(evt){
			if(C.animation.process){
				return;
			}else if(evt && evt.type=='scroll'){
				//если происходит прокрутка, то перепозиционируем #widebox
				// причем лишь в том случае, если бокс показывает свой верхний или нижний край
				var $wide_box=$('#wideBox');
				var scroll_top=$.evScrollTop();
				var screen_height=$.evScreenHeight();
				if(C.books.wide_box_top > scroll_top){
					$wide_box.css({top:scroll_top});
					C.books.wide_box_top=scroll_top;
				}else if( scroll_top + screen_height > C.books.wide_box_top + C.books.wide_box_height){
					var wide_box_top=scroll_top + screen_height - C.books.wide_box_height;
					$wide_box.css({top:wide_box_top});
					C.books.wide_box_top=wide_box_top;
				}
			}else{
				var $wide_box=$('#wideBox');
				var screen_height=$.evScreenHeight();
				var scroll_top=$.evScrollTop();
				var wide_box_height=Math.max(screen_height, C.books.widebox_min);
				$wide_box.css({height:wide_box_height, top:scroll_top});
				// запоминаем высоту #widebox и верхний отступ
				C.books.wide_box_height=wide_box_height;
				// определяем процент прокрутки 
				var scroll_top_percent=scroll_top / ($.evScrollHeight() - screen_height);
				// какую величину от высоты слоя #wideBox составляет этот процент
				var wide_box_scroll_top_percernt=(wide_box_height - screen_height) * scroll_top_percent;
				// определяем точку, где должен начинаться #wideBox
				C.books.wide_box_top=scroll_top - wide_box_scroll_top_percernt;
				// возможна ситуация когда C.books.wide_box_top принимает значение NaN
				// тогда нам нужно превратить его в 0
				if(isNaN(C.books.wide_box_top)){C.books.wide_box_top=0}
				//вот такая сложная формула для определения расстояния 
				// от верхнего края #wideBox до его логического центра
				var wide_box_center=(wide_box_height-C.books.widebox_min) / 2 + 620/2 + C.books.widebox_top
				//нужно установть высоту div.bg и его отступ сверху
				var bg_top=wide_box_center - C.books.widebox_bg/2 - 30;
				$wide_box.children('div.bg').css({height:C.books.widebox_bg, top:bg_top});
				//также установить верхний отступ для div.center
				var center_top=wide_box_center - 620/2 - 30;
				// на странице выставки мы это расстояние поднимаем на 30 пикселов
				// впоследствии это правило было распространено на все картинки
				// также фон div.bg был приподнят на 30 пикселей
				// if(location.pathname.indexOf('/portfolio/exhibitions/')==0){
				// 	center_top-=30;
				// }
				$wide_box.children('div.center').css({top:center_top});
				// console.log('wide_box_height='+wide_box_height);
				// console.log('wide_box_center='+wide_box_center);
				// console.log('bg_top='+bg_top);
				// console.log('center_top='+center_top);
				C.books.setMarginTop($wide_box);
			}
		},
		
		setMarginTop: function($wide_box){
			// вот еще какая задача возникла: расположить по вертикальному центру текстовый блок на первой странице
			var $first_widepage=$wide_box.find('div.images').children().eq(0);
			if($first_widepage.is('div.page') && $first_widepage.children('div.cols').length){
				var top=$first_widepage[0].offsetHeight/2 - $first_widepage.children('div.cols')[0].offsetHeight/2;
				//alert([$first_widepage[0].offsetHeight,$first_widepage.children('div.cols')[0].offsetHeight])
				$first_widepage.children('div.cols').css({paddingTop: top+'px'});
			}
		},
		
		wideStart: function(){
			//запоминаем положение прокрутки до входа в режим полноэкранного просмотра
			//C.books.scroll_bak=[$.evScrollLeft(),$.evScrollTop()];
			C.books.wideReset();
			C.animation.process=true;
			// определяем какой из слайдов нужно показать (class="active")
			var active_i;
			var $thumbnails_a=$('#bookBox div.thumbnails span a');
			for(var i=0; i<$thumbnails_a.length; i++){
				if($thumbnails_a.eq(i).attr('className').indexOf('active')>=0){
					active_i=i;
					break;
				}
			}
			var $wide_box=$('#wideBox');
			// делаем слайд активным (и сбрасываем предыдущий актиынй слайд)
			// аналогично поступаем с эскизиком
			var $images=$wide_box.find('div.images');
			$images.children().removeClass('active').eq(active_i).addClass('active').css({left:0});
			$wide_box.find('div.thumbnails a').removeClass('active').eq(active_i).addClass('active');
			// анимируем появление слоя
			$wide_box.css({top: C.books.wide_box_top-C.books.wide_box_height}).show().animate({top: C.books.wide_box_top+45}, C.animation.time, 'easeInOutCubic', function(){
				$wide_box.children('div.copy').show();
				$wide_box.find('div.close').animate({opacity:1},C.animation.time,function(){$(this).attr({style:''})});
				// показываем стрелки какие можно
				if(active_i>0 || !C.books.currentBookIsFirst()){
					$wide_box.find('div.center > div.prev').animate({opacity:1},C.animation.time)
				}
				if(active_i+1<$images.children().length || !C.books.currentBookIsLast()){
					$wide_box.find('div.center > div.next').animate({opacity:1},C.animation.time)
				}
				$wide_box.animate({top: C.books.wide_box_top}, C.animation.time, 'easeInOutCubic', function(){
					C.animation.process=false;
					//прокручиваем окно к самому верху, сохраняя прежнее значение по горизонтали
					//window.scrollTo(C.books.scroll_bak[0],0);
					//$(window).trigger('scroll');
				});
			})
			C.books.setMarginTop($wide_box);
		},
		
		wideClose: function(){
			// сравниваем url текущего элемента с реальным
			var path_info=C.books.path_infos[C.books.current_book];
			var current_book_url='/portfolio/';
			current_book_url+=path_info[0]+'/'+path_info[2]+'/';
			if(current_book_url!=location.pathname){
				$('#wideBox div.thumbnails span').each(function(i){
					if($(this).children().is('a.active')){
						current_book_url+='page'+(i+1)+'.html';
					}
				})
				location.href=current_book_url;
			}else{
				C.animation.process=true;
				//прокручиваем родительское окно к сохраненным ранее координатам
				//window.scrollTo(C.books.scroll_bak[0],C.books.scroll_bak[1]);
				C.books.wideReset();
				var $wide_box=$('#wideBox');
				$wide_box.find('div.arr').animate({opacity:0}, C.animation.time);
				$wide_box.find('div.close').animate({opacity:0}, C.animation.time);
				$wide_box.animate({top: C.books.wide_box_top+45}, C.animation.time, 'easeInOutCubic', function(){
					$wide_box.animate({top: C.books.wide_box_top-C.books.wide_box_height}, C.animation.time, 'easeInOutCubic', function(){
						C.animation.process=false;
						$wide_box.hide();
					});
					$wide_box.children('div.copy').css({display: 'none'});
				})
			}
		},

		wideToggle: function(hash){
			if(C.animation.process){return;}
			var old_i;
			var $wide_box=$('#wideBox');
			var $div_center=$wide_box.children('div.center');
			var $images=$div_center.children('div.images');
			// определяем old_i
			for(var i=0; i<$images.children().length; i++){
				if($images.children().eq(i).attr('className').indexOf('active')>=0){
					old_i=i;
					break;
				}
			}

			var new_i, direction;
			if(hash.prev){
				new_i=old_i-1;
				direction=-1;
			}else	if(hash.next){
				new_i=old_i+1;
				direction=1;
			}else{
				new_i=hash.new_i;
				if(new_i==old_i){return}
				direction=(new_i>old_i) ? 1 : -1 ;
			}
			if(new_i==-1 && C.books.currentBookIsFirst()){return;}
			if(new_i==C.books.widepages[C.books.current_book].length && C.books.currentBookIsLast()){return;}
			//вызываем действие по клику на эскизик в родительском окне
			$('#bookBox').find('div.thumbnails span a').eq(new_i).trigger('click');
			var width=$images[0].offsetWidth;
			C.animation.process=true;
			//если дошли до края, скрываем стрелку
			if(new_i==0 && C.books.currentBookIsFirst()){
				$div_center.children('div.prev').animate({opacity:0},C.animation.time)
			}else if(new_i+1==$images.children().length && C.books.currentBookIsLast()){
				$div_center.children('div.next').animate({opacity:0},C.animation.time)
			}
			$images.children().eq(old_i).css({left: 0}).animate({left: -1*direction*width}, C.animation.time, 'easeInCubic', function(){
				//если отошли от края, показываем стрелку
				if(old_i==0 && C.books.currentBookIsFirst()){
					$div_center.children('div.prev').animate({opacity:1},C.animation.time)
				}else if(old_i+1==$images.children().length && C.books.currentBookIsLast()){
					$div_center.children('div.next').animate({opacity:1},C.animation.time)
				}
				var $thumbnails_p=$wide_box.find('div.thumbnails p');
				if(new_i==-1 || new_i==$images.children().length){
					// сменить книгу
					C.books.changeCurrentBook(direction);
					new_i=(new_i<0) ? new_i+C.books.widepages[C.books.current_book].length : 0;
					//если теперь выяснилось, что дошли до края, скрываем стрелку
					if(new_i==0 && C.books.currentBookIsFirst()){
						$div_center.children('div.prev').animate({opacity:0},C.animation.time)
					}else if(new_i+1==$images.children().length && C.books.currentBookIsLast()){
						$div_center.children('div.next').animate({opacity:0},C.animation.time)
					}
					// сменить градусник
					$gradusnik_small=$wide_box.find('div.gradusnik>p>small');
					var path_info=C.books.path_infos[C.books.current_book];
					$gradusnik_small.children('a').eq(2).attr({href:'/portfolio/'+path_info[0]+'/'}).children('span').text(path_info[1]);
					$gradusnik_small.children('b').empty().html('<span class="div">/</span> '+path_info[3]);
					// удалить старые эскизики
					$thumbnails_p.empty();
					// удалить старые изображения
					$images.empty();
					// построить эскизики, привесить к ним события, построить изображения другой книги
					C.books.wideCreateThumbnailsAndImages($thumbnails_p,$wide_box,new_i);
					// анимировать появление страницы другой книги
					$images.children().eq(new_i).css({left: direction*width}).addClass('active').animate({left: 0}, C.animation.time, 'easeOutCubic', function(){
						//$images.css({zIndex:'auto'})
						C.animation.process=false;
					})
				}else{
					// анимируем появление другой страницы, когда просмотр происходит в пределах одной книги
					$images.children().eq(old_i).removeClass('active');
					$thumbnails_p.find('a').eq(old_i).removeClass('active');
					$thumbnails_p.find('a').eq(new_i).addClass('active');
					$images.children().eq(new_i).css({left: direction*width}).addClass('active').animate({left: 0}, C.animation.time, 'easeOutCubic', function(){
						//$images.css({zIndex:'auto'})
						C.animation.process=false;
					})
					// размещаем содержимое страницы по вертикальному центру
					if(new_i==0){
						C.books.setMarginTop($wide_box);
					}
				}
			})
		}
	},

	technics: {
		widebox_min: 662,
		widebox_bg: 952,
		widebox_top: 70,
		widepages: [],
		scroll_bak: [],

		init: function(){
			C.technics.wide();
		},

		wide: function(){
			var $technics_box=$('#technicsBox');
			if(!$technics_box.length){return;}
			//добавляем обработчики клика по лид-тексту и sml
			$technics_box.find('div.sml').css({cursor:'pointer'}).bind('click',function(evt){
				evt.preventDefault();
				C.technics.wideStart();
			})
			// на странице полноэкранных слайдов размещаем картинки и текст
			var $wide_box=$('#wideBox');
			for(var i=0; i<C.technics.widepages.length; i++){
				if(C.technics.widepages[i].html){
					$wide_box.children('div.center').children('div.images').
						append($(document.createElement('div')).addClass('page').html(C.technics.widepages[i].html));
				}else{
					$wide_box.children('div.center').children('div.images').
						append($(document.createElement('div')).addClass('image').
							append($(document.createElement('img')).attr({src: C.technics.widepages[i].src, width: C.technics.widepages[i].width, height: 620})));
				}
			}
			// делаем прозрачными кнопки влево вправо и закрыть
			$wide_box.find('div.arr, div.close').css({opacity:0});
			// обработчик a.close
			$wide_box.find('div.close').bind('click',function(evt){
				evt.preventDefault();
				C.technics.wideClose();
			})
			// обработчики клика по стрелочкам
			$wide_box.find('div.arr a').bind('click',function(evt){
				evt.preventDefault();
				if($(evt.target).parents('div.arr').attr('className').indexOf('prev')>=0){
					hash={prev:true};
				}else{
					hash={next:true};
				}
				C.technics.wideToggle(hash);
			})
		},
		
		wideReset: function(evt){
			if(C.animation.process){
				return;
			}else if(evt && evt.type=='scroll'){
				//если происходит прокрутка, то перепозиционируем #widebox
				// причем лишь в том случае, если бокс показывает свой верхний или нижний край
				var $wide_box=$('#wideBox');
				var scroll_top=$.evScrollTop();
				var screen_height=$.evScreenHeight();
				if(C.technics.wide_box_top > scroll_top){
					$wide_box.css({top:scroll_top});
					C.technics.wide_box_top=scroll_top;
				}else if( scroll_top + screen_height > C.technics.wide_box_top + C.technics.wide_box_height){
					var wide_box_top=scroll_top + screen_height - C.technics.wide_box_height;
					$wide_box.css({top:wide_box_top});
					C.technics.wide_box_top=wide_box_top;
				}
			}else{
				var $wide_box=$('#wideBox');
				var screen_height=$.evScreenHeight();
				var scroll_top=$.evScrollTop();
				var wide_box_height=Math.max(screen_height, C.technics.widebox_min);
				$wide_box.css({height:wide_box_height, top:scroll_top});
				// запоминаем высоту #widebox и верхний отступ
				C.technics.wide_box_height=wide_box_height;
				// определяем процент прокрутки 
				var scroll_top_percent=scroll_top / ($.evScrollHeight() - screen_height);
				// какую величину от высоты слоя #wideBox составляет этот процент
				var wide_box_scroll_top_percernt=(wide_box_height - screen_height) * scroll_top_percent;
				// определяем точку, где должен начинаться #wideBox
				C.technics.wide_box_top=scroll_top - wide_box_scroll_top_percernt;
				// возможна ситуация когда C.technics.wide_box_top принимает значение NaN
				// тогда нам нужно превратить его в 0
				if(isNaN(C.technics.wide_box_top)){C.technics.wide_box_top=0}
				//вот такая сложная формула для определения расстояния 
				// от верхнего края #wideBox до его логического центра
				var wide_box_center=(wide_box_height-C.technics.widebox_min) / 2 + 620/2 + C.technics.widebox_top
				//нужно установть высоту div.bg и его отступ сверху
				var bg_top=wide_box_center - C.technics.widebox_bg/2 - 30;
				$wide_box.children('div.bg').css({height:C.technics.widebox_bg, top:bg_top});
				//также установить верхний отступ для div.center
				var center_top=wide_box_center - 620/2 - 30;
				// на странице выставки мы это расстояние поднимаем на 30 пикселов
				// впоследствии это правило было распространено на все картинки
				// также фон div.bg был приподнят на 30 пикселей
				// if(location.pathname.indexOf('/portfolio/exhibitions/')==0){
				// 	center_top-=30;
				// }
				$wide_box.children('div.center').css({top:center_top});
				// console.log('wide_box_height='+wide_box_height);
				// console.log('wide_box_center='+wide_box_center);
				// console.log('bg_top='+bg_top);
				// console.log('center_top='+center_top);
				C.technics.setMarginTop($wide_box);
			}
		},
		
		setMarginTop: function($wide_box){
			// вот еще какая задача возникла: расположить по вертикальному центру текстовый блок на первой странице
			var $first_widepage=$wide_box.find('div.images').children().eq(0);
			if($first_widepage.is('div.page') && $first_widepage.children('div.cols').length){
				var top=$first_widepage[0].offsetHeight/2 - $first_widepage.children('div.cols')[0].offsetHeight/2;
				//alert([$first_widepage[0].offsetHeight,$first_widepage.children('div.cols')[0].offsetHeight])
				$first_widepage.children('div.cols').css({paddingTop: top+'px'});
			}
		},
		
		wideStart: function(){
			//запоминаем положение прокрутки до входа в режим полноэкранного просмотра
			C.technics.wideReset();
			C.animation.process=true;
			// определяем какой из слайдов нужно показать (class="active")
			var active_i;
			for(var i=0; i<C.technics.widepages.length; i++){
				if(C.technics.widepages[i].active){
					active_i=i;
					break;
				}
			}
			// делаем слайд активным (и сбрасываем предыдущий актиынй слайд)
			var $wide_box=$('#wideBox');
			var $images=$wide_box.find('div.images');
			$images.children().removeClass('active').eq(active_i).addClass('active').css({left:0});
			// анимируем появление слоя
			$wide_box.css({top: C.technics.wide_box_top-C.technics.wide_box_height}).show().animate({top: C.technics.wide_box_top+45}, C.animation.time, 'easeInOutCubic', function(){
				$wide_box.children('div.copy').show();
				$wide_box.find('div.close').animate({opacity:1},C.animation.time,function(){$(this).attr({style:''})});
				// показываем стрелки какие можно
				if(active_i>0){
					$wide_box.find('div.center > div.prev').animate({opacity:1},C.animation.time)
				}
				if(active_i+1<$images.children().length){
					$wide_box.find('div.center > div.next').animate({opacity:1},C.animation.time)
				}
				$wide_box.animate({top: C.technics.wide_box_top}, C.animation.time, 'easeInOutCubic', function(){
					C.animation.process=false;
					//прокручиваем окно к самому верху, сохраняя прежнее значение по горизонтали
					//window.scrollTo(C.technics.scroll_bak[0],0);
					//$(window).trigger('scroll');
				});
			})
			C.technics.setMarginTop($wide_box);
		},
		
		wideClose: function(){
			// в том случае, когда мы перемотали слайд на подстраницу, отличную от первоначальной,
			// по клику на "Закрыть" необходимо сделать редирект на новую подстраницу
			// определяем текущий активный элемент
			var current_i;
			var $wide_box=$('#wideBox');
			var $div_center=$wide_box.children('div.center');
			var $images=$div_center.children('div.images');
			for(var i=0; i<$images.children().length; i++){
				if($images.children().eq(i).attr('className').indexOf('active')>=0){
					current_i=i;
					break;
				}
			}
			// сравниваем url текущего элемента с реальным
			if(C.technics.widepages[current_i].url!=location.pathname){
				location.href=C.technics.widepages[current_i].url;
			}else{
				C.animation.process=true;
				//прокручиваем родительское окно к сохраненным ранее координатам
				//window.scrollTo(C.technics.scroll_bak[0],C.technics.scroll_bak[1]);
				C.technics.wideReset();
				var $wide_box=$('#wideBox');
				$wide_box.find('div.arr').animate({opacity:0}, C.animation.time);
				$wide_box.find('div.close').animate({opacity:0}, C.animation.time);
				$wide_box.animate({top: C.technics.wide_box_top+45}, C.animation.time, 'easeInOutCubic', function(){
					$wide_box.animate({top: C.technics.wide_box_top-C.technics.wide_box_height}, C.animation.time, 'easeInOutCubic', function(){
						C.animation.process=false;
						$wide_box.hide();
					});
					$wide_box.children('div.copy').css({display: 'none'});
				})
			}
		},

		wideToggle: function(hash){
			if(C.animation.process){return;}
			var old_i;
			var $wide_box=$('#wideBox');
			var $div_center=$wide_box.children('div.center');
			var $images=$div_center.children('div.images');
			// определяем old_i
			for(var i=0; i<$images.children().length; i++){
				if($images.children().eq(i).attr('className').indexOf('active')>=0){
					old_i=i;
					break;
				}
			}

			var new_i, direction;
			if(hash.prev){
				new_i=old_i-1;
				direction=-1;
			}else	if(hash.next){
				new_i=old_i+1;
				direction=1;
			}else{
				new_i=hash.new_i;
				if(new_i==old_i){return}
				direction=(new_i>old_i) ? 1 : -1 ;
			}

			if($images.children().eq(new_i).length){
				//вызываем действие по клику на эскизик в родительском окне
				$('#technicsBox').find('div.thumbnails span a').eq(new_i).trigger('click');
				var width=$images[0].offsetWidth;
				C.animation.process=true;
				//если дошли до края, скрываем стрелку
				if(new_i==0){
					$div_center.children('div.prev').animate({opacity:0},C.animation.time)
				}else if(new_i+1==$images.children().length){
					$div_center.children('div.next').animate({opacity:0},C.animation.time)
				}
				$images.children().eq(old_i).css({left: 0}).animate({left: -1*direction*width}, C.animation.time, 'easeInCubic', function(){
					$images.children().eq(old_i).removeClass('active');
					var $thumbnails_p=$wide_box.find('div.thumbnails p');
					$thumbnails_p.find('a').eq(old_i).removeClass('active');
					$thumbnails_p.find('a').eq(new_i).addClass('active');
					//если отошли от края, показываем стрелку
					if(old_i==0){
						$div_center.children('div.prev').animate({opacity:1},C.animation.time)
					}else if(old_i+1==$images.children().length){
						$div_center.children('div.next').animate({opacity:1},C.animation.time)
					}
					// меняем градусник
					$wide_box.find('div.gradusnik>p>small').empty().html(C.technics.widepages[new_i].gradusnik);
					// анимируем
					$images.children().eq(new_i).css({left: direction*width}).addClass('active').animate({left: 0}, C.animation.time, 'easeOutCubic', function(){
						//$images.css({zIndex:'auto'})
						C.animation.process=false;
					})
					if(new_i==0){
						C.technics.setMarginTop($wide_box);
					}
				})
			}
		}
	}
}

