/*

Name: Image Dimensions
Version: 0.1
Author: Budhiman
Author Website: http://www.budhiman.com
Plugin Website: http://dev.budhiman.com/image-dimensions
License: GPL

*/
(function($){
  $.fn.imageDimensions = function(options) {
  
    var settings = {
		'style': [],
		'width': 640,
		'height': 480,
		'constrain': 'width', 
		'focus': 'top' 
	  /*
		
		for width constrain: top, mid, bottom
		for height: constrain: left, mid, right
	  
	  */
    };	

	return this.each(function() {
		
		// user submitted options
		if (options) { $.extend(settings, options); }
		// make sure there's no invalid focus option, if it's there reset properly
		if (settings.constrain == 'width') { if (settings.focus != 'top' && settings.focus != 'mid' && settings.focus != 'bottom') settings.focus = 'top'; }
		else { if (settings.focus != 'left' && settings.focus != 'mid' && settings.focus != 'right') settings.focus = 'left'; }				
		
		var style = 'width:' + settings.width + 'px;height:' + settings.height + 'px;overflow:hidden;position:relative;';
		
		// there is a custom style of this element
		if (this.id in settings.style) {
			var css = settings.style[this.id];		
			var estyle = '';
			for (var s in css) {
				if (s == 'width' || s == 'height') estyle += s +': '+ parseInt(css[s]) + ';';
				else estyle += s +': '+ css[s] + ';';
			}
			style += estyle;			
			// put on the cropper div
			$(this).wrap('<div style="'+ style +'">');
		}
		else {
			// put on the cropper div
			$(this).wrap('<div style="'+ style +'">');
		}

		// image needs to be absolute positioned for 'cropping'
		$(this).css('position', 'absolute');
		
		var w = $(this).width();
		var h = $(this).height();		

		if (settings.constrain == 'width') { if (w != settings.width) { $(this).width(settings.width); } }
		else { if (h != settings.height) { $(this).height(settings.height); } }
	
		var adjust = {x:0, y:0};
		switch (settings.focus) {
			
			case 'top': break;
			case 'left': break;
			
			case 'bottom':
				if (($(this).height() > settings.height)) adjust.y = -1 * ($(this).height() - settings.height);				
				break;			
			
			case 'right':				
				if ($(this).width() > settings.width) { adjust.x = -1 * ($(this).width() - settings.width); }
				break;			

			case 'mid':
				if (settings.constrain == 'width') { adjust.y = -1 * ($(this).height() - settings.height) / 2; }
				else { adjust.x = -1 * ($(this).width() - settings.width) / 2; }
				break;	
		}
		
		$(this).css({'left':adjust.x, 'top':adjust.y});
		
	});

  };
})(jQuery);

