(function($){//BEGIN $ = jQuery
	
	/*
	 * obj.clip(50); //縦横いっしょ
	 * obj.clip(50, 30); //幅と高さ指定
	 * obj.clip(50, {～～～});
	 * obj.clip(50, 30, {～～～});
	 * 
	 * ◆オプション
	 * ・position
	 * 		どこを切り抜くか。
	 * 		cssのbackground-positionと同じ指定方法。デフォは'center center'
	 * 		横はleft/center/right、縦はtop/center/bottom。あと左/上からの数値(px)でもOK。
	 * ・default_size
	 * 		trueにしたら元の画像の範囲はそのままにしておくよ。デフォはfalse
	 * 
	 */
	$.fn.clip = function(width, height, options){
		if(!arguments.length) return this;
		
		width = width - 0;
		if(!options && typeof height == "object"){
			options = height;
			height = null;
		}
		height = (height || width) - 0;
		options = $.extend({
			  position: 'center center'
			, default_size: false
		}, typeof options == "object" ? options : {});
		var default_size = options.default_size;
		
		this.filter('img')
			.each(function(){
				var $img = $(this);
				var img_width = this.width,
				    img_height = this.height,
				    img_pos = $img.css('position'),
				    img_css = {};
				
				if(img_pos != 'absolute'){
					if(img_pos == 'static'){
						img_css.top = 0;
						img_css.left = 0;
					}
					
					var $img_wrap = $('<span></span>').css({
						  position: 'relative'
						, display: 'inline-block'
						, width: default_size ? img_width : width
						, height: default_size ? img_height : height
					});
					if(!default_size) $img_wrap.css('overflow', 'hidden');
					
					img_css.position = 'absolute';
					$img.wrap($img_wrap);
				}
				
				var clip_pos = {};
				var opt_pos = options.position.split(' ');
				switch(opt_pos[0]){
					case 'center':
						clip_pos.left  = (img_width - width) / 2;
						clip_pos.right = clip_pos.left + width;
						break;
					case 'right':
						clip_pos.left  = img_width - width;
						clip_pos.right = img_width;
						break;
					default:
						opt_pos[0] = opt_pos[0] - 0;
						if(!opt_pos[0]) opt_pos[0] = 0;
						clip_pos.left  = opt_pos[0];
						clip_pos.right = clip_pos.left + width;
						break;
				}
				switch(opt_pos[1]){
					case 'center':
						clip_pos.top    = (img_height - height) / 2;
						clip_pos.bottom = clip_pos.top + height;
						break;
					case 'bottom':
						clip_pos.top    = img_height - height;
						clip_pos.bottom = img_height;
						break;
					default:
						opt_pos[1] = opt_pos[1] - 0;
						if(!opt_pos[1]) opt_pos[1] = 0;
						clip_pos.top    = opt_pos[1];
						clip_pos.bottom = clip_pos.top + height;
						break;
				}
				img_css.clip = ['rect(', [
					  clip_pos.top
					, clip_pos.right
					, clip_pos.bottom
					, clip_pos.left
				].join('px '), 'px)'].join('');
				
				if(!default_size){
					img_css.top  = clip_pos.top * -1;
					img_css.left = clip_pos.left * -1;
				}
				
				$img.css(img_css);
			});
		
		return this;
	};
	
	
})(jQuery);//END $ = jQuery

