/* jquery.imagefit
 *
 * Version 0.3 by Kasem Ramin based on Oliver Boermans code 
 *
 *
 */
(function($) {
	$.fn.imagefit = function(size2) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){

				$(img)
					.width(size2 || '100%').each(function()
					{
							
							if ($(this).width() >=  $(this).attr('startwidth')){
								  $(this).width($(this).attr('startwidth') + "px");
								  $(this).height($(this).attr('startheight') + "px");
							}
							else {
							      $(this).height(Math.round(
								$(this).attr('startheight')/$(this).attr('startwidth')*($(this).width()))
							+ "px");
						}
					})
				}
		};

		this.each(function(){
				var container = this;

				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));

				// store initial dimensions on each image
				imgs.each(function(){
					// console.log('img');
					// console.log($(this).width());
					if (! $(this).width()) return;
					$(this).attr('startwidth', $(this).width())
						.attr('startheight', $(this).height());
																		
					// console.log($(this).attr('startwidth'));
					// console.log($(this).css('max-width'));
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){fit.all(imgs);});
				
				
				
			});
		return this;
	};
})(jQuery);
