// by Jan Bobrowski
function draglist(id)
{
	this.root = document.getElementById(id)
	if(!this.root) return
	this.root.draglist = this
	this.scan()
}

draglist.prototype.scan = function() {
	var o = this.root.firstChild
	this.items = []
	for(var i=0; o; o=o.nextSibling) {
		if(!o.tagName) continue
		o.onmousedown = this.down
		o.dl_idx = i
		this.items[i++] = o
		o.style.cursor = "default"
	}
}

draglist.prototype.yof = function(e) {
	var y = e.offsetTop
	while(e = e.offsetParent)
		y += e.offsetTop
	return y
}

draglist.prototype.down = function(e) {
	if(!e) e = window.event
	var o=this, c,l,y

	c = o.parentNode
	l = c.draglist
	if(l.items.length<=1) return true
	document.dl_dragged = o
	l.rooty = l.yof(c)
	y = l.yof(o)
	l.prevy = e.clientY
	l.handy = e.clientY - y + c.scrollTop
	l.origy = y - l.rooty

	document.onmousemove = l.move
	document.onmouseup = l.up
	return false
}

draglist.prototype.posfor = function(y) {
	var o,a=0,b=this.items.length,i=0
	y += this.rooty
	for(;;) {
		o = this.items[i]
		if(y < this.yof(o) + o.offsetHeight/2) b = i
		else a = i
		i = a+b>>1
		if(i == a) break
	}
	return b
}

draglist.prototype.move = function(e) {
	if(!e) e = window.event
	var o,c,l,y,m,d,i

	o = this.dl_dragged
	c = o.parentNode
	l = c.draglist
	y = e.clientY - l.rooty - l.handy

	m = c.offsetHeight-o.offsetHeight
	d = e.clientY - l.prevy
	l.prevy += d
	if(d < 0) {
		if(y < 0) c.scrollTop += y
	} else {
		if(y > m) c.scrollTop += y - m
	}
	y += c.scrollTop

	i = l.posfor(y + (d<0 ? 0 : o.offsetHeight))
	if(i<o.dl_idx || i>o.dl_idx+1) {
		c.removeChild(o)
		if(i < l.items.length)
			c.insertBefore(o, l.items[i])
		else
			c.appendChild(o)
		l.origy = l.yof(o) - l.rooty - (parseInt(o.style.top)||0)
		l.scan()
	}

	if(y<0) y=0; else {
		m = c.scrollHeight-o.offsetHeight
		if(y > m) y = m
	}
	o.style.top = (y - l.origy)+"px"

	return false
}

draglist.prototype.up = function(e) {
	if(!e) e = window.event
	var o,c,l

	o = this.dl_dragged
	c = o.parentNode
	l = c.draglist
	if(l.origy+o.offsetHeight > c.scrollTop+c.offsetHeight)
		c.scrollTop = l.origy+o.offsetHeight-c.offsetHeight
	if(l.origy < c.scrollTop)
		c.scrollTop = l.origy

	this.dl_dragged = null
	this.onmousemove = null
	this.onmouseup = null

	o.style.top = "0px"
	return false
}

