var DOMEvent = {
	add : function(el, evtType, handler, capture)
	{
		if (el.addEventListener)
		{
			el.addEventListener(evtType, handler, capture);
		}
		else if (el.attachEvent)
		{
			el.attachEvent('on' + evtType, handler);
		}
		else {
			el['on' + evtType] = handler;
		}
	},
	
	preventDefault : function(e)
	{
		if (e.preventDefault)
		{
			e.preventDefault();
			return;
		}
		e.returnValue = false;
	}
};
function Carousel(params)
{
	this.root = params.root;
	this.length = this.root.getElementsByTagName(params.tagName).length;
	this.itemWidth = params.itemWidth;
	this.itemHeight = params.itemHeight;
	this.onChange = params.onChange;
	
	if (params.visibleItems)
	{
		this.visibleItems = params.visibleItems;
	}
	
	this.root.style.width = (this.length * this.itemWidth) + 20 + 'px'; 
	this._initHandlers(params.prevButton, params.nextButton);
}

Carousel.prototype = {
	constructor : Carousel,
	activeIndex : 1,
	visibleItems : 3,
	
	_initHandlers : function(prev, next)
	{
		var self = this;
		if (prev)
		{
			DOMEvent.add(prev, 'click', function(e){self.movePrev(); DOMEvent.preventDefault(e);}); 
		}
		if (next)
		{
			DOMEvent.add(next, 'click', function(e){self.moveNext(); DOMEvent.preventDefault(e);});
		}
		prev = next = null;
	},
	
	setActiveIndex : function(index)
	{
		if (this.activeIndex !== index)
		{
			this.activeIndex = index;
			if (this.onChange)
			{
				this.onChange.call(this);
			}
		}
	},
	
	movePrev : function()
	{
		var index = this.activeIndex - this.visibleItems;
		if (index >= 0)
		{
			this.setActiveIndex(index);
		}
		else {
			this.setActiveIndex(0);
		}
	},
	
	moveNext : function()
	{
		if (this.length > this.visibleItems)
		{
			var index = this.activeIndex + this.visibleItems;
			if (this.length - index > this.visibleItems)
			{
				this.setActiveIndex(index);
			}
			else {
				this.setActiveIndex(this.length - this.visibleItems);
			}
		}
	}
};
