/**
 * Ticker.js - A tiny whatever ticker ;-)
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

var Ticker = function(id) {
	var ticker,
	    interval,
	    tickerItems,
		tickerWidth,
		contentWidth,
		scrollSpeed = 1,
		visibleItems = 7,
		extraMargin = 10,
		duration = 30;
	
	return {
		initialize: function() {
			ticker = $(id);
			tickerItems = WS.DOM.getElementsByClass('ticker-item', ticker);
			if(tickerItems.length > visibleItems)
				this.initEvents();
		},
		initEvents: function() {
			tickerWidth = ticker.offsetWidth;
			contentWidth = (tickerItems.last().offsetLeft + tickerItems.last().offsetWidth + extraMargin);
			
			WS.Event.addEvent(ticker, 'mouseover', function() { this.stop(); }.bind(this));
			WS.Event.addEvent(ticker, 'mouseout', function() { this.start(); }.bind(this));
			WS.Event.addEvent('ticker-rewind', 'mouseover', function() { this.rewind(); }.bind(this));
			WS.Event.addEvent('ticker-rewind', 'mouseout', function() { this.stop(); this.start(); }.bind(this));
			WS.Event.addEvent('ticker-forward', 'mouseover', function() { this.forward(); }.bind(this));
			WS.Event.addEvent('ticker-forward', 'mouseout', function() { this.stop(); this.start(); }.bind(this));
			
			var content = $('brand-ticker-content');
			for(var i = 0; i < tickerItems.length; i++) {
				content.appendChild(tickerItems[i].cloneNode(true));
			}
			
			this.start();
		},
		start: function() {
			interval = setInterval(function() {
				this.scroll(scrollSpeed);
			}.bind(this), duration);
		},
		stop: function() {
			clearInterval(interval);
		},
		scroll: function(offset) {
			if(ticker.scrollLeft < contentWidth)
				ticker.scrollLeft += offset;
			else
				ticker.scrollLeft = 0;
		},
		rewind: function() {
			this.stop();
			
			interval = setInterval(function() {
				this.scroll(-5);
			}.bind(this), duration);
		},
		forward: function() {
			this.stop();
			
			interval = setInterval(function() {
				this.scroll(5);
			}.bind(this), duration);
		}
	}
}
