/*
	Name: common.js
	Site: bmw-baltauto.ru
	Autor: P1RATE
	Date: 14/04/2011
*/

$(function(){
/* добавляем тени */
/* 	$('.shadowbox').each(function(){
		var _html = $(this).html();
		$(this).html('<div class="sl"><div class="sr"><div class="st"></div><div class="sw">'+ _html +'</div><div class="sb"></div><div class="sc"></div></div></div>')
	}); */

	$('.shadowbox').wrap('<div class="shadowboxWrap"></div>');

/* узнаем высоту первых трех тизеров на главной */
	_newsHeight = $('#moreNewsSlider .tizer, #otherNewsSlider .tizer').map(function(){
		return $(this).outerHeight(true);
	}).get();

 	$('#moreNews').toggle(
		function(){$('#moreNewsSlider').animate({marginTop: '-'+ (_newsHeight[0]+_newsHeight[1]+_newsHeight[2]) +'px'}, 200, 'linear');},
		function(){$('#moreNewsSlider').animate({marginTop: '0px'}, 200, 'linear');}
	);

	$('#otherNews').toggle(
		function(){$('#otherNewsSlider').animate({marginTop: '-'+ (_newsHeight[6]+_newsHeight[7]+_newsHeight[8]) +'px'}, 200, 'linear');},
		function(){$('#otherNewsSlider').animate({marginTop: '0px'}, 200, 'linear');}
	);

/* смена изображений на главной */
	if(!$('.slider').length){
		//большие
/* 		var	currentBig = 1;

		$('.big .skip').html(currentBig +' / '+ $('.big div').length);

		flashArray = $('#flashOnMain > div').map(function(){
			return $(this).html();
		}).get();

		console.log(flashArray);

 		$('#flashOnMain > div').each(function(){
			$(this).html('');
		});

		$('#flashOnMain > div:first').html(flashArray[0]);

		$('.big .skip').click(function(){
			$('.big div').hide();
			currentBig += 1;
			if (currentBig > $('.big div').length) {currentBig = 1;};

				$('.big div:nth-child('+ currentBig +')').html(flashArray[currentBig]);
				$('.big div:nth-child('+ currentBig +')').show();
				$('.big .skip').html(currentBig +' / '+ $('.big div').length);

			return false;
		}); */

		//маленькие
		var currentSmall = 1;

		$('.small .skip').html(currentSmall +' / '+ $('.small div').length);

		$('.small .skip').click(function(){
			$('.small div').hide();
			currentSmall += 1;
			if (currentSmall > $('.small div').length) {currentSmall = 1;};
			$('.small div:nth-child('+ currentSmall +')').show();
			$('.small .skip').html(currentSmall +' / '+ $('.small div').length);

			return false;
		});
	};

/* select на главной */
	$('.select .active').toggle(
		function(){$('.select .options').show();},
		function(){$('.select .options').hide();}
	);

/* меню (слева) */

	menuShow();

 	function menuShow(){
		$('.main ul a').each(function(){
			if ($(this).hasClass('open')) {
				$(this).next('ul').css({'display': 'block'});
			};
		});
	};

	$('.main ul a').click(function(){
		if ($(this).next('ul').length) {

			if ($(this).next('ul').css('display') == 'block') {

				$(this).next('ul').css({'display': 'none'});

			} else {
				$(this).parent('li').prevAll('li').find('ul').css({'display': 'none'});
				$(this).parent('li').nextAll('li').find('ul').css({'display': 'none'});
				$(this).next('ul').css({'display': 'block'});
			};

			return false;
		};
	});

 	$('.hold').click(function(){
		if ($('.main ul a').length) {
			if($(this).find('div').hasClass('up')) {
				$(this).find('div').removeClass('up').addClass('down');
				$('.left-menu .main > ul').slideUp(200);
			} else {
				$(this).find('div').removeClass('down').addClass('up');
				$('.left-menu .main > ul').slideDown(200);
			};
		};
	});

/* slider */
	if($('#getImages').length){

		$('.image *').remove();
		$('.image').addClass('slider').removeAttr('style');
		$('#getImages div').appendTo('.image');
 		$('#getImages').remove();
		$('#content h1').remove();
		$('#content').addClass('sliderText');
		$('.slider').wrapInner('<div class="wrapper"><span></span></div>').append('<ins class="minis"></ins><span class="transparent"></span>');

		$('.slider .wrapper div').each(function(){
			var	_src = $(this).find('img').attr('src').match('(.*)\/');
			$(this).closest('.wrapper').next('ins').append('<span><img src="'+ _src[1] +'/'+ $(this).index() +'s.jpg" alt="" /></span>');
		});

 		$('.minis span').each(function(){
			$(this).css({left: 33 * $(this).index() + 'px'});
		});

		$('.minis span:first').addClass('active');
		$('.slider .wrapper span').prepend('<ins></ins>').append('<del></del>');
		$('.slider .wrapper div:first img').clone().appendTo('.slider .wrapper span del');
		$('.slider .wrapper div:last img').clone().prependTo('.slider .wrapper span ins');

		$('.sliderText > span').each(function(){
			var
				_nextHeader = $(this).next().find('h3').text(),
				_prevHeader = $(this).prev().find('h3').text();

			if($(this).index() != $('.minis span').length - 1) {
				$(this).append('<p><a href="#" class="link" id="next">Далее: '+ _nextHeader +'</a></p>');
			};
				$(this).append('<p><a href="#" class="link" id="prev">Назад: '+ _prevHeader +'</a></p>');
				$(this).append('<p class="pages">Страница '+ ($(this).index()+1) +' из '+ $('.minis span').length +'</p>');
		});

		_currentSpan = 1;
		_currentPos = -211;
		_currentSpanWrapper = 0;

		function spanToggle(){
			$('.sliderText span').hide();
			$('.sliderText span:nth-child('+ _currentSpan +')').show();
			$('.minis span').removeClass('active');
			$('.minis span:nth-child('+ _currentSpan +')').addClass('active');
			$('.slider .wrapper span').animate({left: _currentPos-528 * _currentSpanWrapper + 'px'}, 300, 'linear');
		};

		$('.minis span').live('click', function(){
			_currentSpan = $(this).index() + 1;
			_currentSpanWrapper = $(this).index();
			spanToggle();
		});

		$('#next').live('click', function(){
			_currentSpan += 1;
			_currentSpanWrapper += 1;
			spanToggle();
		});

		$('#prev').live('click', function(){
			_currentSpan -= 1;
			_currentSpanWrapper -= 1;
			spanToggle();
		});
	};

/* wallpaper */
	if($('.wallpaper').length){

		_class = $('#content').attr('class');

		function hideWallpaper(){
			$('.left-menu .main > ul').slideUp(200);
			$('.wallpaper').prev('p').hide().prev('h2').hide();
			$('.image div').hide();
			$('.image').css({minHeight: '0'});
			$('#content').removeAttr('class');
			$('#content').prev('div').hide().prev('div').hide();
			$('.wallpaper').hide();
		};

		function showWallpaper(){
			$('.left-menu .main > ul').slideDown(200);
			$('.wallpaper').prev('p').show().prev('h2').show();
			$('.image div').show();
			$('.image').css({minHeight: '27px'});
			$('#content').addClass(_class);
			$('#content').prev('div').show().prev('div').show();
			$('.wallpaper').show();
		};

		function wallpaperNavigation(){
			$('#content').append('<div class="wallpaperNavigation"></div>');
			$('.wallpaperNavigation').append('<p><a class="link" id="nextWallpaper" href="#">Следующее изображение</a></p><p><a class="link" id="prevWallpaper" href="#">Предыдущее изображение</a></p><a class="link"  id="showWallpaper" href="#">Вернуться в галерею</a><p><img width="189" height="1" src="/i/1x1_afafaf.gif" alt="" /></p><a class="link" id="downloadWallpaper" href="#">Сохранить</a>');
		};

		function wallpaperNavigationMeta(){
			$('#content').append('<img class="currentWallpaper" src="/images/gallery/big/b'+ _srcWallpaper[_currentWallpaper] +'.jpg" alt="" />');
			$('#downloadWallpaper').attr('href', '/images/gallery/big/b'+ _srcWallpaper[_currentWallpaper]+ '.jpg');
		};

		wallpaperNavigation();

		$('.wallpaperNavigation').hide();

		_srcWallpaper = $('.wallpaperItem').map(function(){
			return $(this).find('img').attr('src').match('\[0-9]+');
		}).get();

		_totalWallpaper = $('.wallpaperItem').length - 1;

		$('.wallpaperItem').each(function(i){
			$(this).find('img').wrap('<div class="wallpaperImg"></div>');
			$(this).find('.wallpaperImg').append('<span class="zoom"></span>');
			$(this).append('<a id="saveWallpaper" href="#" class="link">Сохранить</a>');
			$(this).find('#saveWallpaper').attr('href', '/images/gallery/big/b'+ _srcWallpaper[i]+ '.jpg');

			$(this).click(function(){
				hideWallpaper();
				_currentWallpaper = $(this).index();
				$('.wallpaperNavigation').show();
				wallpaperNavigationMeta();

				return false;
			});

		});

		$('#showWallpaper').live('click', function(){
			showWallpaper();
			$('.wallpaperNavigation').hide();
			$('.currentWallpaper').remove();

			return false;
		});

		$('#nextWallpaper').live('click', function(){
			if(_currentWallpaper >= _totalWallpaper) {
				_currentWallpaper = _totalWallpaper;
			} else {
				_currentWallpaper += 1;
				$('.currentWallpaper').remove();
				wallpaperNavigationMeta();
			};
			return false;
		});

		$('#prevWallpaper').live('click', function(){
			if(_currentWallpaper <= 0) {
				_currentWallpaper <= 0
			} else {
				_currentWallpaper -= 1;
				$('.currentWallpaper').remove();
				wallpaperNavigationMeta();
			};
			return false;
		});

	};

/* like summer (big slider) */
	if($('#getBigImages').length){

		$('.image').removeAttr('style').addClass('bigSplash');
		$('#getBigImages').addClass('bigMinis').appendTo('.image');

		_bigMinisSrc = $('.bigMinis img').attr('src').match('(.*)\/');

		$('.bigSlider del').each(function(){
			$(this).wrapInner('<div class="carInfo"></div>');
			$(this).append('<img src="'+ _bigMinisSrc[1] +'/'+ $(this).index() +'.jpg" alt="" />');
			$(this).append('<div class="close"></div>');
		});

		$('.close').live('click', function(){
			$('.bigSlider del').hide();
			$('.bigMinis div').removeClass('active');
		});

		$('.bigMinis div').each(function(){
			$(this).click(function(){
				$('.bigSlider del').hide();
				$('.bigSlider del:nth-child('+ ($(this).index()+1) +')').show();
				$('.bigMinis div').removeClass('active');
				$(this).addClass('active');
			});
		});
	};

/* разделы с новым дизайном */
//слайдер контента
	$('#section .text a.more').toggle(
		function(){
			$(this).hide();
			$('.wrap').slideUp(400, function(){
				$('.hide').slideDown(400, function(){
					$('#section .text a.more').text('Закрыть').show();
				});
			});
		},
		function(){
			$(this).hide();
			$('.hide').slideUp(400, function(){
				$('.wrap').slideDown(400, function(){
					$('#section .text a.more').text('Больше').show();
				});
			});
		}
	);

//галерея (zoom hint)
  $('#gallery li').each(function(){

		$(this).append('<span class="zoom-hint">Увеличить</span>');

		$(this).mousemove(function(e){
			oT = $(this).offset().top;
			oL = $(this).offset().left;
			x = e.pageX-oL-10;
			y = e.pageY-oT-38;
			$(this).find('.zoom-hint').css('top', y).css('left', x);
		});

		$(this).mouseover(function(){
			$(this).find('.zoom-hint').show();
		});

		$(this).mouseout(function(){
			$(this).find('.zoom-hint').hide();
		});

	});

//slideshow
	if ($('#slideshow').length) {
		$('#slideshow .slideshowItem').cycle({
			timeout: 4000,
			fx: 'fade',
			next: '#next',
			prev: '#prev',
			after: onAfter
		});

		$('#pause').click(function(){
			if ($(this).hasClass('pause')) {
				$('#slideshow .slideshowItem').cycle('pause');
				$(this).attr('class', 'play');
			} else {
				$('#slideshow .slideshowItem').cycle('resume', true);
				$(this).attr('class', 'pause');
			};
		});

		$('#slideshow').hover(
			function(){
				$('#controls').animate({bottom: '0px'});
			},
			function(){
				$('#controls').animate({bottom: '-25px'});
			}
		);
	};

/* fancybox */
	if ($('#gallery').length) {
		$('#gallery a[rel="gallery"]').fancybox({
			'padding': 11,
			'cyclic': true,
			'showCloseButton': true,
			'overlayColor': '#000',
			'overlayOpacity': 0.45,
			'speedIn': 200,
			'speedOut': 200,
			'changeSpeed': 200,
			'changeFade': 0,
			'transitionIn': 'fade',
			'transitionOut': 'fade',
			'titlePosition': 'outside',
			'titleFormat': function (){
        var self = this.orig;
        var folder = $(self).attr('data-folder');
        var standart = $(self).attr('data-standart');
        var wide = $(self).attr('data-wide');
				return wall(folder, standart, wide);
			}
		});
	} else {
		$('.galleryItem a[rel="gallery"]').fancybox({
			'padding': 11,
			'cyclic': true,
			'showCloseButton': true,
			'overlayColor': '#000',
			'overlayOpacity': 0.45,
			'speedIn': 200,
			'speedOut': 200,
			'changeSpeed': 200,
			'changeFade': 0,
			'transitionIn': 'fade',
			'transitionOut': 'fade'
		});
	};

/* selectList */
	var
		selectListText = $('.datasheetSelectList a[data-select="selected"]').text(),
		selectDropOpened = false;

	$('.datasheetSelectName').text(selectListText);

	$('.datasheetSelect').click(function(){
		if (selectDropOpened == false) {
			$('.datasheetSelectList').show({duration:1, complete: function(){
				selectDropOpened = true;
			}});
		} else {
			$('.datasheetSelectList').hide({duration:1, complete: function(){
				selectDropOpened = false;
			}});
		};
	});

	$(document).click(function(){
		if (selectDropOpened) {
			$('.datasheetSelectList').hide({duration:1, complete: function(){
				selectDropOpened = false;
			}});
		};
	});
	
	dataSheetNumber = 0;
	
	$('.datasheetSelectList a').click(function(){
		if ($('.technicalDetailsImageBig').css('display') == 'none') {
			$('.datasheetSelectList a').removeAttr('data-selected');
			$(this).attr('data-selected', 'selected');
			$('.datasheetSelectName').text($(this).text());
			dataSheetNumber = $(this).index();
			$('.dataSheetItem').hide();
			$('.dataSheetItem:eq('+ dataSheetNumber +')').show();
		};
	});
	
	$('.dataSheetItem').hide();
	$('.dataSheetItem:first').show();
	
}); //$(function) end

