var _iWindow = null;

function ImageScrollWindow(containerId, imgsrc, width, height)
{
	this.onMouseMove = function (event)	{		
		if (_iWindow.state == 2) {	
			var diff = [event.pointerX() - _iWindow.px, event.pointerY() - _iWindow.py];
			_iWindow.setImgPos(_iWindow.sx + diff[0] * _iWindow.acc, _iWindow.sy + diff[1] * _iWindow.acc);
			event.stop();
		}
	}	
	this.onMouseUp = function (event){
		_iWindow.state = 1;
	}
	
	this.onMouseDown = function (event){
		_iWindow.state = 2;
		_iWindow.px = event.pointerX();
		_iWindow.py = event.pointerY();
		_iWindow.sx = _iWindow.x;
		_iWindow.sy = _iWindow.y;
	}
	
	this.onMouseScroll = function (event){
		event = event ? event : window.event;
		var wheelData = event.detail ? event.detail : event.wheelDelta;
		var offset = 0;
		if (wheelData > 0) offset = 30;
		if (wheelData < 0) offset = -30;
		_iWindow.setImgPos(_iWindow.x, _iWindow.y + offset);	
		cancelEvent(event);
	}
	
	this.setImgPos = function (x, y) {
		if (x > 0) x = 0;
		if (y > 0) y = 0;		
		if (Math.abs(x) + this.vpwidth > this.width)
			x = -Math.abs(this.width - this.vpwidth);			
		if (Math.abs(y) + this.vpheight > this.height)
			y = -Math.abs(this.height - this.vpheight);	
		this.div.style.backgroundPosition = x + 'px ' + y + 'px';
		this.x = x;
		this.y = y;
	}
	
	this.detectViewport = function () {
		this.vpwidth = document.viewport.getWidth();
		this.vpheight = document.viewport.getHeight();
		if (this.vpwidth == 0)
			this.vpwidth = document.body.clientWidth;			
		if (this.vpheight == 0)
			this.vpheight = document.body.clientHeight;
		this.div.style.width=this.vpwidth+'px';
		this.div.style.height=this.vpheight+'px';
		//alert(document.viewport.getWidth()+' / '+document.viewport.getHeight()+' | '+this.vpwidth+' / '+this.vpheight);
	}	
	
	this.start = function (img_src) {
		this.src = img_src;
		if (width <= this.vpwidth && height <= this.vpheight) {
			var imgs = this.div.select('img');
			if (imgs.size() == 1)
				imgs[0].style.display = 'block';			
			return;
		}
		
		this.state = 1;
		this.px = 0;
		this.py = 0;
		this.x  = 0;
		this.y  = 0;
		this.sx = 0;
		this.sy = 0;
		this.width = width;
		this.height = height;
		this.acc = 1;
	}
	
	this.div = $(containerId);	
	if (!$(containerId)) {
		alert('ImageScrollWindow error: container not found');
		return;
	}	
	this.detectViewport();			
	this.start(imgsrc);
	
	this.div.style.cursor = 'move';
	this.div.style.overflow = 'hidden';
	this.div.style.backgroundImage = 'url(' + this.src + ')';
	this.div.style.backgroundRepeat = 'no-repeat';
	this.div.observe('mousemove', this.onMouseMove);
	this.div.observe('mouseup', this.onMouseUp);
	this.div.observe('mousedown', this.onMouseDown);
	
	hookEvent(this.div, 'mousewheel', this.onMouseScroll);
	_iWindow = this;
	this.setImgPos(0, 0);
}
