﻿var Ticker = new Class({
	setOptions: function(options) {
		this.options = Object.extend({
			speed: 1500,
			delay: 5000,
			direction: 'vertical',
			onComplete: Class.empty,
			onStart: Class.empty
		}, options || {});
		this.itemDirection = 'next';
	},
	
	initialize: function(el,options,itemDirection){
		this.setOptions(options);
		if (itemDirection) {
		    this.itemDirection = itemDirection;
		}
		
		this.el = $(el);
		this.items = this.el.getElements('li');
		var w = 0;
		var h = 0;
		if(this.options.direction.toLowerCase()=='horizontal') {
			h = this.el.getSize().y;
				this.items.each(function(li,index) {
				w += li.getSize().x;
			});
	    } else {
			w = this.el.getSize().x;
			this.items.each(function(li,index) {
				h += li.getSize().y;
			});
		}
		this.el.setStyles({
			position: 'absolute',
			top: 0,
			left: 0,
			width: w,
			height: h
		});
		
		this.fxPrevToLast = new Fx.Morph(this.el,{duration:this.options.speed,onComplete:function() {
			var i = (this.current==0)?this.items.length:this.current;
			this.items[i-1].injectInside(this.el);
			this.el.setStyles({
				top:0,
				left:0
			});
		}.bind(this)});
		
		this.fxLastToFirst = function() {
			this.items[this.current].injectTop(this.el);
			
			var i = (this.current==this.items.length-1)?0:this.current+1;
			this.el.setStyles({
				top:-this.items[i].offsetTop,
				left:-this.items[i].offsetLeft
			});
			
			var fxMorphLastToFirst = new Fx.Morph(this.el,{duration:this.options.speed});
			fxMorphLastToFirst.start({
			    top: 0,
			    left: 0
		    });
		}.bind(this);
		
		this.current = 0;
		
		if (this.itemDirection == 'previous'){
		    this.items[this.items.length-1].injectTop(this.el);
			this.el.setStyles({
			    top: -this.items[this.items.length-1].offsetTop,
			    left: -this.items[this.items.length-1].offsetLeft
			});
		}
		
		this.play();
	},
	
	play: function() {
	    if(this.itemDirection.toLowerCase()=='previous') {
	        this.previous();
	    } else {
	        this.next();
	    }
		
		tickerTimer = this.play.bind(this).delay(this.options.delay+this.options.speed);
	}, 
	
	pause: function() {
	    $clear(tickerTimer);
	    tickerTimer = null;
	}, 
	
	resume: function() {
	    if (tickerTimer == null) {
	        this.play();
	    }
	}, 
	
	next: function() {
		this.current++;
		if (this.current >= this.items.length) { this.current = 0; }
		var pos = this.items[this.current];
		this.fxPrevToLast.start({
			top: -pos.offsetTop,
			left: -pos.offsetLeft
		});
	}, 
	
	previous: function() {
		this.current--;
		if (this.current < 0) { this.current = this.items.length-1; }
		this.fxLastToFirst();
	}, 
	
	clickNext: function() {
	    this.pause();
	    if (tickerTimer == null) {
	        this.next();
	    }
	}, 
	
	clickPrevious: function() {
	    this.pause();
	    if (tickerTimer == null) {
	        this.previous();
	    }
	}
	
});

var tickerTimer = null;


