var rootpath = "";
var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag	= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup	= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

ssScroll.prototype.scrollNorth = function(count) { this.startScroll(90, count) }
ssScroll.prototype.scrollSouth = function(count) { this.startScroll(270, count) }
ssScroll.prototype.scrollWest = function(count) { this.startScroll(180, count) }
ssScroll.prototype.scrollEast = function(count) { this.startScroll(0, count) }

ssScroll.prototype.startScroll = function(deg, count) {
	if (this.loaded){
		if (this.aniTimer) window.clearTimeout(this.aniTimer)
		this.overrideScrollAngle(deg)
		this.speed = this.origSpeed
		this.lastTime = (new Date()).getTime() - this.y.minRes
		this.aniTimer = window.setTimeout(this.gRef + ".scroll('"+deg+"','"+count+"')", this.y.minRes)
	}
}

ssScroll.prototype.endScroll = function() {
	if (this.loaded){
		window.clearTimeout(this.aniTimer)
		this.aniTimer = 0;
		this.speed = this.origSpeed
	}
}

ssScroll.prototype.overrideScrollAngle = function(deg) {
	if (this.loaded){
		deg = deg % 360
		if (deg % 90 == 0) {
			var cos = deg == 0 ? 1 : deg == 180 ? -1 : 0
			var sin = deg == 90 ? -1 : deg == 270 ? 1 : 0
		} 
		else {
			var angle = deg * Math.PI / 180
			var cos = Math.cos(angle)
			var sin = Math.sin(angle)
			sin = -sin
		}
		this.fx = cos / (Math.abs(cos) + Math.abs(sin))
		this.fy = sin / (Math.abs(cos) + Math.abs(sin))
		this.stopH = deg == 90 || deg == 270 ? this.scrollLeft : deg < 90 || deg > 270 ? this.scrollW : 0
		this.stopV = deg == 0 || deg == 180 ? this.scrollTop : deg < 180 ? 0 : this.scrollH
	}
}

ssScroll.prototype.overrideScrollSpeed = function(speed) {
	if (this.loaded) this.speed = speed
}


ssScroll.prototype.scrollTo = function(stopH, stopV, aniLen) {
	if (this.loaded){
		if (stopH != this.scrollLeft || stopV != this.scrollTop) {
			if (this.aniTimer) window.clearTimeout(this.aniTimer)
			this.lastTime = (new Date()).getTime()
			var dx = Math.abs(stopH - this.scrollLeft)
			var dy = Math.abs(stopV - this.scrollTop)
			var d = Math.sqrt(Math.pow(dx,2) + Math.pow(dy,2))
			this.fx = (stopH - this.scrollLeft) / (dx + dy)
			this.fy = (stopV - this.scrollTop) / (dx + dy)
			this.stopH = stopH
			this.stopV = stopV
			this.speed = d / aniLen * 1000
			window.setTimeout(this.gRef + ".scroll()", this.y.minRes)
		}
	}
}

ssScroll.prototype.jumpTo = function(nx, ny) { 
	if (this.loaded){
		nx = Math.min(Math.max(nx, 0), this.scrollW)
		ny = Math.min(Math.max(ny, 0), this.scrollH)
		this.scrollLeft = nx
		this.scrollTop = ny
		if (this.y.ns4)this.content.moveTo(-nx, -ny)
		else {
			this.content.style.left = -nx + "px"
			this.content.style.top = -ny + "px"
		}
	}
}

ssScroll.minRes = 10
ssScroll.ie = document.all ? 1 : 0
ssScroll.ns4 = document.layers ? 1 : 0
ssScroll.dom = document.getElementById ? 1 : 0
ssScroll.mac = navigator.platform == "MacPPC"
ssScroll.mo5 = document.getElementById && !document.all ? 1 : 0

