// -------------------------------------------------------------------
// !GYROBGGalleryImage
// 
// GYROBGGalleryImage
// -------------------------------------------------------------------
(function($) {

	$.fn.GYROBGGalleryImage = function(config) {
		
		// default config overriden with settings if avaialble
		var defaults = {
			"transitionLength": 500,
			"imageDimensionRatio": 4/3
		};

		var imageContainer;
		var currentImageSource;
				
		// override config with any matching settings		
		if (config) {
			$.extend(defaults, config);
		}
		
		// -----------------------------------------------------------------------
		// resize the background image to fill the background container
		// - called as handler of window resize
		// - preserves the aspect ratio (allow excess to clip)
		// -----------------------------------------------------------------------
		function resizeToFill() {			
						
			var imageDimensionRatio = imageContainer.width()/imageContainer.height();

			if (imageDimensionRatio < defaults.imageDimensionRatio) {
				imageContainer.children().css({
					"width": "auto",
					"height": "100%"
				});
	
			} else {
	
				imageContainer.children().css({
					"width": "100%",
					"height": "auto"
				});
	
			}
	
		};

		// -----------------------------------------------------------------------
		// show the image identified by imageIndex
		// -----------------------------------------------------------------------
		this.showImage = function(newImageSource) {

			if (currentImageSource !== newImageSource) {

				currentImageSource = newImageSource;			

				// create a new image
				var newImage = $(new Image());
	
				// handle image load (called when image is loaded and available)
				newImage.load(function() {

					imageContainer.trigger("loadComplete");					
										
					image = $(this);
					
					// must do this before appending to the container
					image.hide();
	
					imageContainer.empty();
					imageContainer.append(this);
					resizeToFill();
					
					image.fadeIn(defaults.transitionLength);
						
				});
				
				// handle image loading error
				newImage.error(function() {
					$.log("ERROR: image could not be loaded.");
				});
				
				newImage.attr("src", currentImageSource);
				imageContainer.trigger("loadStart");
			
			}
			
		};
		
		// -----------------------------------------------------------------------
		// initialize for each matched item and return it
		// -----------------------------------------------------------------------
		return this.each(function() {		

			imageContainer = $(this);

			// setup window resize event handler to resize the image 
			// to fill its container
			$(window).resize(function(event) {
				resizeToFill();
			});
			resizeToFill();

			$.log("Finished initializing GYROBGGalleryImage");

		});

	};

})(jQuery);