/* technicalDetailsImage */
	function technicalDetailsImage() {
		if ($('.technicalDetailsImageSmall').css('display') == 'block') {
			$('.technicalDetailsImageBig').show();
			$('.technicalDetailsImageSmall, .technicalDetailsLink, .dataSheetItem, .technicalDetailsLinkCO2, .technicalDetailsPrint, .compareInfoBlock').hide();
		} else {
			$('.technicalDetailsImageBig').hide();
			$('.technicalDetailsImageSmall, .technicalDetailsLink, .dataSheetItem:eq('+ dataSheetNumber +'), .technicalDetailsLinkCO2, .technicalDetailsPrint').show();
		};
	};		

/* compareInfoBlock */	
	function compareInfoBlock() {
		if ($('.compareInfoBlock').css('display') == 'none') {
			$('.compareInfoBlock').css('display', 'block');
		} else {
			$('.compareInfoBlock').css('display', 'none');
		};
	};

/* print */
	function technicalDetailsPrint() {
		window.print();
	};
		
/* pupup */
	function popupShow(fuelText, name){
		if (!$('.popup').length) {
			$('#section .wrap').prepend('<div class="popup"><a onclick="popupHide()" class="closePopup"></a><h4>'+ name +'</h4><div>'+ fuelText +'</div></div>');
		};
	};

	function popupHide(){
		$('.popup').remove();
	};