ssScroll.prototype.scroll = function(deg,count) {
	this.aniTimer = window.setTimeout(this.gRef + ".scroll('"+deg+"','"+count+"')", this.y.minRes)
	var nt = (new Date()).getTime()
	var d = Math.round((nt - this.lastTime) / 1000 * this.speed)
	if (d > 0){
		var nx = d * this.fx + this.scrollLeft
		var ny = d * this.fy + this.scrollTop
		var xOut = (nx >= this.scrollLeft && nx >= this.stopH) || (nx <= this.scrollLeft && nx <= this.stopH)
		var yOut = (ny >= this.scrollTop && ny >= this.stopV) || (ny <= this.scrollTop && ny <= this.stopV)
		if (nt - this.lastTime != 0 && 
			((this.fx == 0 && this.fy == 0) || 
			(this.fy == 0 && xOut) || 
			(this.fx == 0 && yOut) || 
			(this.fx != 0 && this.fy != 0 && 
			xOut && yOut))) {
			this.jumpTo(this.stopH, this.stopV)
			this.endScroll()
		}
		else {
			this.jumpTo(nx, ny)
			this.lastTime = nt
		}
	// update dragger position:
	if(deg=='270')	theThumb[count].style.top = parseInt(((theThumb[count].maxY-theThumb[count].minY)*this.scrollTop/this.stopV)+theThumb[count].minY) + "px"; //ok nomes down
	if(deg=='90')	theThumb[count].style.top = parseInt(((theThumb[count].maxY-theThumb[count].minY)*this.scrollTop/this.scrollH)+theThumb[count].minY) + "px"; //ok nomes down
	}
}

function ssScroll(id, left, top, width, height, speed) {
	var y = this.y = ssScroll
	if (document.layers && !y.ns4) history.go(0)
	if (y.ie || y.ns4 || y.dom) {
		this.height = height 
		this.loaded = false
		this.id = id
		this.origSpeed = speed
		this.aniTimer = false
		this.op = ""
		this.lastTime = 0
		this.clipH = height
		this.clipW = width
		this.scrollTop = 0
		this.scrollLeft = 0
		this.gRef = "ssScroll_"+id
		eval(this.gRef+"=this")
		var d = document
		
		d.write('<style type="text/css">')
		d.write('#' + this.id + 'Container { left:' + left + 'px; top:' + top + 'px; width:' + width + 'px; height:' + height + 'px; clip:rect(0 ' + width + ' ' + height + ' 0); overflow:hidden; }')
		d.write('#' + this.id + 'Container, #' + this.id + 'Content { position:absolute; }')
		d.write('#' + this.id + 'Content { left:' + (-this.scrollLeft) + 'px; top:' + (-this.scrollTop) + 'px; width:' + width  + 'px; }')
			// fix to overwrite p/div/ul width (would be clipped if wider than scroller in css):
		d.write('#' + this.id + 'Container .scrolltextcontent {width:' + parseInt(width-25) + 'px; }')
		d.write('</style>')
	}
}

ssScroll.prototype.load = function(heightoffset) {
	var d, lyrId1, lyrId2
	d = document
	lyrId1 = this.id + "Container"
	lyrId2 = this.id + "Content"
	this.container = this.y.dom ? d.getElementById(lyrId1) : this.y.ie ? d.all[lyrId1] : d.layers[lyrId1]
	this.content = obj2 = this.y.ns4 ? this.container.layers[lyrId2] : this.y.ie ? d.all[lyrId2] : d.getElementById(lyrId2)
	this.docH = Math.max(this.y.ns4 ? this.content.document.height : this.content.offsetHeight, this.clipH)

	
	this.docW = Math.max(this.y.ns4 ? this.content.document.width : this.content.offsetWidth, this.clipW)
	this.scrollH = this.docH - this.clipH + heightoffset;
	this.scrollW = this.docW - this.clipW
	this.loaded = true
	this.scrollLeft = Math.max(Math.min(this.scrollLeft, this.scrollW),0)
	this.scrollTop = 0;//Math.max(Math.min(this.scrollTop, this.scrollH),0)
	this.jumpTo(this.scrollLeft, this.scrollTop)
}


var theHandle = []; 
var theRoot = []; 
var theThumb = []; 
var theScroll = []; 
var thumbTravel = []; 
var ratio = [];

function instantiateScroller(count, id, left, top, width, height, speed, heightoffset){
	//if heightoffset is -1 then initialise the scrollers otherwise re-initialise the scrollers 
	if(document.getElementById) {
		if(heightoffset == -1){
			theScroll[count] = new ssScroll(id, left, top, width, height, speed);
		}else{
			initDragger(heightoffset);
		}
	}
}

