(function($)
{
	$.fn.jqDrag = function(e)
	{
		$(this).each
		(
			function(e)
			{
				$(this).bind
				(
					'mousedown',

					function(e)
					{
						E = $(this);
						
						var draggable = jQuery('.draggable', E);

						if(draggable.attr('contentEditable') == 'false' || draggable.attr('contentEditable') == false)
						{
							if(e.preventDefault)
								e.preventDefault();

							e.cancelBubble = true;

							$.jqDnR.dnr =
							{
								X : parseInt(E.css('left')) || false,
								Y : parseInt(E.css('top')) || false,
								pX : e.pageX,
								pY : e.pageY
							};

							$().mousemove($.jqDnR.drag);
							$().mouseup($.jqDnR.stop);
						}
					}
				);
			}
		);
	};

	$.jqDnR =
	{
		drag : function(e)
		{
			var draggable = jQuery('.draggable', E);
			
			if(draggable.attr('contentEditable') == 'false' || draggable.attr('contentEditable') == false)
			{
				var grid_x = ($('#snapGrid').attr('checked') ? parseInt($('#grid_x').val()) : 1);
				var grid_y = ($('#snapGrid').attr('checked') ? parseInt($('#grid_y').val()) : 1);
			
				var left = $.jqDnR.dnr.X + Math.round((e.pageX - $.jqDnR.dnr.pX) / grid_x) * grid_x;
				var top = $.jqDnR.dnr.Y + Math.round((e.pageY - $.jqDnR.dnr.pY) / grid_y) * grid_y;
				
				if(parseInt(E.css('left')) < left)
					left = left - (left % grid_x);
					
				else if(parseInt(E.css('left')) > left)
					left = left + grid_x - (left % grid_x);

				if(parseInt(E.css('top')) < top)
					top = top - (top % grid_y);
					
				else if(parseInt(E.css('top')) > top)
					top = top + grid_y - (top % grid_y);
					
				if(left <= parseInt(E.parent().css('left')))
					left = parseInt(E.parent().css('left'));
					
				if(left >= parseInt(E.parent().css('left')) + parseInt(E.parent().innerWidth()) - E.outerWidth())
					left = parseInt(E.parent().css('left')) + parseInt(E.parent().innerWidth() - E.outerWidth());
					
				if(top <= parseInt(E.parent().css('top')))
					top = parseInt(E.parent().css('top'));
					
				if(top >= parseInt(E.parent().css('top')) + parseInt(E.parent().innerHeight()) - E.outerHeight())
					top = parseInt(E.parent().css('top')) + parseInt(E.parent().innerHeight() - E.outerHeight());

				E.css
				(
					{
						left : left,
						top : top
					}
				);
				
				$('#location_x').val(left);
				$('#location_y').val(top);
				
				setHorizontalGuide();
				setVerticalGuide();
			}

			return false;
		},

		stop : function()
		{
			$().unbind('mousemove', $(this).drag);
			$().unbind('mouseup', $(this).stop);
		}
	};
	
})(jQuery);