var p4a = {
	
	Home: {
		
		initialize: function() {
			this.projectScroller = new NewsScroller('projects-block', { autoScrollTimeout: 11 });
		}
		
	}
	
}

var NewsScroller = new Class({
	
	Implements: Options,
	
	options: {
		autoScroll: true,
		autoScrollTimeout: 10
	},
	
	initialize: function(element, options) {
		this.setOptions(options);
		this.container = $(element).getElement('div.frames');
		this.scroll = $(element).getElement('ul.scroll');
		this.frames = $(element).getElements('li.item');
		this.counter = $(element).getElement('ul.counter');
		
		if ( this.frames.length > 1 ) {
			this.width = this.container.getWidth();

			$(element).getElement('.prev').addEvent('click', this.doScroll.bind(this, false));
			$(element).getElement('.next').addEvent('click', this.doScroll.bind(this, true));

			this.smscroll = new Fx.Scroll(this.container, { 
				duration: 1000,
				onStart: function() {
					this.isAnimation = true;
				}.bind(this),
				onComplete: function() {
					this.isAnimation = false;
				}.bind(this)
			});
			this.createCounter();
			if ( this.options.autoScroll ) this.startAutoScroll();
		} else {
			$(element).getElement('.prev').addClass('hidden');
			$(element).getElement('.next').addClass('hidden');
		}
	},
	
	startAutoScroll: function() {
		if ( this.timer ) $clear(this.timer);
		this.timer = this.doScroll.periodical(this.options.autoScrollTimeout*1000, this, [true, false]);
	},
	
	doScroll: function(direction, setup) {
		setup = setup || true;
		if ( setup && this.options.autoScroll ) this.startAutoScroll();
		if ( !this.isAnimation ) {
			this.counters[this.current].removeClass('active');
			if ( direction ) {
				this.current = this.current + 1 > this.frames.length - 1 ? 0 : ++this.current;
			} else {
				this.current = this.current - 1 < 0 ? this.frames.length - 1 : --this.current;
			}
			this.smscroll.start(this.width * this.current, 0);
			this.counters[this.current].addClass('active');
		}
	},
	
	createCounter: function() {
		this.frames.each(function(item){
			item.setStyle('width', this.width);
			new Element('li').inject(this.counter);
		}.bind(this));
		this.counter.getElement('li').addClass('active');
		this.scroll.setStyle('width', this.width*this.frames.length);
		this.current = 0;
		
		this.counters = this.counter.getElements('li');
	}
	
});

document.addEvent('domready', p4a.Home.initialize.bind(p4a.Home));