function clearDragger(count){
	var root = document.getElementById('root' + count);
	
	if(root.hasChildNodes){
		var bar = document.getElementById('bar'+count);
		if(bar){
			root.removeChild(bar);
		}
		
		var up = document.getElementById('up'+count);
		if(up){
			root.removeChild(up);
		}
		
		var dn = document.getElementById('dn'+count);
		if(dn){
			root.removeChild(dn);
		}
		
		var thumb = document.getElementById('thumb'+count);
		if(thumb){
			root.removeChild(thumb);
		}
	}
}

function createDragger(count, handler, root, thumb, minX, maxX, minY, maxY, heightoffset){
		if (!document.getElementById(root))
		{
			return;
		}

		var buttons = '<div class="bar" id="bar'+count+'" style="left: 0px; top: 17px;">'+
		              '<img src="'+rootpath+'images/sb_vbar.gif" width="17" height="'+(maxY-17)+'"></div>'+
					  '<div class="up" id="up'+count+'">'+
		              '<a href="#" onmousedown="theScroll['+count+'].scrollNorth(\''+count+'\')" '+
		              'onmouseout="theScroll['+count+'].endScroll();scrollbarimage('+count+',\'up\',false);" onclick="theScroll['+count+'].endScroll();return false;" onmouseover="scrollbarimage('+count+',\'up\',true);">'+
		              '<img name="sb'+count+'up" src="'+rootpath+'images/sb_up.gif" width="17" height="17"></a></div>'+
		              '<div class="dn"  id="dn'+count+'"">'+
		              '<a href="#" onmousedown="theScroll['+count+'].scrollSouth(\''+count+'\')" '+
		              'onmouseout="theScroll['+count+'].endScroll();scrollbarimage('+count+',\'down\',false);" onclick="theScroll['+count+'].endScroll();return false;" onmouseover="scrollbarimage('+count+',\'down\',true);">'+
		              '<img name="sb'+count+'down" src="'+rootpath+'images/sb_down.gif" width="17" height="17"></a></div>'+
		              '<div class="thumb" id="'+thumb+'" style="left: 0px; top: 17px;">'+
		              '<img name="sb'+count+'vdrag" src="'+rootpath+'images/sb_vdrag.gif" width="17" height="157" onmouseover="scrollbarimage('+count+',\'vdrag\',true);" onmouseout="scrollbarimage('+count+',\'vdrag\',false);" onmouseup="scrollbarimage('+count+',\'vdrag\',false);"></div>';

		
		clearDragger(count);
				
		document.getElementById(root).innerHTML = buttons + document.getElementById(root).innerHTML;

		theRoot[count]   = document.getElementById(root);
		theThumb[count]  = document.getElementById(thumb);
		var thisup = document.getElementById("up"+count);
		var thisdn = document.getElementById("dn"+count);
		var thisbar = document.getElementById("bar"+count);
		var thiscontainer=document.getElementById("scroll"+count+"Container");
		var thiscontent=document.getElementById("scroll"+count+"Content");

		theThumb[count].style.left = parseInt(minX) + "px";
		thisup.style.left = parseInt(minX) + "px";
		thisdn.style.left = parseInt(minX) + "px";
		theThumb[count].style.border =0;
		theThumb[count].style.top = parseInt(minY+0) + "px";
		thisup.style.top = 0 + "px";
		thisdn.style.top = parseInt(minY+maxY-17) + "px";
		//thisdn.style.top = 15 + "px";
		
		thisbar.style.left= parseInt(minX) + "px";
		thisbar.style.top = 13 + "px";

		theScroll[count].load(heightoffset);

		//Drag.init(theHandle[count], theRoot[count]); //not draggable on screen
		if (navigator.userAgent.indexOf("MSIE")==-1){
			Drag.init(theThumb[count], null, minX, maxX, minY+0, maxY-157+157-157+1);
		}else{
			Drag.init(theThumb[count], null, minX, maxX, minY+0, maxY-157+157-157+1);
		}
		
		// the number of pixels the thumb can travel vertically (max - min)
		thumbTravel[count] = theThumb[count].maxY - theThumb[count].minY;

		// the ratio between scroller movement and thumbMovement
		ratio[count] = theScroll[count].scrollH / thumbTravel[count];
		
		if (ratio[count]==0)
		{
			thisup.style.display="none";
			thisdn.style.display="none";
			thisbar.style.display="none";
			theThumb[count].style.display="none";
			
			//thiscontainer.style.width=maxX +15+ "px";
			//thiscontent.style.width=maxX +15+"px";
			/*if (document.getElementById('forumrow1')){
				document.getElementById('forumrow1').style.width= "449px";
			}*/
			
			clearDragger(count);
		}

		theThumb[count].onDrag = function(x, y) {
			theScroll[count].jumpTo(null, Math.round((y - theThumb[count].minY) * ratio[count]));
		}
}	

