/*
	Plugin Name:	jQuery Maximize
	Version:		1.0
	Author:			The Uprising Creative
	Author URI:		http://theuprisingcreative.com/
	------------------------------------------------------------------
	Maximize and auto-crop/auto-scale background images

 */
 
(function($) {

	$.fn.maximize = function(options) {
	
		return this.each(function() {
			if(options) { $.extend($.fn.maximize.settings,options); }
			var el = $(this);
			el
				.css({
					position : $.fn.maximize.settings.position,
					zIndex : $.fn.maximize.settings.zIndex,
					top : '50%',
					left : '50%',
					display : 'none'
				});
			$(window).bind('resize',function() {
				$.fn.maximize.resizeElement(el);
			});
			el.load(function() {
				setTimeout(function() {
					$.fn.maximize.resizeElement(el); 
				},100);
			});
		});
	};
	
	$.fn.maximize.settings = {
		position : 'fixed',
		zIndex : 1,
		follow : 'both'
	};
		
	$.fn.maximize.getWindowSize = function() {
		var win = {};
		// IE compat mode
		if(document.body && document.body.offsetWidth) {
			win.width = document.body.offsetWidth;
			win.height = document.body.offsetHeight;
		}
		// IE standards mode
		if(document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) {
			win.width = document.documentElement.offsetWidth;
			win.height = document.documentElement.offsetHeight;
		}
		// Other browsers
		if(window.innerWidth && window.innerHeight) {
			win.width = window.innerWidth;
			win.height = window.innerHeight;
		}
		win.ratio = win.width/win.height;
		return win;
	};

	$.fn.maximize.resizeElement = function(el) {
		var win = $.fn.maximize.getWindowSize();
		var imgDOM = $(el[0]);
		var imgWidth = (imgDOM.attr('width')) ? imgDOM.attr('width') : ((el[0].naturalWidth) ? el[0].naturalWidth : el[0].width);
		var imgHeight = (imgDOM.attr('height')) ? imgDOM.attr('height') : ((el[0].naturalHeight) ? el[0].naturalHeight : el[0].height);
		var img = {
			width : imgWidth,
			height : imgHeight,
			ratio : imgWidth/imgHeight
		};
		var nw;
		var nh;
		switch($.fn.maximize.settings.follow) {
			case 'width':
				nw = win.width;
				nh = win.width/img.ratio;
				break;
			case 'height':
				nw = win.height*img.ratio;
				nh = win.height;
				break;
			case 'both':
				nw = win.height*img.ratio;
				nh = win.height;
				if(nw<win.width) {
					nw = win.width;
					nh = win.width/img.ratio;
				}
				break;
		}
		el
			.css({
				width : nw,
				height : nh,
				marginLeft : -1*(nw/2),
				marginTop : -1*(nh/2),
				display : 'block'
			});
	}

})(jQuery);
