;(function($){
	
	$.fn.extend({
		portfolioRodeo: function(options) {
			return this.each(function() {
				new $.PortfolioRodeo(this, options);
			});
		}
	});
	
	$.PortfolioRodeo = function(element, options) {
		var defaults = {};
		this.options = $.extend({}, defaults, options || {});
		
		this.element = $(element);
		
		this.setup();
	};
	
	$.extend($.PortfolioRodeo.prototype, {
		
		setup: function() {
			
			// Set images to display none as soon as they are available
			this.image = $('.pr-galleryfullsize img', this.element);
			this.caption = $('.pr-caption', this.element);

			// Add selected class to first thumb
			$('.pr-thumbs a:first', this.element).addClass('selected');
			
			var self = this;
			
			$('.pr-thumbs a', this.element).bind('click', function(){
				self.change(this);
				return false;
			});
			
		},
		
		change: function(anchor) {
			
			var anchor	= $(anchor);
			var thumb	= $('img', anchor);
			var img		= $('.pr-galleryfullsize img', this.element);
			var caption	= $('.pr-caption', this.element);
			var href	= anchor.attr('href');	
			var title	= thumb.attr('title');
			var src		= img.attr('src');
			var self	= this;
			
			// Set the main gallery wrapper height
			var galleryHeight = this.element.outerHeight();
			this.element.height(galleryHeight);
			
			// Add selected class to the thumb img
			$('a.selected', this.element).removeClass('selected');
			anchor.addClass('selected');
			
			this.element.addClass('loading');
			
			// Test to see if the thumb that was clicked is not already showing
			if(href !== src) {

				// Fade the caption and insert the new caption text
				caption.fadeOut('fast', function(){
					caption.html(title);
				});
				
				// Fade the large image and change out the src attribute
				img.fadeOut('fast', function() {
					// Swap out the src
					img.attr('src', href);
					self.animate(href, galleryHeight, img, caption);
				});
			}
			
			return false;
		},
		
		animate: function(url, galleryHeight, img, caption) {
			
			var self	= this;
			
			// load the large image
			$.ajax({
				url: url,
				type: 'GET',
				complete: function() {
								
					// Animate the height of the gallery to match height of large image
					var combinedHeight = (img.outerHeight() + caption.outerHeight());
					if(galleryHeight < combinedHeight) {
					
						self.element.stop().animate({
							height: combinedHeight
						}, 250, function() {
							img.fadeIn();
							caption.fadeIn();
							self.element.removeClass('loading');
						});
					
					} else {
					
						img.fadeIn();
						caption.fadeIn();
						self.element.removeClass('loading');
					
					}
				
				}
			});
			
		}
		
	});
	
})(jQuery);

jQuery(document).ready(function($) {
	
	$('.pr-gallery').portfolioRodeo();

});