/*
 * simple dragdrop script 
 * return the drag-drop object's x&y position in its parent container
 * power by jquery
 *
 * script by flywolf(ircman@163.com) at 12/14/2008 02:11
 *
 * for more information visit http://www.suiyuan.org
 */

// for these html blocks whos content contain img tag, there maybe
// some bugs when user click-and-drag the block, but it doesnt
// exist when the content !contain img tag.

this.dd = function(o, c, t, initx, inity) {
	var xmin, ymin, xmax, ymax;
	var canDrag = false;
	var obj = $('#'+o);
	var container = $('#'+c);
	init();
	updatedd(o);

	obj.mousedown(function(e){
		var cx = obj[0].offsetLeft;
		var cy = obj[0].offsetTop;

		  this.X = e.pageX - cx;
		  this.Y = e.pageY - cy;
		
		canDrag = true;
	});
	obj.mouseup(function(e){
		canDrag = false;
	});
	obj.mousemove(function(e){
		if (!canDrag) return;
		updatedd();
		dx = e.pageX - this.X;
		dy = e.pageY - this.Y;
		

		if (dx < xmin) dx = xmin;
		if (dx > xmax) dx = xmax;
		if (dy < ymin) dy = ymin;
		if (dy > ymax) dy = ymax;

		//$shj('#txtContent').val('dx:'+dx+',dy:'+dy+',xmax:'+xmax+',ymax:'+ymax);

		obj
		.css("left",dx+"px")
		.css("top",dy+"px");

		  $('#'+o+'X').val(dx);
		  $('#'+o+'Y').val(dy);
		
	});
	function init() {
	  container.append('<div id="'+o+'" class="dd" style="left:'+initx+'px;top:'+inity+'px">'+t+'</div>');
	  obj = $('#'+o);

	  $('body')
		  .append('<input type="hidden" id="'+o+'X" />')
		  .append('<input type="hidden" id="'+o+'Y" />');
	  $('#'+o+'X').val(initx);
	  $('#'+o+'Y').val(inity);
	};
	
	function updatedd() {	
	  var ix = obj[0].offsetLeft;
	  var iy = obj[0].offsetTop;
	  var iw = container[0].offsetWidth;
	  var ih = container[0].offsetHeight;
	  var tw = obj[0].offsetWidth;
	  var th = obj[0].offsetHeight;
	  
//	  xmin = ix - initx;
//	  ymin = iy - inity;
	  xmin = 0;
	  ymin = 0;
//	  xmax = ix + iw - tw - initx;
//	  ymax = iy + ih - th - inity;
	  xmax = iw - tw - 2;
	  ymax = ih - th;
	};
}