/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * $Version: 2007.08.19 +r2
 *
 *
 * TIL: Drag-Opacity auskommentiert
 *
 *
 * 2008.10.5 - Andrew Hughes
 *
 *    Added full directional support (N,NE,E,SE,S,SW,W,NW)
 *    Added sizing limitations
 *
 * ==Resizing examples==
 * Assign '.handle' to resize '#box' in the 'se' direction
 * $('#box').jqResize('.handle','se');
 *
 * Assign '.handle' to resize '#box' in the 'w' direction
 * $('#box').jqResize('.handle','w');
 *
 * Assign '.handle' to resize '#box' in the 'nw' direction with a
 * minimum width of '100' and a minimum height of '200'
 * $('#box').jqResize('.handle','nw',100,200);
 *
 * ==Notes==
 * You may create as many handles and directions as you need.
 * The direction must be included.
 * Possible directions: (n, ne, e, se, s, sw, w, nw)
 */

(function($){
	$.fn.jqDrag=function(h){
		return i(this,h,'d');
	};
	$.fn.jqResize=function(h,d,mw,mh){
		return i(this,h,d,mw,mh);
	};

	$.jqDnR={
		dnr:{},
		e:0,
		drag:function(v){
	 		if(M.k == 'd')E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY});
	 		else
			{
			      $(document.body).css('cursor',M.k+'-resize');
			      var x=M.X,y=M.Y,w=M.W,h=M.H;
				if (M.k=='n'||M.k=='ne'||M.k=='nw'){y=M.Y+v.pageY-M.pY;h=M.H+(M.pY-v.pageY);}
				if (M.k=='s'||M.k=='se'||M.k=='sw')h=Math.max(v.pageY-M.pY+M.H,0);
                        if (M.k=='w'||M.k=='nw'||M.k=='sw'){x=M.X+v.pageX-M.pX;w=M.W+(M.pX-v.pageX);}
				if (M.k=='e'||M.k=='ne'||M.k=='se')w=Math.max(v.pageX-M.pX+M.W,0);
				if (w>=M.mW)E.css({width:w,left:x});
				else{E.width(M.mW);if(M.k=='w'||M.k=='nw'||M.k=='sw')E.css('left',M.X+M.W-M.mW);}
				if (h>=M.mH)E.css({height:h,top:y});
				else{E.height(M.mH);if (M.k=='n'||M.k=='ne'||M.k=='nw') E.css('top',M.Y+M.H-M.mH);}
			}
	  		return false;
		},
		stop:function(){
			//E.css('opacity',M.o);
			$(document.body).css('cursor','default');
			$().unbind('mousemove',J.drag).unbind('mouseup',J.stop);
		}
	};
	var J=$.jqDnR,M=J.dnr,E=J.e,
	i=function(e,h,k,mW,mH){
		return e.each(function(){
			h=(h)?$(h,e):e;
	 		h.bind('mousedown',{e:e,k:k},function(v){
			 	var d=v.data,p={};E=d.e;
	 			// attempt utilization of dimensions plugin to fix IE issues
	 			if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}}
	 			M={
					X:p.left||f('left')||0,
					Y:p.top||f('top')||0,
					W:f('width')||E[0].scrollWidth||0,
					H:f('height')||E[0].scrollHeight||0,
					pX:v.pageX,
					pY:v.pageY,
					k:d.k,
					//o:E.css('opacity'),
					mW:mW||0,
					mH:mH||0
				};
	 			//E.css({opacity:0.8});
				$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
	 			return false;
	 		});
		});
	},
	f=function(k){
		return parseInt(E.css(k))||false;
	};
})(jQuery);