function initDragger(heightoffset){
	if(theScroll.length>0) {
		for(var i=0;i<theScroll.length;i++){
			if(typeof(heightoffset) == 'number'){
				createDragger(i, "handle"+i, "root"+i, "thumb"+i, theScroll[i].clipW, theScroll[i].clipW, 17, theScroll[i].clipH-17, heightoffset);				
			}else{
				createDragger(i, "handle"+i, "root"+i, "thumb"+i, theScroll[i].clipW, theScroll[i].clipW, 17, theScroll[i].clipH-17, 0);
			}
		}
	}
}



function scrollbarimage(count,id,state)
{
	var o=document["sb"+count+id];
	o.src=rootpath + "images/sb_" + id + ((state) ? '_f2' : '') + ".gif";
}

function jumper(scrollnum,ny){
	if(navigator.userAgent.indexOf("MSIE") < 0){
		theScroll[scrollnum].jumpTo(null,ny);
	
		// Set position of the scrollbar
		theThumb[scrollnum].style.top = parseInt(((theThumb[scrollnum].maxY-theThumb[scrollnum].minY)*theScroll[scrollnum].scrollTop/theScroll[scrollnum].scrollH)+theThumb[scrollnum].minY) + "px";
	}
}

function addLoadEvent(fn) {
      var old = window.onload;
      if (typeof window.onload != 'function') {
         window.onload = fn;
      }
      else {
         window.onload = function() {
         old();
         fn();
         }
      }
   }
addLoadEvent(initDragger)


// Scroll wheel functions

/** This is high-level function.
 * It must react to delta being more/less than zero.
 */
function handle(delta, scrollContainer) {
		var scrollSpeed = 20;
		
        if (delta < 0){ // Down
			jumper(scrollContainer, theScroll[scrollContainer].scrollTop + scrollSpeed);
		}
        else{			// Up
			jumper(scrollContainer, theScroll[scrollContainer].scrollTop - scrollSpeed);
		}
}

/** Event handler for mouse wheel event.
 */
function wheel(event){
	
	if(navigator.userAgent.indexOf("MSIE") < 0){
		var tg = window.event ? event.srcElement : event.target;
		var scrollContainer = null;
		
		while ( tg ){
			if ( tg.nodeName=="DIV" && tg.id.substring(0,6)=="scroll" ){
				scrollContainer = tg.id.substring(6, 7);	
				break;
			}
			tg = tg.parentNode;
		}
		
		if(scrollContainer){
	
			var delta = 0;
			if (!event) /* For IE. */
				event = window.event;
				
			
				
			if (event.wheelDelta) { /* IE/Opera. */
				delta = event.wheelDelta/120;
			} else if (event.detail) { /** Mozilla case. */
				/** In Mozilla, sign of delta is different than in IE.
				 * Also, delta is multiple of 3.
				 */
				delta = -event.detail/3;
			}
			/** If delta is nonzero, handle it.
			 * Basically, delta is now positive if wheel was scrolled up,
			 * and negative, if wheel was scrolled down.
			 */
			if (delta)
				handle(delta, scrollContainer);
			/** Prevent default actions caused by mouse wheel.
			 * That might be ugly, but we handle scrolls somehow
			 * anyway, so don't bother here..
			 */
			if (event.preventDefault)
				event.preventDefault();
			
			event.returnValue = false;
		}
	}
}

/** Initialization code. 
 * If you use your own event management code, change it as required.
 */
if (window.addEventListener)
	/** DOMMouseScroll is for mozilla. */
	window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;
