/**
 * FBTO
 * 
 * @version		1.00.110520
 * @author		LBi, Amsterdam
 *
 */

window.FBTO = (function($) {
	
	Function.prototype.bind = function(scope) {
		var method = this;
		return function() {
			return method.apply(scope, arguments);
		};
	};
	
	var FBTO = {
		
		init: function() {
			this.Banner.init();
		}
		
	};
	
	FBTO.Banner = {
		
		init: function() {
			this.root = $('#banner');
			this.reel = $('.banner-items', this.root);
			this.items = $('.banner-item', this.reel);
			this.nav = $('.banner-nav', this.root);
			this.title = $('.banner-title', this.nav);
			this.arrow = $('.banner-arrow', this.nav);
			
			$('input', this.root).focus(this.stop.bind(this));
			
			this.width = this.root.width();
			this.length = this.items.length;
			
			this.index = 0;
			
			this.setDimensions();
			
			this.initNav();
			this.initBaloons();
			
			this.start();
		},
		
		setDimensions: function() {
			this.reel.width(this.length * this.width);
		},
		
		initNav: function() {
			this.setNav();
			var links = $('li a', this.nav);
			links.click(this.moveto.bind(this));
		},
		
		initBaloons: function() {
			this.items.not(':eq(0)').find('.banner-baloon').hide();
		},
		
		setNav: function() {
			var active = this.nav.find('li').eq(this.index);
			var title = active.find('a').text();
			
			this.arrow.stop().animate({
				left: this.index * 20 -660
			}, this.settings.duration); 
			
			this.title.fadeOut(this.settings.duration / 2);
			
			setTimeout(function() {
				active.addClass('active');
				active.siblings().removeClass('active');
				this.title.text(title);
				this.title.fadeIn(this.settings.duration / 2);
			}.bind(this), this.settings.duration / 2);
		},
		
		count: function() {
			return this.items.length;
		},
		
		start: function() {
            this.stop();
            this.timer = setInterval(this.next.bind(this), this.settings.delay);
        },

        stop: function() {
            clearInterval(this.timer);
        },
		
        pause: function() {
            this.stop();
        },
		
        resume: function() {
            this.start();
        },
        
        next: function() {
			if (this.index + 1 === this.length) {
				this.index = 0;
			} else {
				this.index++;
			}
			
            this.animate();
        },
		
		moveto: function(e) {
			e.preventDefault();
			this.stop();
			var link = $(e.target).closest('li');
			var index = link.index();
			if (index !== this.index) {
				this.index = link.index();
				this.animate();
			}
		},
		
		animate: function() {
			this.reel.stop().animate({
				marginLeft: this.index * -this.width
			}, this.settings.duration);
			
			this.setNav();
			
			this.items.not(':eq(' + this.index + ')').find('.banner-baloon').fadeOut(this.settings.duration);
			this.items.eq(this.index).find('.banner-baloon').fadeIn(this.settings.duration);
		},
		
		settings: {
			delay: 5000,
			duration: 500
		}
		
	};
	
	$(function() {
		FBTO.init();
	});
	
	return FBTO;
	
}(jQuery));
