(function($){  
$.fn.constrain = function(options) {  

		return this.each(function() { 
			var img = $(this);  

			var element = $(options.element, document);

			if (img.width() > img.height()) {								 		
					img.css('height', 'auto');
					img.width('width', '100%'); 				
			} else {
					img.css('width', 'auto');
					
			

					img.width('height', '100%'); 	
			}
			
		});   
};  
})(jQuery); 

(function($){ 
$.fn.gallery = function(options) {  

		var defaults = {  
			imageDiv: "#galleryimage",
			captionDiv: "#gallerycaption",
			constrainImage: true
		};  
			
		var options = $.extend(defaults, options); 


		return this.each(function() {   
			var tag = $(this);
			
			$('li', tag).each(function() {
				var li = $(this);			
				
				var _a = $('a', li);			
				var _img = $('img', li);
			
				_img.attr('ref', _a.attr('href'));
				
				li.append(_img);
				
				_a.remove();
				
				_img.click(function() {														
					var imagediv = $(options.imageDiv, $(document));
					
					imagediv.empty(); // get rid of old value
					

					var imgtag = $(document.createElement('img')).attr('src', $(this).attr('ref'));
					imgtag.css('visible', 'hidden')
					
					var divtag = $(document.createElement('div')).css('position', 'absolute')
					divtag.css('visible', 'hidden');

					divtag.append(imgtag);

					$('body', document).append(divtag);

					lastImage = $(this).parent();
					
					imgtag.click(function () {
						var gallery = $('#gallery > li > img[ref='+$(this).attr('src')+']', document);
						alert(gallery.parent().next().html());
						$('img', gallery.parent().next()).click();

						if (gallery.parent().next() == null) {
							alert('eol');

						}
					
					});
					
					imgtag.constrain({element: options.imageDiv});

					imagediv.append(imgtag);

					divtag.remove();					
					
					$(options.captionDiv, $(document)).empty();
					$(options.captionDiv, $(document)).append('<p>' + $(this).attr('alt') + '</p>');
					
		
				});

				// simulate image view

				if (li.hasClass('active')) {
					$('img', li).click();		
				}

			});
			
			
		});  
};  
})(jQuery);  