var loadingImages = [];
jQuery(document).ready(function($) {
	
	/**
	 * For pages with customized scrollbars.
	 */
	$('.scroll-pane').jScrollPane({scrollbarWidth:13, dragMinHeight:48, dragMaxHeight:48});
	
	
	/**
	 * For Main pages.
	 */
	if( !$('#book-title').length && !$('#controls').length ) {
		$('img').closest('div').addClass('loading_white').children().hide();
		$('img').one('load', function() {
			$(this).closest('div').removeClass('loading_white').children().fadeIn();
		}).each(function(){if(this.complete) $(this).trigger("load");});
	}
	
	
	/**
	 * For "/books/" the page's book title switch.
	 */
	if( $('#book-title').length ) {
		$('#slideshow img').hover(
			function() {
				$('#book-title').html($(this).next().html());
			},
			function() {
				$('#book-title').text('');
			}
		);
		$('#slideshow img').hide().one('load', function() {
			$(this).fadeIn();
		}).each(function(){if(this.complete) $(this).trigger("load");});
		
		$('#pageSwitcher').detach().appendTo("#switchcontainer");
		
		$('#pageSwitcher .page01').click(function() {
			$(this).addClass('active');
			$('#pageSwitcher .page02').removeClass('active');
			$('#page01').show();
			$('#page02').hide();
		})
		$('#pageSwitcher .page02').click(function() {
			$(this).addClass('active');
			$('#pageSwitcher .page01').removeClass('active');
			$('#page02').show();
			$('#page01').hide();
		})
	}
	
	
	/**
	 * For Slideshow pages. (They're the only ones with controls.)
	 */
	
	if ( $('#controls').length ) {
		var currentSlide;
		var slideshowVisible = false;
		var playing;
		var intervalID;
		var oldSlide;
		if ( $('#slideshow area').length ) {
			$('#slideshow').addClass('loading').children('img').hide().one("load",function(){
				$('#slideshow').removeClass('loading');
				$(this).fadeIn();
			}).each(function(){if(this.complete) $(this).trigger("load");});
		} else {
			$('#slideshow img').hide().one("load",function(){$(this).fadeIn();})
			.each(function(){if(this.complete) $(this).trigger("load");});
		}
		$('.pos-top-left').css('background-color','#010101').children('img').hide().one("load",function(){
			$('.pos-top-left').removeClass('loading');
			$(this).fadeIn();
		}).each(function(){if(this.complete) $(this).trigger("load");});
		
		setupThisSlideshow();
	}
	
	function setupThisSlideshow() {
		
		// If there's no gallery, create it. No page should have to have a gallery set.
		if (!$('#gallery').length) {
			
			// Creates nessasary DOM elements and styles
			$('#slideshow').after('<div id="gallery" class="pos-center"><table cellspacing="0" style="width: 100%; height:100%; border: 0 none; padding: 0; border-collapse:collapse; border-spacing:0; "><tr><td>');
			var bookTitle = $('h2.sub').text();
			var images;
			
			// count images. Switch shouldn't be necessary after imgs are areas
			if ( $('#slideshow area').length ) {
				images = $('#slideshow area');
			}
			
			var timg;
			for (var i=0; i < images.length; i++) {
				timg = loadingImages[i]
				timg = {
					holder: null,
					linkElem: null,
					imageElem: null,
					imageID: $(images[i]).attr('class'),
					imagePopID: $(images[i]).attr('class'),
					imageDirectory: null
				}
			
				// all thumbnails, full images and slide show images are in a common directory, and the name is embedded in the imageID.
				if ( 'a' == timg.imageID.substring(timg.imageID.length-1) || 'b' == timg.imageID.substring(timg.imageID.length-1) ) {
					timg.imageDirectory = timg.imageID.substring(0, timg.imageID.length-3);
					timg.imagePopID = timg.imageID.substring(0, timg.imagePopID.length-1);
				} else {
					timg.imageDirectory = timg.imageID.substring(0, timg.imageID.length-2);
				}
				
				timg.holder = $('<div>').attr('id',timg.imageID).addClass("loading");
				timg.linkElem = $('<a>').attr({
						// rel: "gallery",
						// title: 'Full size image ' + (i+1) + ' of ' + images.length + ' from &quot;' + bookTitle + '&quot;',
						href: '/_images/' + timg.imageDirectory + '/pop-up/' + timg.imagePopID + '_popup.jpg'
					});
				timg.imageElem = $('<img src="/_images/' + timg.imageDirectory + '/slide-show/' + timg.imageID + '_slideshow.jpg" class="' + timg.imageID + '">');
				
				$(timg.linkElem).append(timg.imageElem);
				$(timg.holder).append(timg.linkElem);
				$('#gallery td').append(timg.holder);
				$('#gallery img').hide().one('load', function() {
					$(this).closest('div').removeClass('loading')
					$(this).fadeIn();
				}).each(function(){if(this.complete) $(this).trigger("load");});
			}
			
			$('#gallery a').each(function() {
				$(this).click(function() {
					var targetWindow = window.open($(this).attr('href'), "ImageVeiwer", 'scrollbars=1,resizable=1,top=20,left=10' );
					var oNewDoc = targetWindow.document.open("text/html", "replace");
					var sMarkup = '<html><head><title>' + $(this).children().attr('class') + '</title>' + 
						'</head><body style="background-color:#010101;margin:0"><div><img src="' + $(this).attr('href') + '"></div></body></html>';
					oNewDoc.write(sMarkup);
					
					$( 'img', targetWindow.document ).one("load", function() {
						if (targetWindow.innerHeight) {
						  targetWindow.innerHeight = $( 'img', targetWindow.document ).height(); 
						  targetWindow.innerWidth = $( 'img', targetWindow.document ).width(); 
						  if ( targetWindow.outerWidth > screen.availWidth - 20 ) {
							  targetWindow.innerWidth = screen.availWidth - 20;
						  }
						}
						else {
						  targetWindow.resizeTo( $('img', targetWindow.document ).width()+38, $('img', targetWindow.document).height()+92 );
						}
					}).each(function(){if(this.complete) $(this).trigger("load");});
					
					oNewDoc.close();
					$('#pause').click();
					return false;
				})
			});
		}
		
		currentSlide = $('#' + $('#gallery img').first().attr('class'));
		slideshowVisible = false;
		oldSlide = currentSlide;
		
		$('#play').show().click(function() {
			if (currentSlide.next('div').length) {
				if (slideshowVisible) {$('#forward').click();}
			} else {
				oldSlide = currentSlide;
				currentSlide = $('#' + $('#gallery img').first().attr('class'));
				if (slideshowVisible) {
					oldSlide.fadeOut('normal', function() {
						currentSlide.fadeIn('normal');
					});
				}
			}
			showSlideshow();
			autoPlay();
		});
		$('#begining').hide().click(function() {
			stopPlay();
			oldSlide = currentSlide;
			currentSlide = $('#' + $('#gallery img').first().attr('class'));
			oldSlide.fadeOut('fast', function() { currentSlide.fadeIn('fast'); });
			showSlideshow();
		});
		$('#ending').hide().click(function() {
			stopPlay();
			oldSlide = currentSlide;
			currentSlide = $('#' + $('#gallery img').last().attr('class'));
			oldSlide.fadeOut('fast', function() { currentSlide.fadeIn('fast'); });
			showSlideshow();
		});
		$('#pause').hide().click(function() {
			stopPlay();
			showSlideshow();
		});
		$('#forward').hide().click(function() {
			// if (playing) {autoPlay();} // resets interval counter.
			stopPlay();
			advanceSlide();
		});
		$('#rewind').hide().click(function() {
			// if (playing) {autoPlay();} // resets interval counter.
			stopPlay();
			retreatSlide();
		});
		$('#expand').hide().click(function() {currentSlide.children('a').click();});
		$('#close').hide().click(hideSlideshow);
		$('h2.sub').click(hideSlideshow);
		$('#open').show().click(function() {showSlideshow();autoPlay();});
		$('#gallery').hide();
		
		$('#slideshow area').click(function() {
			currentSlide = $('#' + $(this).attr('class'));
			showSlideshow();
			autoPlay();
			return false;
		});
	}
	function autoPlay() {
		if (slideshowVisible) {
			if( $(currentSlide).hasClass('loading') ){
				stopPlay();
				$(currentSlide).find('img').one('load',autoPlay).each(function(){if(this.complete) $(this).trigger("load");});
			} else {
				playing = true;
				window.clearInterval(intervalID);
				intervalID = window.setInterval( advanceSlide, 4000 );
				$('#play').fadeOut();
				$('#pause').fadeIn();
			}
		} else {
			stopPlay();
		}
	}
	function stopPlay() {
		playing = false;
		window.clearInterval(intervalID);
		$('#play').fadeIn();
		$('#pause').fadeOut();
	}
	function advanceSlide() {
		if (currentSlide.next('div').length) { // has next slide
			oldSlide = currentSlide;
			currentSlide = currentSlide.next('div');
			if (slideshowVisible) {
				oldSlide.fadeOut('fast', function() {
					currentSlide.fadeIn('fast');
				});
			}
			if( $(currentSlide).hasClass('loading') ){
				stopPlay();
				$(currentSlide).find('img').one('load',autoPlay);
			}
		}
		showSlideshow();
	}
	
	function retreatSlide() {
		if (currentSlide.prev('div').length) {
			oldSlide = currentSlide;
			currentSlide = currentSlide.prev('div');
			if (slideshowVisible) {
				oldSlide.fadeOut('fast', function() {
					currentSlide.fadeIn();
				});
			}
		}
		showSlideshow();
	}
	
	function showSlideshow() {
		if (!slideshowVisible) {
			slideshowVisible = true;
			oldSlide.hide();
			currentSlide.show();
			$('#gallery').fadeIn('fast');
			$('#open').hide(); 
			$('#close').show();
			$('#expand').fadeIn('fast');
		}
		
		//$('#output').text( $(currentSlide).attr('id') );
		
		if (currentSlide.prev('div').length) {
			$('#rewind').fadeIn('fast');
			$('#begining').fadeIn('fast');
		} else {
			$('#rewind').fadeOut('fast');
			$('#begining').fadeOut('fast');
		}
		
		if (currentSlide.next('div').length) {
			$('#forward').fadeIn('fast');
			$('#ending').fadeIn('fast');
		} else {
			$('#forward').fadeOut('fast');
			$('#ending').fadeOut('fast');
			stopPlay();
			// $('#output').text( 'End of show' );
		}
	}
	function hideSlideshow() {
		if (slideshowVisible) {
			slideshowVisible = false;
			stopPlay();
			$('#open').show(); 
			$('#close').hide();
			$('#expand').fadeOut('fast');
			$('#rewind').fadeOut('fast');
			$('#forward').fadeOut('fast');
			$('#ending').fadeOut('fast');
			$('#begining').fadeOut('fast');
			$('#gallery').fadeOut('fast', function() {currentSlide.hide()});
		}
	}
});
