window.addEvent( 'domready', function() {

	var IMAGE_IS_LOADING = false;

	[ '.pagers a', '.gallery_items a'].each( function( sel ) {
		$$(sel).addEvent( 'click', function(e) {
			e.stop();
	
			if( IMAGE_IS_LOADING ) {
				return;
			}
	
			var url = this.get( 'href' );
	
			new Request.JSON({
				'method': 'get',
				'url': url+'.json',
				'onComplete': function( data ) {
					
					if( !data.selected ) {
						TSNSetMessage( 'notice',
							'Oops! There appears to have been an error.' );
						return;
					}
					
					setImage( data );
				}
			}).send();
		
		});
	});
	
	var setImage = function( data ) {
		var imageData = data.selected;
		
		var mainImage = $$('#gallery-main-image .image .col_8').pop();

		var coords = mainImage.getCoordinates();
		
		var cover = new Element( 'div', {
//			'text': "Loading...",
			'styles': {
				'background': '#333 url( '+TSN_BASE_PATH+
					'style/images/throbber_333.gif ) no-repeat center center',
				'color': '#333',
				'position': 'absolute',
				'opacity': 0,
				'height': coords.height,
				'width': coords.width,
				'top': coords.top,
				'left': coords.left
			},
			'tween': {
				'duration': 100,
				'onComplete': function() {
					if( IMAGE_IS_LOADING ) {
						IMAGE_IS_LOADING = false;
						cover.destroy();
					}
				}
			}
		});

		$(document.body).adopt( cover );
		cover.fade( 0.9 );

		var imgPath = TSN_BASE_PATH+'media/'+
			TSNMediaPath( imageData.uid )+imageData.uid+'_'+
			imageData.base_name+'_big.'+imageData.extension;

		var loader = new Image;
		loader.onload = function() {
	
			mainImage.set( 'src', imgPath );
			
			$('gallery-main-caption').innerHTML = decodeURIComponent(
				imageData.caption_formatted );
				
				
			var credit = $$('#gallery-main-image .image .credit').pop();
	
			var creditText = '';
			if( imageData.authors.length ) {
				var authors = [];
				imageData.authors.each( function( author ) {
					authors.push( '<a href="'+TSN_BASE_PATH+'search/?q='+
						author.name+'">'+unescape( author.name )+'</a>' );
				});
				
				creditText = 'By '+authors.join( ', ');
			}
			
			credit.innerHTML = creditText;
	
	
			var reprint = $$('#gallery-main-image .image .reprint').pop();
			reprint.set( 'href', reprint.get( 'href' ).replace(
				/object_name=\d+/, 'object_name='+imageData.uid ) );
			
			$$('.pagers .next').each( function(el) {
				el.set( 'href', unescape( data.nextUrl ) );
			});
	
			$$('.pagers .previous').each( function(el) {
				el.set( 'href', unescape( data.previousUrl ) );
			});
			
			cover.fade( 'out' );
		};
		setTimeout( function() {
			loader.src = imgPath;
		}, 500 );

	};

});
