// Плагин для карусели ***************************************************************
( function(){
	$.fn.dekkyInfiniteCarousel = function(){
		function repeat(str, n){
			return new Array(n+1).join(str);
		}
	
		return this.each( function(){
			var $wrapper = $('> div', this).css('overflow','hidden'),
				$slider = $wrapper.find('> ul').css('width','9999px'),
				$items = $slider.find('> li'),
				$single = $items.filter(':first'),
				
				singleWidth = $single.outerWidth(true),
				visible = Math.ceil($wrapper.innerWidth() / singleWidth ),
				currentPage = 1,
				pages = Math.ceil($items.length / visible);
				
				//console.log(singleWidth);
				//console.log(visible);
				//console.log(pages);
				
			if ( $items.length % visible != 0 ){
				$slider.append( repeat('<li class="empty" />', visible-($items.length % visible)) );
				$items = $slider.find('> li');
			}
			
			$items.filter(':first').before( $items.slice(-visible).clone().addClass('cloned') );
			$items.filter(':last').after( $items.slice(0,visible).clone().addClass('cloned') );
			$items = $slider.find('> li');
			
			$wrapper.scrollLeft(singleWidth * visible);
			
			function gotoPage(page){
				var dir = page < currentPage ? -1 : 1,
					n = Math.abs(currentPage - page),
					left = singleWidth * dir * visible * n;
					
				$wrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
				}, 500, function() {
					if ( page > pages ) {
						$wrapper.scrollLeft(singleWidth * visible);
						page = 1;
					} else if (page == 0) {
						page = pages;
						$wrapper.scrollLeft(singleWidth * visible * pages);
					}
					currentPage = page;
				});
			}
			
			$wrapper.after('<a href="#" class="arrow back" title="НАЗАД">&lt;</a><a href="#" class="arrow forward" title="ВПЕРЕД">&lt;</a>');
			
			$('a.back',this).click(function(){
				gotoPage(currentPage-1);
				return false;
			});
			$('a.forward',this).click(function(){
				gotoPage(currentPage+1);
				return false;
			});
			
			$(this).bind('goto', function(event, page) {
				gotoPage(page)
			});
			
			$(this).bind('next', function(){
				gotoPage(currentPage + 1);
			});
		});
	};
})(jQuery);

