/**
 *	Apartment photo gallery.
 */
(function( $ ){

	$.fn.paApartGallery = function( options ) {  
		
		var settings = {};
		var photoholder;
		var currentSrc = "";
		
		function loadImage(src) {
			if(currentSrc != src) {
				currentSrc = src;
				photoholder.empty();	
				var image = new Image();
				$(image).bind('load', function() {
					displayImage(this);
				});
				$(image).hide();
				image.src = src;
				if(isImageLoaded(image)) {
					displayImage(image);
				}
			}
		}
		
		function isImageLoaded(img) {
			var isLoaded = true;
			if(typeof img.complete != 'undefined' && !img.complete) {
				isLoaded = false;
			};
			if(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
				isLoaded = false;
			};
			return isLoaded;
		}
		
		function displayImage(img) {
			photoholder.html(img);
			var top = (photoholder.height() - $(img).height())/2;
			var left = (photoholder.width() - $(img).width())/2;
			$(img).css({ 'position':'relative',
						 'top':top,
						 'left':left});
			$(img).fadeIn();
		}
		
		function displayThumbnail(img) {
			var width = $(img).width();
			var height = $(img).height();
			var ratio = width / height;
			var parent = $(img).parent();
			var top = 0;
			var left = 0;
			if(width < parent.width()) {
				width = parent.width();
				height = width / ratio;
				top = (parent.height() - height)/2;
			}
			$(img).css({'width':width, 
						 'height':height,
						 'position':'relative',
						 'display':'block',
						 'top':top});
		}
		
		return this.each(function() {        
			// If options exist, lets merge them with our default settings
			if (options) { 
				$.extend(settings, options);
			}
			// Plugin code starts here.
			var $this = $(this);
			photoholder = $("#photoholder", this);
			
			// creates accordions for category selection
			$("#photocategories", this).accordion({ 
				header: "h3",
				autoHeight: false
			});
			
			// iterate through the image links
			$("a", $(".thumbs-container")).each(function(index) {
				$(this).click(function(event) {
					event.preventDefault();
					loadImage($(this).attr('href'));
				});
			});
			
			// iterate through the miniatures images
			$("img", $(".thumbs-container")).each(function(index) {
				// wrap the image into a div
				$(this).parent().wrap('<div class="thumbnail" />');
				// bind the 'load' event to resize and position the image when loaded.
				// #### TODO : doesn't work on IE...
				if(isImageLoaded(this)) {
					displayThumbnail(this);
				} else {
					$(this).bind('load', function() {
						displayThumbnail(this);
					});
				}
			});
			
			// display the categories
			$("#photocategories").css("visibility", "visible");
			
			// load the first image
			var firstSrc = $("img:first", $(".thumbs-container")).parent().attr('href');
			loadImage(firstSrc);
			
			
		});
	
	};
})( jQuery );
