
var DWScroller = {
	scrollClass : "scroller",
	buttonClass : "scrollBtn",
	styleSheetPath : "css/scroller.css",
	Scroller : function(obj) {
		var currentLeft = 0, vel = 0, targetLeft = 0, img = obj.getElementsByTagName("img")[0], imgWidth = img.offsetWidth + 10;
		var acc = 0.4, deacc = 8, animating = false, leftBtn, rightBtn, num = 0;
		var images = img.parentNode.parentNode;
		var scroller = this;
		this.drawButtons = function() {
			leftBtn = document.createElement("div");
			rightBtn = document.createElement("div");
			var inner = obj.getElementsByTagName("div")[0];

			leftBtn.className = rightBtn.className = DWScroller.buttonClass;
			leftBtn.className += " left";
			rightBtn.className += " right";

			inner.appendChild(leftBtn);
			inner.appendChild(rightBtn);

			leftBtn.onclick = function() {
				if (!animating) scroller.moveLeft();
			}

			rightBtn.onclick = function() {
				if (!animating) scroller.moveRight();
			}

			this.updateButtons();
		}

		this.updateButtons = function() {
			leftBtn.style.display = (num == 0)?"none":"block";
			rightBtn.style.display = (num == obj.getElementsByTagName("img").length-2)?"none":"block";
		}

		this.moveLeft = function() {
			num--;
			animating = true;
			targetLeft = currentLeft + imgWidth;
			scroller.animate();
		}

		this.moveRight = function() {
			num++;
			animating = true;
			targetLeft = currentLeft - imgWidth;
			scroller.animate();
		}

		this.animate = function() {
			vel = Math.round((vel+(targetLeft-currentLeft)*1/acc)/deacc);
			currentLeft += vel;
			images.style.left = currentLeft + "px";
			if (vel!=0) setTimeout(scroller.animate, 100);
			else {
				animating = false;
				currentLeft = targetLeft;
				images.style.left = currentLeft + "px";
			}
			scroller.updateButtons();
		}

		this.drawButtons();
	},
	init : function() {
		if (document.getElementsByTagName) {
			// apply scroller stylesheet
			document.write("<link rel='stylesheet' href='" + this.styleSheetPath + "' />");
			// find scroller elements
			if (window.onload) var old = window.onload;
			window.onload = function() {
				var divs = document.getElementsByTagName("DIV");
				for (var i = 0; i < divs.length; i++) {
					if (divs[i].className.indexOf(DWScroller.scrollClass)>=0)
						new DWScroller.Scroller(divs[i]);
				}
				if (old) old();
			}
		}
	}
}
DWScroller.init();
