﻿// конфигурация



var

	indexEffectTime = 1000, // время (мс) затухания/появления товаров на главной странице

	indexEffectInterval = 2500, // интервал (мс) между выполнениеми эффекта затухания/появления товаров на главной странице

	indexEffectCount = 1, // количество товаров, задействованных в эффекте затухания/появления на главной странице

	newItemCount = 12, // количество подгружаемых за раз товаров в каталоге ( должно быть кратно 4 !!! )

	itemRowLoadingCount = 2, // количество подгружаемых рядов товаров в каталоге

	catalogLoadingSpeed = 1000, // время (мс) подгрузки новых товаров в каталоге

	sliderSpeed = 150, // время (мс) смещения одного превью в карусели

	photoAnimSpeed = 500; // продолжительность (мс) анимации во время смены фотографий в галерее



// служебные переменные



var

	autoLoadMutex = true,

	fspXk, fspYk, loupeWidth, loupeHeight, loupeWidth2, loupeHeight2, loupeWLeft, loupeWTop, loupeWWTop, z = false, loupeWWidth, loupeWHeight;



$( document ).ready( function() {



	// выравнивание товаров в каталоге



	repairItems( $( '.item-row' ).not( $( '.item-photos .item-row' ) ), true );

	repairItems( $( '.item-photos .item-row' ), false );



	// эффект затухания/появления товаров на главной странице



	if ( $( '.index' ).length ) {



		setInterval( function() {



			var

				itemCount = $( '.item' ).length,

				count = Math.min( indexEffectCount, itemCount );



			$items = $( '.item' );

			for ( var i = 1; i <= itemCount - indexEffectCount; i++ )

				$items = $items.not( $items.eq( Math.round( Math.random() * ( $items.length - 1 ) ) ) );



			if ( $.browser.msie && $.browser.version < 7 ) {

				$items.css( 'left', '-99999px' );

				setTimeout( function() {

					$items.css( 'left', '0' );

				}, indexEffectTime );

			} else

				$items.animate( { opacity: 0 }, indexEffectTime, 'linear', function() {

					$items.animate( { opacity: 1 }, indexEffectTime, 'linear', function() {

						$items.css( 'opacity', '' );

					});

				});



		}, indexEffectInterval + 2 * indexEffectTime );



	}



	// меню сортировки в каталоге



	$( '.sort').children( 'li' ).each( function() {



		var $li = $( this );

		$li.find( 'span' ).click( function() {

			$( '.sort .open' ).not( $li ).removeClass( 'open' );

			$li.toggleClass( 'open' );

		});



	});



	var mouseInSort = false;



	$( '.sort li' ).mouseover( function() {

		mouseInSort = true;

	}).mouseout( function() {

		mouseInSort = false;

	});



	$( '*' ).not( '.sort li' ).click( function() {

		if ( ! mouseInSort )

			$( '.sort .open' ).removeClass( 'open' );

	});



	// автоподгрузка товаров в каталоге



	if ( $( '.autoloading' ).length ) {



		loadItems( itemRowLoadingCount );



		$( window ).scroll( function() {



			if ( needNewItems() ) {

				autoLoadMutex = false;

				loadItems( itemRowLoadingCount );

			}



		});



	}



	// скрипты для IE6



	if ( $.browser.msie && $.browser.version < 7 ) {



		// резиновые тени от фотографий и подписей под ними



		$( '.ip-r, .ii-r' ).each( function() {

			var

				top = parseInt( $( this ).css( 'top' ) ),

				bottom = parseInt( $( this ).css( 'bottom' ) ),

				parentHeight = $( this ).parent().outerHeight(),

				height = parentHeight - top - bottom;



			$( this ).height( height );

		});



		$( '.ip-b, .ii-b' ).each( function() {

			var

				left = parseInt( $( this ).css( 'left' ) ),

				right = parseInt( $( this ).css( 'right' ) ),

				parentWidth = $( this ).parent().outerWidth(),

				width = parentWidth - left - right;



			$( this ).width( width );

		});



		// ролловеры

		makeHover( '.pic-link a', 'hover' );

		makeHover( '.sort span', 'hover' );



	}



	// скролл текста в блоке



	if ( $( '.item-description' ).length )

		$( '.id-in' ).jScrollPane( {

			showArrows: true,

			scrollbarWidth: 9,

			maintainPosition: 0,

			scrollbarMargin: 0

		});



	if ( $( '.gallery' ).length ) {



		loadPhoto( $( '.slider a:first' ).attr( 'href' ) );



		// включение-выключение зума



		var

			zoomMutex = true;

			$zoom = $( '.fullsize-photo' );



		$zoom.attr( 'w', parseInt( $zoom.css( 'width' ) ) ).width( 0 ).height( 0 );



		$( '.big-photo .item-title strong' ).click( function() {



			if ( zoomMutex ) {



				zoomMutex = false;



				$( this ).toggleClass( 'zoom' );



				if ( $( this ).hasClass( 'zoom' ) ) {



					var $photo = $( '.big-photo .item-photo img' );



					$zoom.addClass( 'fp-visible' ).animate( {

						width: $zoom.attr( 'w' ),

						height: $photo.height()

					}, photoAnimSpeed, function() {

						$( '.big-photo' ).addClass( 'zoom' );

						z = true;

					});



				} else {



					$( '.big-photo' ).removeClass( 'zoom' );

					z = false;



					$zoom.animate( {

						width: 0,

						height: 0

					}, photoAnimSpeed, function() {

						$( this ).removeClass( 'fp-visible' )

					});



				}



				zoomMutex = true;

			}



		});



		$( '.loupe' ).mousemove( function( e ) {

			if ( z ) {



				var

					x = Math.round( ( e.pageX - loupeWLeft ) - loupeWidth2 ),

 					y = Math.round( ( e.pageY - loupeWTop + loupeWWTop ) - loupeHeight2 );



				if ( x < 0 )

					x = 0;

				if ( x > loupeWWidth - loupeWidth )

					x = loupeWWidth - loupeWidth;



				if ( y < 0 )

					y = 0;

				if ( y > loupeWHeight - loupeHeight )

					y = loupeWHeight - loupeHeight;



				$( '.big-photo em' ).css( 'left', x + 'px' ).css( 'top', y + 'px' );



				// смещение полноразмерного изображения во вьюпорте



				var

					fspX = - Math.round( x * fspXk ),

					fspY = - Math.round( y * fspYk );



				if ( $zoom.find( 'img' ).length )

				$zoom.find( 'img' ).css( 'left', fspX + 'px' ).css( 'top', fspY + 'px' );



			}

		});



		$( '.loupe' ).click( function() {

			$( '.big-photo .item-title strong' ).click();

		});



		$( '.slider a' ).click( function() {

			loadPhoto( $( this ).attr( 'href' ) );

			return false;

		});



	}



});





