jQuery(document).ready(function(){
var	carSpeed = 600;	// скорость смены слайдов
	popSpeed = 500	// скорость показа попапа
// прелоад
jQuery('body').append('<img src="pic/lightbox/lightbox-ico-loading.gif" style="position: absolute; left: -1000px; top: -1000px" />')

var	carousel = jQuery('.contentCarousel').eq(0),				// карусель (ul)
	toLeft = jQuery('#carouselLeft'),						// id стрелки влево
	toRight = jQuery('#carouselRight');						// id стрелки вправо
	process = false,									// флаг состояния процесса анимации
	aaa = new Array(),
	slideArray = jQuery('.contentCarousel').find('>li');			// массив слайдов	
	elementsCount = slideArray.length,						// кол-во слайдов	
	current = jQuery(slideArray[0]),						// назначаем текущий слайд
	next = jQuery(slideArray[1]),							// назначаем следующий слайд
	prev = jQuery(slideArray[elementsCount-1]),				// назначаем предыдущий слайд
	nextNext = jQuery(slideArray[2]),						// назначаем после следующего
	prevPrev = jQuery(slideArray[elementsCount-2]),			// назначаем слайд перед предыдущим
	curIndex = 1, nextIndex = 2, prevIndex =elementsCount,	// ------------------------------------------------
	nextNextIndex = nextIndex+1, prevPrevIndex = prevIndex-1,// счетчики для слежения порядка слайдов
	carContainer =	jQuery('.contentCarouselContainer').eq(0);	// контейнер карусели
var	tempPrevSlide = prevIndex, tempNextSlide = nextIndex;

	// генерим пайджинг
	var	pStruct='', i;
	for (i=1;i<=elementsCount;i++)
	{
		if (i == curIndex) 
		{
			pStruct +='<li style="visibility: hidden" id="pageBack"><div>...</div></li><li style="display: inline">'+i+'.</li>'; 
			var	ten;
			if (elementsCount<10) ten = elementsCount
				else ten = 10;
			i++;
			while (i<=ten)
			{
				if (i%6 == 0) pStruct +=''+'<li style="clear: left; margin-left: 20px"><span>'+i+'.</span></li>'
					else
						pStruct +=''+'<li style="display: inline"><span>'+i+'.</span></li>';
				i++;
			};
			i--;
		}
			else 	pStruct +=''+'<li style="display: none"><span>'+i+'.</span></li>';
	};
	if (elementsCount > 10) pStruct +='<li style="display: inline" id="pageMore"><div>...</div></li>'
		else pStruct +='<li style="visibility: hidden" id="pageMore"><div>...</div></li>'; 
		
	carContainer.after('<ul class="carouselPaging">'+pStruct+'</ul>');
	
	// массив с пейджингом		
	var	pageArray = jQuery('.carouselPaging').find('>li'),
		pageCount = Math.ceil((pageArray.length-2)/10),
		pageRest = (pageArray.length-2)%10,
		pageCounter = 1;
		
		
	// раздаем подписи слайдам
	carousel.find('> li a div').each(function(){
		jQuery(this).html('<span></span>'+'<p>'+jQuery(this).parent().find('img').eq(0).attr('alt')+'</p>');
	});		
	
	// устанавливаем следующий и предыдущий слайды
	prev.css({display: 'block', left: 0, top: 28, width: 326, height: 217, opacity: 1, zIndex: 1});
		prev.find('img').css({display: 'block', left: 0, top: 0, width: 326, height: 217, opacity: 1});
	next.css({display: 'block', left: 285, top: 28, width: 326, height: 217, opacity: 1, zIndex: 1});
		next.find('img').css({display: 'block', right: 0, top: 0, width: 326, height: 217, opacity: 1});
	current.css('z-index','2');


// клик на пейджинге
jQuery('.carouselPaging li span').live('click', function(){
if (process == false)
{
	process = true;	
	var	targetSlide = parseInt(jQuery(this).text()),
		direction;
		
		if (curIndex<targetSlide) 
		{
			direction = 'right';
			nextIndex = targetSlide;
			rightClick(targetSlide);
			pageChange(targetSlide, direction);	
		}
			else
			{
				direction = 'left';
				prevIndex = targetSlide;
				pageChange(targetSlide, direction);
				leftClick(targetSlide);
			};
};

});			
	
// right scroll	
toRight.click(function(){
	if (process == false)
	{
		process = true;
		rightClick(curIndex+1);
		pageChange(curIndex+1, 'right');
		if (nextIndex>elementsCount) nextIndex = 1;
		if (((nextIndex)%10) == 1) 
		{
			pagerRight();
		};
		
	};
});		       


// left scroll	
toLeft.click(function(){
	if (process == false)
	{
		process = true;
		pageChange(curIndex-1, 'left');				
		leftClick(curIndex-1);
		if ((curIndex%10) == 1)
		{
//			alert(pageCounter);
			pagerLeft();
		};
		
/*		if ((pageCounter == pageCount)&(curIndex == 1)&(pageCount>1)) 
		{
			pageCounter = 1;
			pagerLeft();
		}
*/		
	};
});		


function rightClick(target) {
	// темп-слайды
	jQuery(slideArray[tempNextSlide-1]).css({opacity: 0});
	jQuery(slideArray[tempPrevSlide-1]).css({opacity: 0});
	tempPrevSlide = curIndex;
	tempNextSlide = target+1;

	// проверяем не вылезли ли за границы счетчики
	if (target > elementsCount) target = 1;
	if (target == elementsCount) nextNextIndex = 1
		else 	nextNextIndex = target+1;

	// указываем слайды для операции
	current = jQuery(slideArray[curIndex-1]);
	next = jQuery(slideArray[target-1]);
	prev = jQuery(slideArray[prevIndex-1]);
	nextNext = jQuery(slideArray[nextNextIndex-1]);
	prevPrev = jQuery(slideArray[prevPrevIndex-1]);

	// подготовка следующих и предыдущих слайдов
	prev.css({display: 'block', left: 0, top: 28, width: 326, height: 217, opacity: 1});		
		prev.find('img').css({display: 'block', left: 0, top: 0, width: 326, height: 217, opacity: 1});
	next.css({display: 'block', left: 285, top: 28, width: 326, height: 217, opacity: 0});		
		next.find('img').css({display: 'block', left: 0, top: 0, width: 326, height: 217, opacity: 1});
	nextNext.css({display: 'block', left: 408, top: 90, width: 163, height: 108, opacity: 1, zIndex: 0});
		nextNext.find('img').css({display: 'block', right: 0, top: 0, width: 163, height: 108, opacity: 1});
	

		// смена слайдов
		prev.css('z-index',1);
		current.css('z-index', 2);
		next.css('z-index',3);
		
var	nextClone = next.clone().insertBefore(next);
		nextClone.css({zIndex: 1, opacity: 1});

		
		// прячем левую  картинку
		prev.animate({
			     	width: 163,
				height: 108,
				top: 100,
				left: 40,
				opacity: 1
			     },carSpeed);
		
		prev.find('img').eq(0).animate({
			     	width: 163,
				height: 108
			     },carSpeed);
		
		// текущую влево
		current.animate({
							  width: 326,
							  height: 217,
							  top: 28,
							  left: 0,
							  opacity: 1
						  }, carSpeed);
		
		current.find('img').eq(0).animate({
							  width: 326,
							  height: 217,
							  top: 0,
							  left: 0,
							  opacity: 1
						  }, carSpeed);
		
		// целевую - в центр		
		nextClone.animate({
							  width: 408,
							  height: 269,
							  top: 0,
							  left: 106,
							  opacity: 0
						  }, carSpeed);
		
		nextClone.find('img').eq(0).animate({
							  width: 408,
							  height: 269
						  }, carSpeed);
		
		next.animate({
							  width: 408,
							  height: 269,
							  top: 0,
							  left: 97,
							  opacity: 1
						  }, carSpeed);
		
		next.find('img').eq(0).animate({
							  width: 408,
							  height: 269
						  }, carSpeed);

		// свято-место пусто не бывает
		nextNext.animate({
			     	width: 326,
				height: 217,
				top: 28,
				left: 285
			     },carSpeed);
		
		nextNext.find('img').eq(0).animate({
			     	width: 326,
				height: 217
			     },carSpeed);

		
		// смена подписей		
		current.find('div').eq(0).fadeOut(carSpeed/2);
		setTimeout(function(){
			next.find('div').eq(0).fadeIn(carSpeed/2);
		}, carSpeed/2);
		
	
		// подготавлиаем к следующему прокруту
		setTimeout(function(){
			nextClone.remove();
			prev.css('opacity', 0);
			// переключаем класс
			current.toggleClass('current');
			next.toggleClass('current');

			// обновляем счетчики
			prevIndex = curIndex;
			curIndex = target;
			nextIndex = target+1;
			if (nextIndex > elementsCount) nextIndex = 1;
			process = false;
			prevPrevIndex = prevIndex-1;
			nextNextIndex = nextIndex+1;
			if (nextIndex == elementsCount) nextNextIndex = 1;

		}, carSpeed+100);			    
// end of right scroll	
}

function leftClick(target) {
	// темп-слайды
	jQuery(slideArray[tempNextSlide-1]).css({opacity: 0});
	jQuery(slideArray[tempPrevSlide-1]).css({opacity: 0});
	tempNextSlide = curIndex;
	tempPrevSlide = target - 1;

	// проверяем не вылезли ли за границы счетчиков
	if (target < 1) target = prevIndex = elementsCount;
	if (target == 1) prevPrevIndex = elementsCount
		else prevPrevIndex = target -1;
	
	// указываем слайды для операции
	current = jQuery(slideArray[curIndex-1]);
	next = jQuery(slideArray[nextIndex-1]);
	prev = jQuery(slideArray[target-1]);
	nextNext = jQuery(slideArray[nextNextIndex-1]);
	prevPrev = jQuery(slideArray[prevPrevIndex-1]);

	// подготовка следующих и предыдущих слайдов
	next.css({display: 'block', left: 285, top: 28, width: 326, height: 217, opacity: 1});		
		next.find('img').css({display: 'block', left: 0, top: 0, width: 326, height: 217, opacity: 1});
	prev.css({display: 'block', left: 0, top: 28, width: 326, height: 217, opacity: 0});		
		prev.find('img').css({display: 'block', left: 0, top: 0, width: 326, height: 217, opacity: 1});
	prevPrev.css({display: 'block', left: 40, top: 90, width: 163, height: 108, opacity: 1, zIndex: 0});
		prevPrev.find('img').css({display: 'block', left: 0, top: 0, width: 163, height: 108, opacity: 1});

		// смена слайдов
		prev.css('z-index',3);
		current.css('z-index', 2);
		next.css('z-index',1);
		
var	prevClone = prev.clone().insertBefore(prev);
		prevClone.css({zIndex: 1, opacity: 1});

		// прячем правую  картинку
		next.animate({
			     	width: 163,
				height: 108,
				top: 100,
				left: 408,
				opacity: 1
			     },carSpeed);
		
		next.find('img').eq(0).animate({
			     	width: 163,
				height: 108
			     },carSpeed);

		// текущую вправо
		current.animate({
							  width: 326,
							  height: 217,
							  top: 28,
							  left: 285,
							  opacity: 1
						  }, carSpeed);
		
		current.find('img').eq(0).animate({
							  width: 326,
							  height: 217,
							  top: 0,
							  left: 0,
							  opacity: 1
						  }, carSpeed);
		
		// целевую - в центр		
		prevClone.animate({
							  width: 408,
							  height: 269,
							  top: 0,
							  left: 97,
							  opacity: 0
						  }, carSpeed);
		
		prevClone.find('img').eq(0).animate({
							  width: 408,
							  height: 269
						  }, carSpeed);
		
		prev.animate({
							  width: 408,
							  height: 269,
							  top: 0,
							  left: 97,
							  opacity: 1
						  }, carSpeed);
		
		prev.find('img').eq(0).animate({
							  width: 408,
							  height: 269
						  }, carSpeed);
		
		// свято-место пусто не бывает
		prevPrev.animate({
			     	width: 326,
				height: 217,
				top: 28,
				left: 0
			     },carSpeed);
		
		prevPrev.find('img').eq(0).animate({
			     	width: 326,
				height: 217
			     },carSpeed);


		// смена подписей		
		current.find('div').eq(0).fadeOut(carSpeed/2);
		setTimeout(function(){
			prev.find('div').eq(0).fadeIn(carSpeed/2);
		}, carSpeed/2);
		
	
		// подготавлиаем к следующему прокруту
		setTimeout(function(){
				    
			prevClone.remove();
			next.css('opacity', 0);

			// переключаем класс
			current.toggleClass('current');
			prev.toggleClass('current');
					
			// обновляем счетчики
			nextIndex = curIndex;
			curIndex = target;
			prevIndex = target-1;		
			if (prevIndex < 1) prevIndex = elementsCount;
			process = false;
			prevPrevIndex = prevIndex-1;
			nextNextIndex = nextIndex+1;
			if (prevIndex == 1) prevPrevIndex = elementsCount;
		}, carSpeed+100);			    
// end of left scroll	
}

// анимация для пейджинга
function pageChange(target, direct){
	if (target > elementsCount) target = 1;
	if (target < 1) target = prevIndex = elementsCount;
var	curText =	jQuery(pageArray[curIndex]).text(),
	nextText = jQuery(pageArray[target]).find('span').eq(0).text(),
	prevText = jQuery(pageArray[target]).find('span').eq(0).text();

	jQuery(pageArray[curIndex]).css({fontSize: 12});
	switch (direct)
	{
		case 'right':	jQuery(pageArray[target]).find('span').eq(0).css({fontSize: 16});
					jQuery(pageArray[curIndex]) .attr('style','display: inline') .html('<span>'+curText+'</span>');
					if ((target+4)%10 != 0) jQuery(pageArray[target]).html(nextText) .attr('style','display: inline')
						else jQuery(pageArray[target]).html(nextText) .attr('style','display: inline; clear: left; margin-left: 20px');
					break;
					
		case 'left':	jQuery(pageArray[target]).find('span').eq(0).css({fontSize: 16});
					jQuery(pageArray[curIndex]) .attr('style','display: inline') .html('<span>'+curText+'</span>');
					if ((target+4)%10 != 0) jQuery(pageArray[target]).html(nextText) .attr('style','display: inline')
						else jQuery(pageArray[target]).html(nextText) .attr('style','display: inline; clear: left; margin-left: 20px');
					break;
	}
};	

// клик на пейджере дальше
jQuery('#pageMore').live('click',function(){

if (process == false)
{
	process = true;
	rightClick(pageCounter*10+1);
	pageChange(pageCounter*10+1, 'right');
	pagerRight();	
};

});				  

function pagerRight(){
var	curPageIndex = (pageCounter*10)-9;
	pageRest = 10-(pageCount*10-elementsCount), i;
	if (pageCounter == pageCount-1)
	{
		for(i=pageCounter*10-10;i<=pageCounter*10; i++) 
		{
			jQuery(pageArray[i]).css('display','none');
		};

		for(i=pageCounter*10+1;i<=pageCounter*10+pageRest; i++) 
		{
			if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
				else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});

		};
		jQuery('#pageMore').css('visibility','hidden');
		jQuery('#pageBack').css('visibility','visible');
		pageCounter++;
	}
		else if (pageCounter == pageCount)
		{
			for(i=pageCounter*10-9;i<=pageCounter*10-10+pageRest; i++)
			{
				jQuery(pageArray[i]).css('display','none');
			};
			
			for(i=1;i<=10; i++) 
			{
				if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
					else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});

			};
			jQuery('#pageMore').css('visibility','visible');
			jQuery('#pageBack').css('visibility','hidden');			
			pageCounter = 1;			
		}
			else
			{
				for(i=pageCounter*10-9;i<=pageCounter*10; i++) 
				{
					jQuery(pageArray[i]).css('display','none');
				};
				
				for(i=pageCounter*10+1;i<=pageCounter*10+10; i++) 
				{
					
					if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
						else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});

				};
				
				jQuery('#pageMore').css('visibility','visible');
				jQuery('#pageBack').css('visibility','visible');
				pageCounter ++;
			};

