window.onload = function() {
		var sel = new Carousel('realstories', 'moveleft', 'moveright');
		sel.moveLeft.onclick = function() { if(sel.movement === false) move(sel, 'left'); };
		sel.moveRight.onclick = function() { if(sel.movement === false) move(sel, 'right'); }
}

var Carousel = function(el, ctrlLeft, ctrlRight) {
	this.el = document.getElementById(el);
	this.moveLeft = document.getElementById(ctrlLeft);
	this.moveRight = document.getElementById(ctrlRight);
	this.time = 3;	
	this.distance = this.el.parentNode.offsetWidth;	
	this.move = false;
	this.movement = false;
	
	this.moveLeft.style.display = 'inline';
	this.moveRight.style.display = 'inline';
	
	var children = this.el.getElementsByTagName('li'),
		width = getWidth(children[1]);

	this.el.style.width = (children.length * width) + "px";
		
	if (!this.el.style.left) {
		this.el.style.left = "0px";
	}
	if (!this.el.style.top) {
		this.el.style.top = "0px";
	}
	
	return this;
}

function getWidth(el) {
	var style = el.currentStyle?'marginLeft':'margin-left';
	return el.offsetWidth + parseInt(getStyle(el,style)) + parseInt(getStyle(el,style));
}

function getStyle(el,styleProp)
{
	var x = el, y;
	if (x.currentStyle) {
		y = x.currentStyle[styleProp];
	}
	else if (window.getComputedStyle)
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function move(obj, dir) {
	if (obj.movement) {
		clearTimeout(obj.movement);
	}
	
	var xPos = parseInt(obj.el.style.left);
		mover = obj.move !== false?obj.move:obj.distance;
	
	switch(dir) {
		case 'left':
			final_x = xPos + mover;
			break;
		case 'right':
			final_x = xPos - mover;
	}
	
	if (xPos == final_x || 
	   (xPos === 0 && dir == 'left') ||
	   (!(xPos%obj.distance) && obj.el.offsetWidth <= (Math.abs(xPos)+obj.distance) && dir == 'right' )) {
		obj.move = obj.movement = false;
		return true;
	}
	if (xPos < final_x) {
		var dist = Math.ceil((final_x - xPos)/9);
		xPos = xPos + dist;
	}
	if (xPos > final_x) {
		var dist = Math.ceil((xPos - final_x)/9);
		xPos = xPos - dist;
	}
	
	obj.move = mover - dist;
	obj.el.style.left = xPos + "px";
	obj.movement = setTimeout(function() { move(obj, dir); }, obj.time);
}

