/*
 * Written by Yevgeny Smirnov [yevgeny.ru], 2007
 * ------------------------------------------------------------ */

function ParticularAlbumTweaks() {
	var albumBlock = $('album-block');
	var nextAlbumImageAnchor = $('next-album-image-anchor');
	var horizontalPageMargins = 32 * 2;
	
	if(nextAlbumImageAnchor) {
		nextAlbumImageAnchor.style.position = 'absolute';
		function MoveNextAlbumImageAnchor () {
			nextAlbumImageAnchor.style.left =/* IE: albumBlock.width = */ (Math.floor((document.body.offsetWidth - horizontalPageMargins)/192)*192  - horizontalPageMargins/2) + 'px';
		};
		MoveNextAlbumImageAnchor();
		Event.observe(window, 'resize', MoveNextAlbumImageAnchor);
		Event.observe(document, 'load', MoveNextAlbumImageAnchor);
		Event.observe(document, 'focus', MoveNextAlbumImageAnchor);
	}
}

function IndexPageTweaks () {
	var recentAlbum = $('recent-album');
	var horizontalPageMargins = 32 * 2;

	if(recentAlbum) {
		function MoveRecentAlbum () {
			var bodyWidth = document.body.offsetWidth;
			var photoAlbumsWidth = Math.floor( (bodyWidth - horizontalPageMargins)/210 ) * 210;
			
			var leftMargin = bodyWidth - horizontalPageMargins - photoAlbumsWidth;
			recentAlbum.style.marginLeft = leftMargin + 'px';
		}
		Event.observe(window, 'resize', MoveRecentAlbum);
		Event.observe(document, 'load', MoveRecentAlbum);		
		Event.observe(document, 'focus', MoveRecentAlbum);		
		MoveRecentAlbum();
	}
}