// end of pager right
};

// клик на пейджере назад
jQuery('#pageBack').live('click',function(){

if (process == false)
{
	process = true;
	leftClick((pageCounter-2)*10+1);
	pageChange((pageCounter-2)*10+1, 'right');
	pagerLeft();	
};

});				  

function pagerLeft(){
var	curPageIndex = (pageCounter*10)-9;	
if (curPageIndex < 0) curPageIndex = (pageCount*10)-9;

	if (pageCounter <= 1)
	{
		pageCounter = 1;
		
		for(i=pageCounter*10-9;i<=pageCounter*10; i++) 
		{
			jQuery(pageArray[i]).css('display','none');
		};
		curIndex = pageCount*10;
		for(i=pageCount*10-9;i<=(pageCount-1)*10+pageRest; i++) 
		{
			if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
				else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});

		};
		jQuery('#pageMore').css('visibility','hidden');
		jQuery('#pageBack').css('visibility','visible');
		pageCounter = pageCount;
	}
		else if (pageCounter == 2)
		{
			for(i=pageCounter*10-9;i<=pageCounter*10; i++)
			{
				jQuery(pageArray[i]).css('display','none');
			};
			
			for(i=1;i<=10; i++) 
			{
				if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
					else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});

			};
			jQuery('#pageMore').css('visibility','visible');
			jQuery('#pageBack').css('visibility','hidden');			
			pageCounter = 1;
		}
			else if (pageCounter == pageCount)
			{
				for(i=(pageCounter-1)*10;i<=(pageCounter-1)*10+pageRest; i++) 
				{
					jQuery(pageArray[i]).css('display','none');
				};
				
				for(i=(pageCounter-2)*10+1;i<=(pageCounter-1)*10; i++) 
				{
					
					if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
						else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});
				};
				
				jQuery('#pageMore').css('visibility','visible');
				jQuery('#pageBack').css('visibility','visible');
				pageCounter --;
				
			}
				else
				{
					for(i=(pageCounter-1)*10+1;i<=pageCounter*10; i++) 
					{
						jQuery(pageArray[i]).css('display','none');
					};
					
					for(i=(pageCounter-2)*10+1;i<=(pageCounter-1)*10; i++) 
					{
						
						if ((i+4)%10 != 0) jQuery(pageArray[i]).css('display','inline')
							else jQuery(pageArray[i]).css({display: 'inline', clear: 'left', marginLeft: 20});
					};
					
					jQuery('#pageMore').css('visibility','visible');
					jQuery('#pageBack').css('visibility','visible');
					pageCounter --;
				};
	