function loadPhoto( src )

{// загружает фотографию в карточке товара



	var

		galleryWidth = parseInt( $( '.gallery' ).css( 'width' ) ),

		$ip = $( '.big-photo .item' ),

		$loader = $( '.big-pl' ),

		$fsp = $( '.fullsize-photo' );



	$ip.addClass( 'ip-none' );

	$fsp.addClass( 'fsp-hidden' );

	$loader.css( 'top', Math.round( ( $loader.parent().height() - $loader.height() ) / 2 ) + 'px' ).show( 0 );



	var img = new Image();



	// когда фотография загрузилась

	$( img ).load( function() {



		$loader.hide( 0 );



		var

			midWidth = galleryWidth - 11,

			midHeight = Math.round( ( ( midWidth ) / img.width ) * img.height );



		$( '.big-photo .item-photo' ).animate( {

			width: midWidth,

			height: midHeight

		}, photoAnimSpeed, function() {



			$ip.find( 'img' ).attr( 'src', img.src ).show( 0 );

			$ip.removeClass( 'ip-none' );

			$fsp.removeClass( 'fsp-hidden' );



			$fsp.find( 'img' ).attr(

				'src', img.src

			).attr(

				'width', img.width

			).attr(

				'height', img.height

			);



			$( '.loupe' ).width( $( '.big-photo .item-photo img' ).width() ).height( $( '.big-photo .item-photo img' ).height() );



			var

				$loupe = $( '.big-photo em' ),

				$photo = $( '.big-photo .item-photo' );



			if ( $( '.zoom' ).length )

				$zoom.css( 'height', midHeight + 'px' );



			$loupe.width(

				$zoom.attr( 'w' ) / $zoom.find( 'img' ).width() * $photo.width()

			).height(

				$photo.height() / $zoom.find( 'img' ).height() * $photo.height()

			);



			fspXk = $zoom.find( 'img' ).width() / $( '.big-photo .item-photo' ).width();

			fspYk = $zoom.find( 'img' ).height() / $( '.big-photo .item-photo' ).height();

			loupeWidth = $loupe.width();

			loupeHeight = $loupe.height();

			loupeWidth2 = loupeWidth / 2;

			loupeHeight2 = loupeHeight / 2;

			loupeWLeft = $( '.loupe' ).offset().left;

			loupeWTop = $( '.loupe' ).offset().top;

			loupeWWTop = $( '.loupe' ).parent().position().top;

			loupeWWidth = $( '.loupe' ).width();

			loupeWHeight = $( '.loupe' ).height();



			$loupe.css( 'left', '1px' ).css( 'top', '1px' );

			$fsp.find( 'img' ).css( 'left', '0' ).css( 'top', '0' );



		});



	});



	// загружаем изображение

	img.src = src;



}





function screenHeight() { // возвращает высоту рабочей области браузера

	return $.browser.opera ? window.innerHeight : $( window ).height();

}





function repairItems( $itemRowSet, makePadding )

