var Ticker = Class.create({

	initialize: function(container, options) {  
		this.container = container;  
		this.options = Object.extend(options || {},{  
			frequency: 500,  
			item_frequency: 1000,  
			char_frequency: 50,  
			endBits: ['_','-']  
		});  
		this.paused = false;
		this.current = 0;  
		this.currentChar = 0;
		this.startTick();  
	},  
	startTick: function() {
		var _this = this;
		this.container.each(function(item) {
			item.hide();
			item.observe("mouseover", function() {
				_this.pause(true);
			});
			item.observe("mouseout", function() {
				_this.resume(true);
			});
		});
		var _this = this;
		this.pe = new PeriodicalExecuter(function(pe) {
			pe.stop();
			_this.onTick();
		}, this.options.frequency / 1000);
	},
	
	onTick: function() {
		if (!this.paused) {
			if(this.currentChar==0) {
				if (this.current_item) {
					this.current_item.hide();
				}
				this.current_item = this.container[this.current%this.container.length];
				this.current_item.show();
				this.current_element = this.current_item.firstDescendant();
				this.current_title = this.current_element.innerHTML;
				this.current++;
			}
	
			this.current_element.innerHTML = this.current_title.substring(0,this.currentChar) + this.options.endBits[this.currentChar&this.options.endBits.length-1];
			if(this.currentChar==this.current_title.length) {
				this.current_element.innerHTML = this.current_title.substring(0,this.current_title.length);
				this.currentChar=0;
				var t = this.options.item_frequency || 1000;
			} else {
				this.currentChar++;
				var t = this.options.char_frequency || 50;
			}
			
			var _this = this;
			this.pe = new PeriodicalExecuter(function(pe) {
				pe.stop();
				_this.onTick();
			}, t / 1000);
		}
	}, 
	
	stopTick: function(){
//			console.log("testing observer");    
////			console.log("1 "+this.current_element.innerHTML);
			
	},
	
	pause: function(showAll) {
		this.paused = true;
		if (this.pe) {
			this.pe.stop();
			this.pe = null;
		}
		if (showAll)
			this.current_element.innerHTML = this.current_title;
	},
	
	resume: function(showAll) {
		if (this.paused) {
			this.paused = false;
			if (showAll)
				this.currentChar = this.current_title.length;
			this.onTick();
		}
	},
	
	prev: function() {			
		this.pause();
		this.current_element.innerHTML = this.current_title;
		this.currentChar = 0;
		this.current = this.current > 1 ? this.current - 2 : 0;
		this.resume();
	},
	
	next: function() {
		this.pause();
		this.current_element.innerHTML = this.current_title;
		this.currentChar = 0;
		this.resume();
	}
});  