function PhotoPage() {
	
		var _self = this;
		
		var keyCode;
		document.onkeydown = KeyboardNavigation;

		var previousPage = $('PrevLink');
		var nextPage = $('NextLink');

		var previousImageAnchor = $('previous-image-anchor');
		if(previousImageAnchor) var previousImageAnchorDefaultHref = previousImageAnchor.href;

		var nextImageAnchor = $('next-image-anchor');
		if(nextImageAnchor) var nextImageAnchorDefaultHref = nextImageAnchor.href;

		var nextAlbumImageAnchor = $('next-album-image-anchor');
		var previousAlbumImageAnchor = $('previous-album-image-anchor');

		var lastBreadcrumb = $('breadcrumb_4');
		var photoWasNotInCache = false;
		var preloadedImage = new Image();
		var hasBeenScrolled = false;
		
		var cleanOriginalFileName = currentPhotoThumbnail.src.match(/\/([^\/#]+)(__[^\.]+(\.[^\.#]+))#?(.*)$/);
		
		if(cleanOriginalFileName[4] != null) var originalImageThumbnail = $(cleanOriginalFileName[4]);
		if(originalImageThumbnail) originalImageThumbnail.down().onclick();
		else cleanOriginalFileName = cleanOriginalFileName[1] + cleanOriginalFileName[3];
		

		function KeyboardNavigation(event) {
			if (window.event) event = window.event;
			keyCode = event.keyCode ? event.keyCode : event.which ? event.which : null;
			switch(keyCode) {
				case 0x25:
					Event.stop(event);
					_self.Navigate('backward');
				break;

				case 0x27:
					Event.stop(event);
					_self.Navigate('forward');
				break;
			}
		}


		this.Navigate = function(direction) {
			switch(direction) {
				case 'backward':
					if(previousImageAnchor && previousImageAnchor.href) {
						
						var previousThumbnailChilds = currentPhotoThumbnail.up().previous('a').childNodes;

						var i = 0;
						while(previousThumbnailChilds[i] && previousThumbnailChilds[i].src == null) i++;
						if(previousThumbnailChilds[i]) previousThumbnailChilds[i].onclick();
						else if(previousPage.href){
							fullPhoto.onload = null;
							_self.HideFullPhoto();
							ClearTimers;
							document.onkeydown = null;
							window.location = previousPage.href;
						}
						previousImageAnchor.style.backgroundColor = '#777';
						_SetImageAnchorStyle({
							type: 'click',
							target: previousImageAnchor
						});
						
					};
				break;

				case 'forward':
					if(nextImageAnchor && nextImageAnchor.href) {

						var nextThumbnailChilds = currentPhotoThumbnail.up().next('a').childNodes;

						var i = 0;
						while(nextThumbnailChilds[i] && nextThumbnailChilds[i].src == null) i++;
						if(nextThumbnailChilds[i]) nextThumbnailChilds[i].onclick();
						else if (nextPage.href){
							fullPhoto.onload = null;
							_self.HideFullPhoto();
							ClearTimers;
							document.onkeydown = null;
							window.location = nextPage.href;
						};
						nextImageAnchor.style.backgroundColor = '#777';
						_SetImageAnchorStyle({
							type: 'click',
							target: nextImageAnchor 
						});

					};
				break;
			};
			
			return false;
		}
		
		// Джаваскриптовое переназначение стилей для того, чтобы стиль стрелок следующей-предыдущей фотографии работал и после применения _element_.style.[...]
		$A([previousImageAnchor, nextImageAnchor, previousImageAnchor, nextImageAnchor]).each(
			function(element) {
				if(element) {
//					element.onclick = _SetImageAnchorStyle;
					element.onmouseover = element.onmouseout = _SetImageAnchorStyle;
//					 _SetImageAnchorStyle;
				}
			}
		); 

		var imageAnchorHovered;
		function _SetImageAnchorStyle (event) {

			// ИЕ
			if(event) {
				
				switch(event.type) {
					case ('mouseout'):
						this.style.backgroundColor = 'transparent';
						imageAnchorHovered = null;
					break;
				
					case ('mouseover'):
						this.style.backgroundColor = '#606060';
						imageAnchorHovered = this;
					break;
				
					case ('click'):
						if(imageAnchorHovered != event.target) {
							event.target.style.backgroundColor = 'transparent'; 
						} else {
							event.target.style.backgroundColor = '#606060'; 
						};
						return false;
					break;
				}
			}
//			if(imageAnchorHovered) var arrowsBackgroundStyle = setTimeout(function() { imageAnchorHovered.style.backgroundColor = 'transparent' }, 200);
		}
		
		function ClearTimers() {
			clearInterval(revealFullPhotoInterval);
			clearInterval(hideFullPhotoInterval);
			clearTimeout(loadIndicatorTimout);
		};

		window.onunload = function() {
			_self.HideFullPhoto();
			ClearTimers;
		}

		this.HideFullPhoto = function() {
			ClearTimers();

			hideFullPhotoInterval = setInterval(
				function() {
					if (fullPhotoOpacity <= .4) {
						clearInterval(hideFullPhotoInterval);
						fullPhoto.src = preloadedImage.src;
					}else{
						fullPhoto.setStyle({
							opacity: fullPhotoOpacity -= .15
						});
					};
				}
			, 30)

			// выводить индикатор загрузки после того. как убедимся, что фотография не загрузилась из браузерного кеша
			loadIndicatorTimout = setTimeout(
				function() {
					photoLoadIndicator.style.display = 'block';
					photoWasNotInCache = true;
				},
				600
			)
		}

		function RevealFullPhoto () {
			
			fullPhotoOpacity = fullPhoto.getStyle('opacity');
			photoLoadIndicator.style.display = 'none';
			clearTimeout(loadIndicatorTimout);
			clearInterval(hideFullPhotoInterval);

			var increaseStep = (photoWasNotInCache) ? .05 : .08;
			photoWasNotInCache = false;

			revealFullPhotoInterval = setInterval(
				function() {
					fullPhoto.setStyle({
						opacity: fullPhotoOpacity += increaseStep
					});
					if (fullPhotoOpacity >= 1) {
						clearInterval(revealFullPhotoInterval);
						fullPhoto.setStyle({
							opacity: fullPhotoOpacity = 1
						});
					};
				}
			, 30);
		}


		function _AppendThumbnailHandlers() {
			var photoThumbnails = $('photo-thumbnails').getElementsByTagName('img');
			for (var i=0; i < photoThumbnails.length; i++) {
				photoThumbnails[i].onclick = _ChangePhoto;
			};
			currentPhotoThumbnail.onclick = _ChangePhoto;

			// document.body.style.overflowY = 'scroll';

			function _ChangePhoto() {

				if(this == currentPhotoThumbnail) { return false };

				var imagePath = this.src.match(/\/([^\/#]+)(__[^\.]+(\.[^\.#]+))#?(.*)$/);
				preloadedImage.src = photoAlbumDirectory + imagePath[1] + '__full' + imagePath[3];
				
				/*	статистика посещений	*/
				var requestedPath = photoAlbumDirectory.match(/(https?:\/\/[^\/]+)?\/(.*)/);
				requestedPath = "/" + requestedPath[2] + imagePath[1] + imagePath[3];

				if( typeof urchinTracker != 'undefined' ) urchinTracker(requestedPath);
				/*	/статистика	*/
				
				
				var cleanFileName = imagePath[1] + imagePath[3];
				if(cleanFileName != cleanOriginalFileName) window.location = '#' + cleanFileName;
				else window.location = '#current';

				_self.HideFullPhoto();

				// при просмотре очередного альбома однократно подвинуть экран к большой фотограф
				if(!hasBeenScrolled) {
					window.scrollTo(0, 140);
					hasBeenScrolled = true;
				};

				var fileName = imagePath[1].match(/[^\/]+$/) + imagePath[3];
				currentPhotoThumbnail.style.border = 'none';
				currentPhotoThumbnail.style.backgroundPosition = '0 0';
				currentPhotoThumbnail.style.width = currentPhotoThumbnail.style.height = '64px';
				currentPhotoThumbnail.style.cursor = 'pointer';

				var newCurrentPhotoThumbnail = document.createElement('div');
				newCurrentPhotoThumbnail.className = 'thumbnail current';
				newCurrentPhotoThumbnail.src = this.src;
				newCurrentPhotoThumbnail.style.backgroundImage = "url('" + this.src + "')";
				newCurrentPhotoThumbnail.style.cursor = 'default';
				newCurrentPhotoThumbnail.onclick = _ChangePhoto;

				newCurrentPhotoThumbnail = this.parentNode.insertBefore(newCurrentPhotoThumbnail, this);
				this.parentNode.removeChild(this);
				
				// IE не прототипирует новые элементы, созданные document.createElement
				currentPhotoThumbnail = $(newCurrentPhotoThumbnail);

				var nextElement = currentPhotoThumbnail.up().next('a');
				if(nextImageAnchor) {
					nextImageAnchor.style.visibility = "visible";
					if (nextAlbumImageAnchor && nextElement.id == 'next-image-anchor') nextImageAnchor.href = nextAlbumImageAnchor.href;
					else {
						//				IE не понимает nextElement.href != null
						if(nextElement && nextElement.href != "" && nextElement != nextImageAnchor) nextImageAnchor.href = nextElement.href;
						else if(nextAlbumImageAnchor) nextImageAnchor.href = nextImageAnchorDefaultHref;
						else {
							nextImageAnchor.removeAttribute("href");
							nextPage.removeAttribute("href");
							nextImageAnchor.style.visibility = "hidden";
						};
					};
					if(nextImageAnchor.href) nextPage.href = nextImageAnchor.href;
				} else if(nextElement) {
					nextImageAnchor = document.createElement('a');
					nextImageAnchor.id = "next-image-anchor";
					nextImageAnchor.className = "images-navigation";
					nextImageAnchor.onclick = function() { return pageActions.Navigate('forward') };
					nextImageAnchor.title = "Следующая фотография [клавиатурная стрелка «вправо»]";
					nextImageAnchor.style.position = "absolute";
					nextImageAnchor.style.visibility = "visible";
					nextImageAnchor.style.backgroundColor = "transparent";
					nextImageAnchor.href = nextElement.href;
					nextImageAnchor.innerHTML = "&rarr;";
					fullPhotoContainer.appendChild(nextImageAnchor);
				};

				var previousElement = currentPhotoThumbnail.up().previous('a');
				if(previousImageAnchor) {
					previousImageAnchor.style.visibility = "visible";
					if (previousAlbumImageAnchor && previousElement.id == 'previous-image-anchor') previousImageAnchor.href = previousAlbumImageAnchor.href;
					else {
						if(previousElement && previousElement.href != "" && previousElement != previousImageAnchor) previousImageAnchor.href = previousElement.href;
						else if(previousAlbumImageAnchor) previousImageAnchor.href = previousImageAnchorDefaultHref;
						else {
							previousImageAnchor.removeAttribute("href");
							previousPage.removeAttribute("href");
							previousImageAnchor.style.visibility = "hidden";
						};
					};
					if(previousImageAnchor.href) previousPage.href = previousImageAnchor.href;
				} else if(previousElement) {
						previousImageAnchor = document.createElement('a');
						previousImageAnchor.id = "previous-image-anchor";
						previousImageAnchor.className = "images-navigation";
						previousImageAnchor.onclick = function() { return pageActions.Navigate('backward') };
						previousImageAnchor.title = "Предыдущая фотография [клавиатурная стрелка «влево»]";
						previousImageAnchor.style.position = "absolute";
						previousImageAnchor.style.visibility = "visible";
						previousImageAnchor.style.backgroundColor = "transparent";
						previousImageAnchor.href = previousElement.href;
						previousImageAnchor.innerHTML = "&larr;";
						fullPhotoContainer.appendChild(previousImageAnchor);
				};

				lastBreadcrumb.innerHTML = fileName;

				return false;
			};
		}

		var fullPhotoContainer = $('full-photo-container');

		var fullPhoto = $('full-photo');
		var fullPhotoOpacity = 1;
		fullPhoto.setStyle({
			opacity: fullPhotoOpacity
		});
		var loadIndicatorTimout;
		var revealFullPhotoInterval;
		var hideFullPhotoInterval;

		var photoLoadIndicator = document.createElement('img');
		photoLoadIndicator.src = 'http://no-cache.yevgeny.ru/images/load-indicator-aaa.gif';
		photoLoadIndicator.id = 'photo-load-indicator';
		fullPhotoContainer.appendChild(photoLoadIndicator);
	//	fullPhotoContainer.parentNode.insertBefore(fullPhotoContainer, photoLoadIndicator);

		var isGecko = (navigator.userAgent.indexOf('Gecko') != -1);

		if(isGecko) fullPhoto.onload = function() { setTimeout(RevealFullPhoto, 20)};
		else fullPhoto.onload = function() { RevealFullPhoto() };
		
		_AppendThumbnailHandlers();
}