{// выравнивает фотографии товаров в заданном множестве рядов товаров

 // makePadding - (true/false) надо ли растягивать товары по ширине страницы



	$itemRowSet.each( function() {



		var

			loadedImgCount = 0, // количество загруженных изображений в ряду

			$itemRow = $( this ),

			$imgs = $itemRow.find( '.item .item-photo img' );



		$imgs.each( function() {



			var img = new Image();

			img.src = $( this ).attr( 'src' );



			$( img ).load( function() {



				loadedImgCount++;



				if ( loadedImgCount == $imgs.length ) {



					var rowWidth = $itemRow.parent().innerWidth();



					var itemWidth = 0;

					$itemRow.find( '.item' ).each( function() {

						// подписи под фото не должны растягивать блоки

						$( this ).css( 'width', $( this ).find( '.item-photo img' ).get( 0 ).width + 11 + 'px' );

						itemWidth += $( this ).innerWidth(); // считаем общую ширину товаров в ряду

					});



					if ( makePadding ) {



						var

							itemCount = $itemRow.find( '.item' ).length,

							padding = Math.floor( ( rowWidth - itemWidth ) / ( itemCount - 1 ) ), // отступ между товарами

							lastPadding = ( rowWidth - itemWidth ) - padding * ( itemCount - 2 ); // отступ перед последним товаров (учет ошибки округления)



						// задаем отступы

						for ( var i = 1; i <= itemCount - 1; i++ )

							$itemRow.find( '.item' ).eq( i - 1 ).css( 'padding-right', ( i == itemCount - 1 ? lastPadding : padding ) + 'px' );



					}



				}



			});



		});



	});



	$itemRowSet.find( '.item .item-photo img' ).each( function() {

		$( this ).get( 0 ).src = $( this ).attr( 'src' );

	});



	if ( $.browser.msie && $.browser.version < 7 ) {



		// резиновые тени от фотографий и подписей под ними



		$itemRowSet.find( '.ip-r, .ii-r' ).each( function() {

			var

				top = parseInt( $( this ).css( 'top' ) ),

				bottom = parseInt( $( this ).css( 'bottom' ) ),

				parentHeight = $( this ).parent().outerHeight(),

				height = parentHeight - top - bottom;



			$( this ).height( height );

		});



		$itemRowSet.find( '.ip-b, .ii-b' ).each( function() {

			var

				left = parseInt( $( this ).css( 'left' ) ),

				right = parseInt( $( this ).css( 'right' ) ),

				parentWidth = $( this ).parent().outerWidth(),

				width = parentWidth - left - right;



			$( this ).width( width );

		});



	}



	// слайдер превью



	if ( $( '.slider' ).length )

		$( '.slider' ).jCarouselLite({

			speed: sliderSpeed,

			visible: 4,

			circular: false,

			easing: "jswing",

			btnPrev: "#sbLeft",

			btnNext: "#sbRight",

			beforeStart: function() {

				$( '.slider-protection' ).addClass( 'sp-active' );

				setTimeout( function() {

					$( '.slider-protection' ).removeClass( 'sp-active' );

				}, sliderSpeed * 2 );

			}

		});



}



function setCarousel( $obj, count )

{// запускает карусель в объекте $obj с количеством видимых элементов равным count



	$obj.each(function(){

		var left = $(this).parent().siblings(".left-slider-btn").attr("id");

		var right = $(this).parent().siblings(".right-slider-btn").attr("id");

	});

}



function needNewItems()

{// возвращает true, если на экране отображается нижняя граница каталога, т.е. требуется подгрузка новых товаров



	return ( autoLoadMutex &&

	         $( document ).scrollTop() + screenHeight() > $( '.catalog' ).offset().top + $( '.catalog' ).height() + 50 &&

		     $( '.autoloading .item-row' ).length != $( '.autoloading .item-row-visible' ) );



}



function loadItems( n )

{// подгружает n рядов товаров в каталог



	$hiddenItemRows = $( '.autoloading .item-row' ).not( '.item-row-visible' );



	if ( $hiddenItemRows.length ) {



		$( '.loader' ).addClass( 'loader-visible' );



		setTimeout( function() {



			var $newItemRows = $();

			if ( $hiddenItemRows.length <= itemRowLoadingCount )

				$newItemRows = $hiddenItemRows;

			else

				for ( var i = 1; i <= itemRowLoadingCount; i++ )

					$newItemRows = $newItemRows.add( $hiddenItemRows.eq( i - 1 ) );



			$newItemRows.addClass( 'item-row-visible' );



			$( '.loader' ).removeClass( 'loader-visible' );



			autoLoadMutex = true;



			if ( needNewItems() )

				loadItems( n );



		}, catalogLoadingSpeed );

	}

}





function makeHover( object, className )

{// добавляет к объекту класс при наведении мыши



	$( '' + object ).hover(

		function(){

			$( this ).addClass( className );

		},

		function(){

			$( this ).removeClass( className );

		}

	);

}


