$(document).ready(function(){

	var menu = $('#subMenu');
	menu.show();
	var menuHeight = menu.height();
	menu.hide();
	
	menu.mouseover(function(event){
		event.stopPropagation();
	});
	
	$('#menu').hover(function(){
		menu
		.css({
			'opacity' : 0,
			'height' : 0,
			'display' : 'block',
			'overflow' : 'hidden'
		})
		.animate({
			height : menuHeight + 'px',
			opacity : 1
		}, 400);
	}, function(){
		menu.animate({
			height : '0px',
			opacity : 0
		}, 400, function(){
			$(this).css('display', 'none');
		});
	});
	
	
	//index
	var path = '/photos/',
	urlPath = '/album/',
	curr = new Array();
	
	
	
	function hujator() {
		for(var z=1; z <= 9; z++) {
			var img = random(0, images.length-1);
			while(checkArr(curr, img)) {
				img = random(0, images.length-1);
			}
			$('#img'+z).attr('src', path + images[img][0]);	
			$('#img'+z).parent('a').attr('href', urlPath + images[img][1]);
			curr.push(img);
		}
	}

	var hujatorTimeout;
	function hujatorEngine() {
		clearTimeout(hujatorTimeout);
		var pause = random(2000,4000);
		var targetImg = random(1,9);
		var newImg = random(0, images.length-1);
		
		while(checkArr(curr, newImg)) {
			//console.log(checkArr(curr, newImg))
			newImg = random(0, images.length-1);
		}
		curr[targetImg - 1] = newImg;
		
		var targetImage = $('#img' + targetImg);

		var targetImageOp = 1;
		var tempImageOp = 0;
		
		var tempImg = new Image();		
		tempImg.src = path + images[newImg][0];
		tempImg.className = 'tempImg';
		tempImg.id = 'img' + targetImg;
		
		$(tempImg).load(function(){
			$(this).animate({'opacity' : 1}, 800);
		});
		
		$(targetImage).animate({'opacity' : 0}, 1200, function(){
			//$(this).attr('src', tempImg.src);
			$(this).remove();
			//$(this).css({'opacity' : 1});
			
			$(this).parent('a').attr('href', urlPath + images[newImg][1]);
		});
		
		$('#block' + targetImg).append(tempImg);
		
		hujatorTimeout = setTimeout(function(){hujatorEngine()}, pause);
	}
	
	function random(min, max) {
	  return Math.floor(Math.random() * (max - min + 1)) + min;
	}

	function checkArr(arr, val) {
		console.log(arguments);
		if (! arr.length) {
			return false;
		}
		if (val === undefined) return false;
		for (var z in arr) {
			if (parseInt(arr[z], 10) == parseInt(val, 10)) {
				return true;
			}
		}
		return false;
	}
	
	if ($('#hujator').length > 0) {
		$('#hujator img').each(function(){
			//console.log($(this))
			curr.push(parseInt($(this).attr('data-id'), 10));
		})
		//console.log(curr)
		setTimeout(function(){hujatorEngine()}, 2000);
	}
	
	var width =  $('body').width();
	var imagesPosition = new Array();
	var imagesWidth = new Array();
	var currentImage = 0;
			
	$(window).load(function () {
		if ($('#photoZone').length > 0) {
			
			Scroll.to(window,{'x':0,'y':0},500);
			
			$('#photoZone').show();
			$('#thumbnails').show();
			$('#preloader').hide();

			album_images = $('.bigPhoto');
			smallImages = $('.smallPhoto');
			imageRotator(); 
			window.onkeydown = function (e) {
				switch (e.keyCode) {
					case 39: switchImage(parseInt(currentImage)+1); return false; break;
					case 37: switchImage(parseInt(currentImage)-1); return false; break;
				}
			}	
			$('#breadcrumbs').bind('click', function(){
				switchImage(0);
				$(this).fadeOut(200);
				return false
			});
		}
	});
	
	/*
	if ($('#album-desc').length) {
		$('#album-desc').css({
			left : (($('h1#text').width() + 40) + 15) + 'px'
		})
	}
	*/
	
	function imageRotator() {
		if (album_images.length) {
			var left = parseInt(width / 2) - parseInt(album_images.find('img:first').width() / 2);
		
			var cnt = 0;
			album_images.each(function(){
			
				$(this).css('left' , left + 'px');
				imagesPosition.push(left);
				var divWidth = $(this).find('img:first').width();
				
				$(this).css({
					width : divWidth
				})
				
				imagesWidth.push(divWidth);
				left += divWidth+20;
				if (cnt == currentImage) {
					$(this).addClass('activeImage'); 
				} else {
					$(this).addClass('inActiveImage');
				}
				cnt ++;
			});
			
			album_images.find('a').bind('click', function(event){
				event.stopPropagation();
				return true
			});
			
			album_images.bind('click', function () {
				if ($(this).attr('id') != currentImage) {
					switchImage($(this).attr('id'));
				}
				return false; 
			});
				
			
			$('#photoZone').css({
				'width' : (left + $(album_images[album_images.length - 1]).width() / 2) +'px'
			});
		
		}
	
		cnt = 0;
		if (smallImages.length) {
			left = 0;
			var totalWidth = 0;
			
			smallImages.each(function(){
				$(this).css('left', left +'px');
				left += $(this).find('img:first').width()+1;
				totalWidth += parseInt($(this).width())+2;
				if (cnt == currentImage) {
					$(this).addClass('activeImage'); 
				} else {
					$(this).addClass('inActiveImage'); 
				}
				cnt ++;
			});
			smallImages.bind('click', function () {
				if ($(this).attr('rel') != currentImage) {
					switchImage($(this).attr('rel'));
				}
				return false; 
			});
			
			if (totalWidth < 1000) {
				var marginLeft = -1 * parseInt(totalWidth / 2);
				smallImages.parent().css({
					'width' : totalWidth+'px',
					'marginLeft' : marginLeft+'px'
				});
			}
			
		}
	}
	
	function animateScroll(settings) {
		//скрываем или открываем  стрелку
		if ( $('#breadcrumbs').is(':hidden') && parseInt(settings.scrollTo) !=  imagesPosition[0]) {
			$('#breadcrumbs').fadeIn(200);
		} else if ( $('#breadcrumbs').is(':visible') && parseInt(settings.scrollTo) ==  imagesPosition[0]) {
			$('#breadcrumbs').fadeOut(200);
		}
		Scroll.to(window,{'x':settings.scrollTo - settings.screenHalfSize,'y':0},500);
	}
	
	
	function switchImage(imgId) {
		if ((imgId > album_images.length - 1)||(imgId<0)) return;
		
		//прозрачность на маленькие картинки
		
		smallImages.removeClass('activeImage').removeClass('inActiveImage').addClass('inActiveImage');
		smallImages[imgId].className = 'smallPhoto activeImage';
					
		//прозрачность на большие картинки
		
		album_images.removeClass('activeImage').removeClass('inActiveImage').addClass('inActiveImage');
		album_images[imgId].className = 'bigPhoto activeImage';

		var screenHalfSize = parseInt((width - imagesWidth[imgId]) / 2);
				
		//запуск прокрутки
		var settings = {
			scrollTo:imagesPosition[imgId],
			screenHalfSize:screenHalfSize
		};
	
		
		
		//прокручиваем маленькие картинки на центр если они оказались слишком слева или справа
		var smallImgLeft = parseInt(smallImages[imgId].style.left);
		var smallImgContainer = $('#thumbnails');
		var smallImgContainerScroll = smallImgContainer.scrollLeft();
		var smallImgContainerWidth = smallImgContainer.width();
		
		
		if (smallImgContainerWidth - ((smallImgLeft - smallImgContainerScroll)) < 150) {
			smallImgContainer.scrollLeft((smallImgContainerScroll / 2) + (smallImgLeft / 2));
		}
		
		if (smallImgLeft <= smallImgContainerScroll + 100) {
			smallImgContainer.scrollLeft(smallImgLeft - (smallImgContainerWidth / 2));
		}
		
			
		
		$(album_images[imgId]).css('opacity', 1);
		$(album_images[currentImage]).animate({'opacity' : 0.7}, 200);		
		animateScroll(settings);
		currentImage = imgId;
	}
	
	$('#black-brick').bind('click', function(){
		$('body').addClass('inBlack');
		$('#breadcrumbs img').attr('src', '/images/al3-white.png');
		$.cookie('bgColor', 'black', { expires: 30 });
		return false
	});
	
	$('#white-brick').bind('click', function(){
		$('body').removeClass('inBlack');
		$('#breadcrumbs img').attr('src', '/images/al3-white.png')
		$.cookie('bgColor', null);
		return false
	});
	
});

	Scroll = {
		sL:function(o){return o!=window?o.scrollLeft:document.body.scrollLeft||document.documentElement.scrollLeft},
		sT:function(o){return o!=window?o.scrollTop:document.body.scrollTop||document.documentElement.scrollTop},
		anim:function(p){function d(p){return Math.pow(p,3)};if(p<0.5){return d(2*p)/2;}else{return (2-d(2*(1-p)))/2;}}, // рассчет анимации
		animator:[], /* массив с анимируемыми объектами */
		anielems:0, /* счетчик анимируемых объектов */
		to: function(obj,values,time,callback){
			// перебираем параметры и значения
			for(key in values){anima(key,values[key])}
			function anima(param,to){
				// проверяем и останавливаем предыдущие анимации
				for(key in Scroll.animator){if(Scroll.animator[key].o==obj&&Scroll.animator[key].p==param){clearInterval(Scroll.animator[key].timer)}}
				var aID=Scroll.anielems,
				result,
				now,
				progress,
				w=obj==window?1:0,
				param=param=='x'?1:0,
				from=param?Scroll.sL(obj):Scroll.sT(obj);
				Scroll.animator[aID] = {
					start: new Date().getTime(),
					timer: setInterval(function(){
						now=(new Date().getTime())-Scroll.animator[aID].start;
						progress=now/time;
						result=(to-from)*Scroll.anim(progress)+from;
						if(param){
							if(w){window.scrollTo(result,Scroll.sT(obj))}
							else{obj.scrollLeft=result}
						}else{
							if(w){window.scrollTo(Scroll.sL(obj),result)}
							else{obj.scrollTop=result}
						}
						if(progress>=1){
							clearInterval(Scroll.animator[aID].timer);
							if(param){
								if(w){window.scrollTo(to,Scroll.sT(obj))} else{obj.scrollLeft=to}
							}else{
								if(w){window.scrollTo(Scroll.sL(obj),to)} else{obj.scrollTop=to}
							}
							//if(callback != undefined) {eval(callback+'(undefined)'); return}
							if(callback != undefined) {callback(); return}
						}
					},10)
				}
				Scroll.anielems++;
			}
		}
	};