$(function() {  
	// Различные переменные для скриптов
	var searchFocus;	// Перменная-флаг поля searchstring (есть ли фокус у этого поля)

    // Увеличиваем центральную картинку с девушкой на весь экран ***************************************************************
    var bgImg = new Image(),
    	theWindow        = $(window),
        $bg,
        aspectRatio;
    
    function resizeBg() {
    	if ( (theWindow.width() / theWindow.height() ) < aspectRatio ) 	
		{
        	$bg.removeClass().addClass('bgheight');
        } else 
		{
            $bg.removeClass().addClass('bgwidth');
        }
    }    
    
    $(bgImg).load(function(){
    	$bg = $(this);
        aspectRatio = this.width / this.height;
        
        if ( (theWindow.width() / theWindow.height()) < aspectRatio ) 	
		{
        	$(this).removeClass().addClass('bgheight');
        } else 
		{
            $(this).removeClass().addClass('bgwidth');
        }
        
    	$('#fullscr-bg').append(bgImg);
    	$('body').css('background','transparent');
    	
    	theWindow.resize(function() {
       		resizeBg();
    	}).trigger("resize");
    }).attr({
    	'src': 'img/girl.jpg',
    	'id': 'fullscr-img'
    }); 
           
    // Убираем текст с поля поиска при первом фокусе на него и анимируем ********************************************
    $('.top-search').css({'opacity':'0.5'});
    $('.top-search').hover( function(){
        	$(this).animate({'opacity':'1'},500);
    	},
        function(){
        	if ( searchFocus == false )
            	$(this).animate({'opacity':'0.5'},500);
        }
    );
    $('.top-search input[name=searchstring]').focusin( function(){
       if ( $(this).attr('value') == 'Введите запрос для поиска...' )
            $(this).attr('value','');
       $(this).animate({'opacity':'1'},500);
       searchFocus = true;
    });
    $('.top-search input[name=searchstring]').focusout( function(){
       if ( $(this).attr('value') == '' )
            $(this).attr('value','Введите запрос для поиска...');
       $(this).animate({'opacity':'0.5'},500);
       searchFocus = false;
    });
    
    // Оформляем левое меню на главной странице	***************************************************************
    $('.home-left-menu > ul > li:odd').addClass('odd');
    $('.home-left-menu > ul > li:even').addClass('even');
    
    // Форма "Войти" с кнопкой ***************************************************************
    $('#overflow').click( function(){
           $('#login-btn').removeClass('expand');
           $(this).css({
               'display': 'none'
           });
           $('#login-form').fadeOut('fast');
    });
    $('#login-btn').click( function(){
        if ( $(this).hasClass('expand') ) {
           $(this).removeClass('expand');
           $('#overflow').css({
               'display': 'none'
           });
           $('#login-form').fadeOut('fast');
        }
        else {
            $(this).addClass('expand');
            $('#login-form').fadeIn('fast').css({
            	'display': 'inline'
            });
            $('#overflow').css({
               'display': 'block',
               'height': $(document).height(),
               'width': $(document).width()
            }); 
        }
    });
    
	// Слайдер на главной странице ***************************************************************
	var index = 0;
	var images = $("#gallery a");
	var thumbs = $("#thumbs img");
	var imgHeight = thumbs.attr("height");
	thumbs.slice(0,3).clone().appendTo("#thumbs");
	for (i=0; i<thumbs.length; i++)
	{
		$(thumbs[i]).addClass("thumb-"+i);
		$(images[i]).addClass("image-"+i);
	}

	$("#next").click(sift);
	show(index);
	setInterval(sift, 8000);

	function sift()
	{
		if (index<(thumbs.length-1)){index+=1 ; }
		else {index=0}
		show (index);
		return false;
	}

	function show(num)
	{
		images.fadeOut(400);
		$(".image-"+num).stop().fadeIn(400);
		var scrollPos = (num+1)*imgHeight;
		$("#thumbs").stop().animate({scrollTop: scrollPos}, 400);
	}
	
	// Раскрывающееся меню товаров ***************************************************************
	var $items = $('.left-menu li.ischild'),
		level = 2;
	
	$items.each( function(){
		var catID = $(this).attr('rel'),
			$item = $(this);
			
		$(this).find('div > div').each( function(){
			$(this).click(function(){
				var $divItem = $(this);
				// 1. Проверяем раскрыт список или нет
				if ( $(this).hasClass('down-cat') ){
					// 2. Список не раскрыт, проверяем загруженны или нет данные
					if ( $item.has('ul').length == 0 )
					{
						// 3. Данные не загруженны, добавляем класс loader
						$(this).addClass('loader');
						// 4. Загружаем данные
						//console.log('index.php?ajax=yes&level=' + level + '&menu=' + catID);
						$.get('index.php?ajax=yes&level=' + level + '&menu=' + catID, function(data){
							$item.append(data);
							$item.find('> ul').each( function(){
								$(this).hide();
								$(this).slideDown('fast');
							});
							$divItem.removeClass('loader down-cat');
							$divItem.addClass('up-cat');
						});
					}
					else{
						// 5. Список уже загружен
						$divItem.removeClass('down-cat');
						$divItem.addClass('up-cat');
						$item.find('> ul').each( function(){
								$(this).hide();
								$(this).slideDown('fast');
							});
					}
				}
				else {
					// 6. Список раскрыт, прячем его
					$item.find('> ul').each(function(){
						$(this).slideUp('fast');
					});
					$divItem.removeClass('up-cat').addClass('down-cat');
				}
			});
		});
	});
	
	// Запускаем слайдер на главной ***************************************************************
	$('#new-carousel').dekkyInfiniteCarousel().mouseover(function() {
		autoscrolling = false;
	}).mouseout(function(){
		autoscrolling = true;
	});
	// Автоматическая смена страниц
	var autoscrolling = true;
	
	setInterval( function(){
		if (autoscrolling){
			$('#new-carousel').trigger('next');
		};
	}, 3000);
	// TODO: Показываем дополнительную информацию при наведении на изображение товара
	
	// Наводим мышкой на товар в категории
	$('li.product-brief').each( function(){
		$(this).hover(function(){
			$(this).find('h3.product-title > a').each(function(){
				$(this).addClass('hovered');
			});
			$(this).find('p.additional-href > a').each(function(){
				$(this).addClass('hovered');
			});
		},
		function(){
			$(this).find('h3.product-title > a').each(function(){
				$(this).removeClass('hovered');
			});
			$(this).find('p.additional-href > a').each(function(){
				$(this).removeClass('hovered');
			})
		});
	});
	
	// prettyPhoto галерея для картинок товара
	$("a[rel^='prettyPhoto']").prettyPhoto({
		theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
		keyboard_shortcuts: false,
		allow_resize: false
	});
	
	// Загружаем большую картинку при наведении мышки на маленькую
	// TODO: Отобразить процесс загрузки новой картинки
	$('.small-imgs > li > a').each( function() {
		$(this).hover(function(){
			$('.big-img').attr('src', $(this).attr('href') );
		}, function(){
			return false;
		});
	});
	
	// Организуем навигацию по табам
	var tabContainers = $('div.tabs > div');
	tabContainers.hide().filter(':first').show();
	$('div.tabs ul.tab-navigation a').click( function(){
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		
		$('div.tabs ul.tab-navigation a.active').removeClass('active');
		$(this).addClass('active');
		
		return false;
	});
	
	// Блоки с товарами одинаковой ширины
	/*$('ul.products-grid').each( function() {
		var currentHeight = 0;
		$(this).find('li.grid').each( function() {
			if ( $(this).height() > currentHeight )
				currentHeight = $(this).height();
		});
		
		$(this).find('li.grid').each( function() {
			$(this).height(currentHeight);
		});
	});*/
	
	// Раскрывающиеся ответы на вопросы
	$('.feedback').each( function(){
		var question = $(this);
		$(this).find('p.question').click( function(){
			if( question.find('> div').css('display') == 'none' ) {
				question.find('> div').fadeIn('fast');
			} else {
				question.find('> div').fadeOut('fast');
			}
		});
	});
});
