
/**
 * slider-block.js
 * Copyright 2011 Konstantin Kachurenko
 * Design studio "SOLASS"
 */
 
(function($){

	$( document ).ready( function(){

		if ( $( '#product-slider-block' ).length ) {

			/* Интервал автоматического переключения слайдов */
			var AutoslideInterval = 7000;
			
			/* Высота блока с картинкой */
			var FotoblockHeight = 342;
			
			var IE = !jQuery.support.opacity;
			var $slides = $( '#product-slider-list .slide' );
			var $sliderBlock = $( '#product-slider' );
			
			/* Если слайды есть */
			if ( $slides.length ) {
				
				var $htmlBlock = $sliderBlock.children( '.slider-html' ).eq(0);
				var $fotoBlock = $sliderBlock.children( '.slider-foto' ).eq(0);

				var $firstBlockHTML = $slides.eq(0).children( '.slider-html' ).eq(0);
				var $firstBlockFOTO = $slides.eq(0).children( '.slider-foto' ).eq(0);

				var $fotoBg = $( '#product-slider-fotoBg' );
				var $fotoImg = $( '#product-slider-fotoImg' );

				var $newIMG = $( document.createElement( 'IMG' ) );
				var activeSlide = 0;
				var Autoslide = 0;
				
				$fotoImg.css({ 'opacity': 0 });
				$fotoImg.append( $( document.createElement( 'DIV' ) ).attr( 'id', 'product-slider-preloader' ) )

				/* Функция смены слайда */
				var changeSlide = function( next ) {

					// подготовка нового изображения для загрузки,
					// остановка автопереключения слайдов,
					// отображение предзагрузчика
					clearTimeout( Autoslide );
					$preloader.css( 'display', 'block' );
					$newIMG.unbind( 'load' );
					$newIMG = $( document.createElement( 'IMG' ) );

					// определение "направления" листания
					if ( typeof next === 'undefined' ) {
						next = ( activeSlide + 1 >= $slides.length )? 0: activeSlide + 1;
					} else if ( next < 0 ) {
						next = ( activeSlide - 1 < 0 )? $slides.length - 1: activeSlide - 1;
					}
					var $nextHtml = $slides.eq( next ).children( '.slider-html' ).eq(0);

					// обработчик загрузки следующего изображения
					$newIMG.bind( 'load', function(e) {
						var $this = $( this );
						var $navPagesLinks = $sliderPagesBlock.children( 'a' );

						// установка активного пункта "постраничной" навигации
						$navPagesLinks.removeClass( 'active' ).filter( function( i ){
							if ( $( $navPagesLinks.eq( i ) ).data( 'slide' ) == next ) { return true; }
							return false;
						}).addClass( 'active' );

						// скрытие предзагрузчика
						$preloader.css( 'display', 'none' );

						// анимация смены изображения
						$fotoBg.css({ 'background-image': 'url('+$this.attr( 'src' )+')' });
						$fotoImg.stop().animate({
							'opacity': 0
						}, 500, function() {
							// замена ссылки на изображении
							$fotoImg.attr( 'href', $nextHtml.find( 'h2 > a' ).eq(0).attr( 'href' ) )
							// подстановка background-image на его постоянное место
							$fotoImg.css({ 
								'background-image': 'url('+$this.attr( 'src' )+')', 
								'opacity': 1
							});
						});

						// анимация HTML-блока
						$htmlBlock.stop().animate({
							'opacity': 0
						}, 250, function(){
							var height = $htmlBlock.outerHeight();
							$htmlBlock.css( 'height', height+'px' ).html( $nextHtml.html() );
							$htmlBlock.animate({
								'opacity': 1,
								'height': $fotoBlock.outerHeight()+'px'
							}, 250 );
						});

						// запуск автозагрузки следующего слайда
						clearTimeout( Autoslide );
						Autoslide = setTimeout( function(){
							changeSlide( undefined );
						}, AutoslideInterval );
					});

					// установка маркера "активный слайд"
					activeSlide = next;

					// старт загрузки следующего изображения
					$newIMG.attr( 'src', $slides.eq( next ).children( '.slider-foto' ).eq(0).children('a').eq(0).attr( 'href' ) );
					return false;
				}

				var $preloader = $( '#product-slider-preloader' );
				var $sliderPagesBlock = $( '#product-slider-pages' );

				var _NavHeight = parseInt( $( '#product-slider-fotoNav' ).outerHeight() );
				var _minHeight = ( FotoblockHeight > 0 )? (FotoblockHeight+_NavHeight): (parseInt( $firstBlockFOTO.css( 'min-height' ) )+_NavHeight);

				// обработчик загрузки ПЕРВОГО изображения:
				// подготовка и отображение самого слайдера
				$newIMG.one( 'load', function(e) {
					$fotoImg.attr( 'href', $firstBlockHTML.find( 'h2 > a' ).eq(0).attr( 'href' ) )
					$fotoImg.css( 'background-image', 'url('+$( this ).attr( 'src' )+')' );
					$preloader.hide();
					$fotoBlock.css({
						'width': ( parseInt( this.width )+'px' ),
					});
					$fotoImg.css({ 'opacity': 1, 'height': ( ( FotoblockHeight > 0 )? FotoblockHeight: parseInt( this.height ) )+'px' });
					$fotoBg.animate({
						'opacity': 1, 
						'height': ( ( FotoblockHeight > 0 )? FotoblockHeight: parseInt( this.height ) )+'px'
					}, 300, function() {

						// Если слайдов больше чем один, добавляем элементы навигации по слайдам
						if ( $slides.length > 1 ) {

							// подготовка и отображение линейки "постраничной" навигации
							$slides.each( function( i, elem ) {
								var pagesLink = $( document.createElement( 'a' ) ).attr( 'href', '#' );
								pagesLink.data( 'slide', i ).addClass( i==0? 'active': '' ).appendTo( $sliderPagesBlock );
							});
							var $pages = $sliderPagesBlock.children( 'a' );
							$sliderPagesBlock.css( 'width', ( $pages.eq(0).outerWidth( true ) * parseInt( $pages.length ) )+'px' );
							$pages.each( function( i, elem ) {
								$( elem ).bind( 'click', function( e ){
									return changeSlide( $( this ).data( 'slide' ) );
								});
							});

							// подготовка и отображение навигации "влево/вправо"
							$fotoBlock.append( $( document.createElement( 'span' ) ).attr( 'id', 'product-slider-navleft' ) );
							$fotoBlock.append( $( document.createElement( 'span' ) ).attr( 'id', 'product-slider-navright' ) );
							$( '#product-slider-navleft' ).show( IE? 0: 200 ).bind( 'click', function(){
								changeSlide( -1 );
							});
							$( '#product-slider-navright' ).show( IE? 0: 200 ).bind( 'click', function(){
								changeSlide( undefined );
							});
							$( '#product-slider-navleft' ).add( $( '#product-slider-navright' ) ).one( 'mouseenter', function( e ){
								clearTimeout( leftRightHideTimeout );
							});
							var leftRightHideTimeout = setTimeout( function(){
								$( '#product-slider-navleft' ).hide( IE? 0: 300 );
								$( '#product-slider-navright' ).hide( IE? 0: 300 );
							}, 3000 );

							// подготовка и отображение навигации "влево/вправо"
							$fotoImg.bind({
								'mouseenter': function( e ) {
									clearTimeout( leftRightHideTimeout );
									$( '#product-slider-navleft:hidden' ).show( IE? 0: 200 );
									$( '#product-slider-navright:hidden' ).show( IE? 0: 200 );
								},
								'mouseleave': function( e ) {
									if ( e.relatedTarget === document.getElementById( 'product-slider-navleft' ) || e.relatedTarget === document.getElementById( 'product-slider-navright' ) ) {
										$( e.relatedTarget ).one( 'mouseleave', function( e ){
											if ( e.relatedTarget !== $fotoImg.get(0) ) {
												$( '#product-slider-navleft:visible' ).hide( IE? 0: 200 );
												$( '#product-slider-navright:visible' ).hide( IE? 0: 200 );
											}
										});
									} else {
										$( '#product-slider-navleft:visible' ).hide( IE? 0: 200 );
										$( '#product-slider-navright:visible' ).hide( IE? 0: 200 );
									}
								}
							});
						}
					});
					$htmlBlock.css({ 'height': ( ( FotoblockHeight > 0 )? FotoblockHeight: parseInt( this.height ) )+_NavHeight+'px' });
					clearTimeout( Autoslide );
					Autoslide = setTimeout( function(){
						changeSlide( undefined );
					}, AutoslideInterval );
					$sliderBlock.bind({
						'mouseenter': function( e ) {
							clearTimeout( Autoslide );
						},
						'mouseleave': function( e ) {
							clearTimeout( Autoslide );
							Autoslide = setTimeout( function(){
								changeSlide( undefined );
							}, Math.floor( parseInt( AutoslideInterval / 2 ) ) );
						}
					})
				});
				
				$htmlBlock.css({ 'height': _minHeight+'px' });
				$htmlBlock.append( $firstBlockHTML.html() );
				$preloader.css({
					'left': parseInt( ( $fotoBlock.outerWidth() / 2 ) - ( $preloader.outerWidth() / 2 ) ),
					'top': parseInt( ( _minHeight / 2 ) - ( $preloader.outerHeight() / 2 ) ),
					'display': 'block'
				});
				$htmlBlock.css( 'opacity', 0 );
				$fotoBlock.css({
					'opacity': 0,
					'min-height': 0,
					'height': '1px'
				}).animate({
					'opacity': 1,
					'height': _minHeight+'px'
				}, 500 );

				// СТАРТ загрузки ПЕРВОГО изображения:
				$newIMG.attr( 'src', $firstBlockFOTO.children( 'a' ).eq(0).attr( 'href' ) );

				// Отображение блока слайдера
				$sliderBlock.css( 'display', 'block' );
				$htmlBlock.animate({
					'opacity': 1
				}, 1000 );
			}
		}
	});
	
})(jQuery);