// end of left pager
};

// игры с попапом

// активация попапа
jQuery('.contentCarousel li a').click(function(){
if (process == false)
{
var	loading = false;
	imgSrc = jQuery(this).attr('href'),
	imgStartTop = jQuery(this).find('img').eq(0).offset().top,
	imgStartLeft = jQuery(this).find('img').eq(0).offset().left,
	imgStartWidth = jQuery(this).find('img').eq(0).width(),
	imgStartHeight = jQuery(this).find('img').eq(0).height(),
	img = jQuery(this).find('img').eq(0),
	descr = img.attr('alt');
var	bigWidth =0, bigHeight = 0;

	// втавляем оверлей
	jQuery('#mainWrap').before('<div id="popupOverlay"></div>');
var	overlay = jQuery('#popupOverlay').animate({opacity: 0.3}, popSpeed/3);
	overlay	.css({
		     	width: jQuery(document).width(),
			height: jQuery(document).height()
		     })
	// вставляем попап с прелоадером
	overlay.before('<div id="imgPopup"><div id="imgContainer"><img src='+imgSrc+' width="100%" height="100%" /><span id="close"></span><span id="descr">'+descr+'</span></div><span id="preload"><img src="img/lightbox/lightbox-ico-loading.gif" alt="" width="32" height="32" /></span></div>');
var	popup = jQuery('#imgPopup'),
	bigImg = jQuery('#imgContainer img').eq(0),
	imgContainer = jQuery('#imgContainer').eq(0);

	// определяем стартовую позицию и размер
	popup	.css({
				width: imgStartWidth,
				height: imgStartHeight,
				top: imgStartTop-10,
				left: imgStartLeft-10
			});
	
	// загрузка изображения
	bigImg.load(function(){
	    jQuery(this).removeAttr("width")
		   .removeAttr("height")
		   .css({ width: "", height: "" });
			loading = true;	
			return loading;
	});


// ждем загрузки картинки
var int =	setInterval (function(){
	// если картинка загрузилась
	if (loading == true)
	{
		// реальные размеры картинки
		bigWidth  = bigImg.width(),
		bigHeight = bigImg.height();
		
		clearInterval(int);
var		newPos = windowWorkSize(),
		newXPos = (newPos[0]/2)-(bigWidth/2),
		newYPos = (newPos[1]/2)-(bigHeight/2);
		
		// убрали прелоадер
		popup.find('img').eq(1).remove();
		
		// стартовые размеры картинки
		bigImg	.css({
					width: imgStartWidth,
					height: imgStartHeight
				});		
		bigImg.fadeIn(popSpeed/3);
		setTimeout(function(){
			img.css('display','none');		
		}, popSpeed/3);
		
		// двигаем в центр
		setTimeout(function(){
			popup.animate({
					width: bigWidth,
					height: bigHeight,
					left: newXPos,
					top: newYPos
				      }, popSpeed);
			bigImg.animate({
					width: bigWidth,
					height: bigHeight
				      }, popSpeed);
			
			// развертываем блок
			setTimeout(function(){
				imgContainer.css('background', '#fff');
				imgContainer.animate({
							width: bigWidth+20,
							height: bigHeight + 60
						     }, popSpeed);
				// добавляем кнопку и описание
				setTimeout(function(){
					jQuery('#close').css({
							     top: bigHeight+30,
							     left: bigWidth - 87
							     });
					jQuery('#close').fadeIn(popSpeed/3);
					jQuery('#descr').css({
								top: bigHeight +20,
								left: 10
							     });
					jQuery('#descr').fadeIn(popSpeed/3);
				},popSpeed);					
				
			}, popSpeed);					    
		}, popSpeed/3);
	};
}, 10);


jQuery('#popupOverlay, #close').live('click', function(){
	jQuery('#popupOverlay').animate({opacity: 0}, popSpeed/3);
	// свертываем блок
	imgContainer.animate({
				width: bigWidth,
				height: bigHeight
			     }, popSpeed/3);
	setTimeout(function(){
		imgContainer.css('background', 'none');
		
		// двигаем на исходную
		popup.animate({
				width: imgStartWidth,
				height: imgStartHeight,
				left: imgStartLeft-10,
				top: imgStartTop-10
			      }, popSpeed/3);
		bigImg.animate({
				width: imgStartWidth,
				height: imgStartHeight
			      }, popSpeed/3);
		setTimeout(function(){
			bigImg.fadeOut(popSpeed/3);
			img.css('display','block');
				
				// удаляем попап и оверлей
				jQuery('#imgPopup').animate({opacity: 0}, popSpeed/3);
				setTimeout(function(){
					jQuery('#popupOverlay').remove();
					jQuery('#imgPopup').remove();
				}, popSpeed/3);	
			
		}, popSpeed/3);
	}, popSpeed/3);	
	
});		     
// end process
};
return false;
});				    


// фунция определения "рабочего пространства" для центрирования
function windowWorkSize(){
var wwSize = new Array();
	if (window.innerHeight !== undefined) wwSize= [window.innerWidth,window.innerHeight]
		else	
			{
				wwSizeIE = (document.body.clientWidth) ? document.body : document.documentElement; 
				wwSize= [wwSizeIE.clientWidth, wwSizeIE.clientHeight];
			};
	return wwSize;
};


});				
