

jQuery(function($){
	if(navigator.userAgent.match(/MSIE [1-6]\D/))
		return;
	
	if(window.imagesByAlbumID){
		/**
		 * Provide iPhoto interface for the album thumbnails
		 */
		$('#album-list > li > a > img')
			.mousemove(function(e){
				if(!this.getBoundingClientRect)
					return;
				var left = this.getBoundingClientRect().left; //var left = $(this).data('left');
				var id = $(this).closest('li').attr('id').substr(6);
				var images = imagesByAlbumID[id];
			
				if(!images)
					return;
				var i = Math.floor((e.clientX - left)/(this.offsetWidth/images.length));
				
				if(!$(images[i].img).data('loaded'))
					return;
				
				this.src = images[i].img.src;
				this.alt = images[i].img.alt;
				
				var albumImagePath = images[i].href.substr(images[i].href.indexOf(location.pathname)+location.pathname.length-1);
				var pathParts = albumImagePath.match(/^\/([^\/]+)(\/.+)/);
				var albumURL = $(this).closest('a').attr('href').replace(/#.*/, '');
				$(this).closest('a').attr('href', albumURL + '#' + pathParts[2]);
			})
			.mouseleave(function(){
				var id = $(this).closest('li').attr('id').substr(6);
				var images = imagesByAlbumID[id];
				if(!images)
					return;
				
				var first = imagesByAlbumID[id][0];
				this.src = first.img.src;
				this.alt = first.img.alt;
				var albumURL = $(this).closest('a').attr('href').replace(/#.*/, '');
				$(this).closest('a').attr('href', albumURL); //reset
			});
	}
	
	//Gallery login form: ensure that the hash is passed onto gallery_redirect
	var $gallery_login_form = $('#gallery_login_form');
	if($gallery_login_form.length && window.location.search.indexOf('gallery_redirect') !== -1 && location.hash.substr(1,1) == '/'){
		var $gallery_redirect = $gallery_login_form.find('input[name="gallery_redirect"]');
		$gallery_redirect.val($gallery_redirect.val().replace(/#.*/, '') + location.hash);
	}
	
	//Rewrite the links to individual images in the album view
	$('#content.gallery-album #album-images > li > a').each(function(){
		this.href = "#" + this.href.substr(this.href.indexOf(location.pathname)+location.pathname.length-1);
	});
	
	//Redirect to the album with hash if they link to the individual image
	if($('#content').hasClass('gallery-album-image') && window.albumURL){
		var hash = location.href.substr(albumURL.length-1).replace(/#.*/, '');
		location.replace(albumURL + "#" + hash);
		return;
	}
	
	//Album viewer
	if($('#content').hasClass('gallery-album') && window.albumImages && albumImages.length){
		var $imageBox = $('#album-image-box');
		var albumURL = location.href.replace(/(\?|#).*$/, '');
		var albumDocumentTitle = document.title;
		
		//Add interactivity to the slideshow button; disable slideshow whenever
		// a click happens on the page, or if the hash is changed via the back button?
		var slideshowEnabled = false;
		var slideshowTimerID = null;
		function toggleSlideshow(state){
			if(state || state === false)
				slideshowEnabled = state;
			else
				slideshowEnabled = !slideshowEnabled;
			$('#album-slideshow-btn').text( slideshowEnabled ? 'Stop Slideshow' : 'Play Slideshow' );
			
			if(!slideshowEnabled){
				clearInterval(slideshowTimerID);
				$('#content').removeClass('gallery-album-slideshow');
			}
			else {
				$('#content').addClass('gallery-album-slideshow');
				var advanceSlide = function(){
					if(window.nextAlbumImage){
						window.location = '#' + nextAlbumImage.href.substr(albumURL.length-1);
						
						$('#album-navigation > a[rel=next]').addClass('active');
						setTimeout(function(){
							$('#album-navigation > a[rel=next]').removeClass('active');
						}, 500);
					}
				};
				slideshowTimerID = setInterval(advanceSlide, 4000);
				advanceSlide();
			}
		}
		$('#album-slideshow-btn').click(function(e){
			toggleSlideshow();
			
			if(navigator.userAgent.match(/MSIE 7\D/))
				this.blur();
			e.preventDefault();
			e.stopPropagation();
		});
		$('html').click(function(e){
			if(slideshowEnabled){
				toggleSlideshow(false);
				$('#album-slideshow-btn').addClass('highlighted');
				setTimeout(function(){
					$('#album-slideshow-btn').removeClass('highlighted');
				}, 500);
			}
		});
		
		//Detect when the location hash changes
		var intervalID;
		function hashchangeHandler(e){
			if(!e)
				e = window.event;
			//Disable the polling if hashchange event is supported natively
			if(intervalID && e && e.type == 'hashchange'){
				clearInterval(intervalID);
				intervalID = null;
			}
			
			//Check to see if the hash refers to an actual image in the current album
			var hash = location.hash.substr(1);
			
			//If no hash, then null-out albumImage so that the interface will go back to the album view
			window.currentAlbumImage = null;
			
			//With the supplied hash, see if there is an album image that matches
			if(hash){
				for(var i = 0; i < albumImages.length; i++){
					if(albumURL + hash.substr(1) == albumImages[i].href){
						window.previousAlbumImage = albumImages[i-1];
						if(!window.previousAlbumImage)
							window.previousAlbumImage = albumImages[albumImages.length-1];
						window.currentAlbumImage = albumImages[i];
						window.nextAlbumImage = albumImages[i+1];
						if(!window.nextAlbumImage)
							window.nextAlbumImage = albumImages[0];
					}
				}
			}
			
			//Pre-load next image
			if(window.nextAlbumImage && nextAlbumImage.src){
				var preloadImg = new Image();
				preloadImg.src = window.nextAlbumImage.src;
			}
			
			//Bring the interface back to the album view
			if(!window.currentAlbumImage){
				$('#content').removeClass('image-browser');
				$imageBox.attr('hidden', 'hidden');
				$('#content').toggleClass('refreshAttributeSelector');
				document.title = albumDocumentTitle;
			}
			//Display an individual photo
			else {
				$('#content').addClass('image-browser');
				$imageBox.removeAttr('hidden');
				$imageBox.find('img')
					.attr('alt', window.currentAlbumImage['title'])
					.attr('src', window.currentAlbumImage['src']);
				document.title = window.currentAlbumImage['title'] + ' | ' + albumDocumentTitle;
				
				var previousHash = previousAlbumImage.href.substr(albumURL.length-1);
				var nextHash = nextAlbumImage.href.substr(albumURL.length-1);
				
				//Set the previous/next navigation links
				$imageBox.find('a[rel~=next]')
					.attr('title', "Next album image: " + nextAlbumImage['title'])
					.attr('href', '#' + nextHash);
				$('#album-navigation a[rel~=next]')
					.attr('title', "Next album image: " + nextAlbumImage['title'])
					.attr('href', '#' + nextHash);
				$('#album-navigation a[rel~=previous]')
					.attr('title', "Previous album image: " + previousAlbumImage['title'])
					.attr('href', '#' + previousHash);
				
				$imageBox.find('.title > h2').text(currentAlbumImage['title']);
				$imageBox.find('.description').html(window.currentAlbumImage['caption'] + window.currentAlbumImage['description'])
				var $download = $imageBox.find('.download');
				$download.find('> a').attr('href', currentAlbumImage['download_href']);
				$download.find('.filesize').text(Math.round(currentAlbumImage['download_filesize']/10000)/100);
				
				//Highlight the item in the index, and scroll to it
				var $el = $('#album-images > li > a')
					.removeClass('active')
					.filter('[href$="#' + hash + '"]:first')
					.addClass('active')
				
				$('#album-images').scrollTo($el, 100);
				$('#content').toggleClass('refreshAttributeSelector');
			}
		}
		
		//Monitor the location.hash for changes
		document.getElementsByTagName('body')[0].onhashchange = hashchangeHandler;
		var previousHash = location.hash.substr(1);
		if(previousHash)
			hashchangeHandler();
		intervalID = window.setInterval(function(){
			var thisHash = location.hash.substr(1);
			if(thisHash != previousHash){
				hashchangeHandler();
				previousHash = thisHash;
			}
		}, 100);
	}
	
	//console.info(previousHash)
});