/* slideshow */
	function onAfter(curr,next,opts) {
		var caption = (opts.currSlide + 1) + ' / ' + opts.slideCount;
		$('#number').html(caption);
	};

/* fancybox wallpaper */
	function wall(folder, standart, wide){
		return "<span id=\"fancybox-title-over\"><p>Загрузить</p><a class=\"link\" href=\""+ folder+standart +"\">Стандартный: 1600 x 1200</a><br><a class=\"link\" href=\""+ folder+wide +"\">Широкоэкранный: 1920 x 1200</a></span>";
	};

/* Форма узнайте первым */
	function knowFirstShow(){
		$('.knowFirst').show();
	};

	function knowFirstClose(){
		$('.knowFirst').hide();
	};

//fun
$(function(){

	f = true;

	$(document).keydown(function(k){
		if (k.ctrlKey && k.keyCode == 192) {
			if (f) {

				$('body').append('<div class="score" style="position:fixed; z-index:99999; top:0; right:0; background:#0044cc; color:#fff; text-aling:right; padding:5px;">Очков: 0</div>');
				$('*').css({cursor: 'default'});

				score = 0;

				$('body *').mouseover(function(){
						$(this).click(function(){
							if($(this).hasClass('score')){
								return false;
							} else {
								$(this).fadeOut({duration: 100});
								score += 10;
								$('.score').html('Очков: '+ score);
								return false;
							};
						});

				});
				return false;
			} else {
				f = true;
			};
		};
	});

});
