/**
 * PResize Plugin
 * It resize, crop and center one (or more) images into a container
 * to fit container's viewport.
 * 
 * This is a Javascript + CSS technique so you need some
 */

(function($){
	
	$.presize = true;
	
	$.fn.presize = function(config) {
		
		config = $.extend({ foo:''
			
			,container: $(this).parent()
			
			,attachToWindow: true
			
			,classes: {
				cnt:			'presize-container',
				img:			'presize-img',
				fullW: 			'presize-img-full-width',
				fullH: 			'presize-img-full-height'
			}
		
		},config);
		
		if ( !$(config.container).hasClass(config.classes.cnt) ) {
		
			// Setup basic local styles
			style = '<style>';
			style+= '.' + config.classes.cnt + '{position:relative;overflow:hidden}';
			style+= 'img.' + config.classes.img + '{position:absolute;top:0;left:0}';
			style+= 'img.' + config.classes.fullW + '{width:100%;height:auto}';
			style+= 'img.' + config.classes.fullH + '{height:100%; width:auto}';
			style+= '</style>';
			$('body').append(style);
			
			// Apply basic classes to 
			$(config.container).addClass(config.classes.cnt);
			
		}
		
		
		
		// Attach resize behavior to the window management.
		return $(this).each(function(){
			
			var obj = this;
			
			__presize_do_presize( obj, config );
			
			if ( config.attachToWindow != true ) return;
			
			$(window).resize(function(){
				
				__presize_do_presize( obj, config );
				
			});
			
		});
		
		
		
		
		function __presize_do_presize( obj, config) {
			
			$(obj).addClass(config.classes.img);
			
			var data = {
				image: {
					w: $(obj).width(),
					h: $(obj).height(),
					r: 0
				},
				stage: {
					w: $(config.container).width(),
					h: $(config.container).height(),
					r: 0
				}
			}
			
			// Check viewport and image's aspect ratio
			data.image.r = Math.round( ( data.image.w / data.image.h ) * 100 ) / 100;
			data.stage.r = Math.round( ( data.stage.w / data.stage.h ) * 100 ) / 100;
			
			// Remove previous setted classes.
			$(obj).removeClass(config.classes.fullW).removeClass(config.classes.fullH);
			
			// Setup img widht with a custom class.
			if ( data.stage.r < data.image.r ) {
				$(obj).addClass(config.classes.fullH);
			} else {
				$(obj).addClass(config.classes.fullW);
			}
			
			// Center image into viewport.
			hoffset = Math.round( ( $(obj).height() - data.stage.h ) / 2 );
			woffset = Math.round( ( $(obj).width() - data.stage.w ) / 2 );
			$(obj).css('top','-'+hoffset+'px');
			$(obj).css('left','-'+woffset+'px');
			
		} // EndOf: "__presize_do_presize()" ###
		
		
		return this;
	
	} // EndOf: "$.fn.presize()" ###
	

})(jQuery);
