window.addEvent('domready', function() {
	if ($('fp-banner')) {
		var BScroller = new Class( {
			initialize : function() {
				this.current = 0;
				this.items = $$('#fp-banner table.fpb-item');
				this.timer = null;
				this.allow_change = true;
				this.setActionHandlers();
				this.interval = parseInt(this.items[0].title * 1000);1
				
				this.startTimer();
			}
		});
		BScroller.implement( {
			setActionHandlers : function() {
				var obj = this;
				$$('#fp-banner a.banner_prev').each( function(link) {
					link.addEvent('click', function(e) {
						new Event(e).stop();
						obj.showPrev();
					});
				});
				$$('#fp-banner a.banner_next').each( function(link) {
					link.addEvent('click', function(e) {
						new Event(e).stop();
						obj.showNext();
					});
				});
			},
			show : function(item_id) {
				var obj = this;
				obj.allow_change = false;
				var hide_ef = new Fx.Morph(obj.items[obj.current], {
					duration : 100,
					onComplete : function() {
						obj.items[obj.current].addClass('hidden');
						obj.current = item_id;
						obj.items[obj.current].setStyle('opacity', 0);
						obj.items[obj.current].removeClass('hidden');
						var show_ef = new Fx.Morph(obj.items[obj.current], {
							duration : 800,
							onComplete : function() {
								obj.allow_change = true;
							}
						});
						show_ef.start( {
							opacity : [ 0, 1 ]
						});
					}
				});
				hide_ef.start( {
					opacity : [ 1, 0 ]
				});
			},
			showPrev : function() {
				this.stopTimer();
				if (!this.allow_change) {
					return;
				}
				if (this.current == 0) {
					this.show(this.items.length - 1);
				} else {
					this.show(this.current - 1);
				}
			},
			showNext : function() {
				this.stopTimer();
				if (!this.allow_change) {
					return;
				}
				if (this.current == this.items.length - 1) {
					this.show(0);
				} else {
					this.show(this.current + 1);
				}
			},
			stopTimer : function() {
				if (this.timer) {
					clearInterval(this.timer);
				}
			},
			startTimer : function() {
				var obj = this;
				
				obj.timer = setInterval( function() {
					
					if (obj.current < obj.items.length - 1) {
						var next = obj.current + 1;
					} else {
						var next = 0;
					}
					
					obj.interval = parseInt(obj.items[next].title * 1000);
					obj.show(next);
					
					obj.stopTimer();
					obj.startTimer();
					
				}, obj.interval);
			}
		});
		new BScroller;
	}
});
