var Homepage_Boxes = new Class({
	Implements : [Options],
	box : undefined,
	callouts : [],
	options : {
		transition_every : 1000
	},
	interval : undefined,
	current_callout : undefined,
	current_callout_offset : undefined,
	call_buttons : undefined,
	next_button : undefined,
	previous_button : undefined,

	initialize : function( element , options ){
		this.setOptions(options);
		this.box = element;
		this.callouts = this.box.getElements( '.callout' );
		if ( this.callouts.length > 1 ) {
			this.call_buttons = this.box.getElement( '.call_buttons' );
            this.interval = this.do_next.periodical( this.options.transition_every , this );
            if ( this.call_buttons !== null ) {
				this.call_buttons.setStyle( 'display' , 'block' );
				this.next_button = this.call_buttons.getElement( 'a[rel="next"]' );
				this.previous_button = this.call_buttons.getElement( 'a[rel="prev"]' );

				this.next_button.addEvent( 'click' , this.do_next.bind( this ) );
				this.previous_button.addEvent( 'click' , this.do_previous.bind( this ) );
			}

		}
		this.get_current();
	},

	get_current : function(){
		this.callouts.each(function(e , i){
			if ( e.hasClass('current') ) {
				this.current_callout = e;
				this.current_callout_offset = i;
			}
			if (e.hasClass('hidden')) {
				e.setStyle('opacity' , 0);
				e.removeClass('hidden');
			}
		} , this);
		return this.current_callout;
	},

	do_next : function(e){
		var next_offset , next;
		clearInterval( this.interval );
		next_offset = this.current_callout_offset + 1;
		if ( this.callouts[ next_offset ] == undefined ) next_offset = 0;

		next = this.callouts[ next_offset ];
		
		this.show( next , next_offset );
		return false;
	},

	do_previous : function(e){
		var previous_offset , previous;
		clearInterval( this.interval );
		previous_offset = this.current_callout_offset - 1;
		if ( this.callouts[ previous_offset ] == undefined ) previous_offset = this.callouts.length - 1;

		previous = this.callouts[ previous_offset ];
		
		this.show( previous , previous_offset );
		return false;
	},

	show : function( n , i ){
		this.current_callout.set( 'tween' , {
			duration: 400,
			onComplete : ( function(){
				this.current_callout.removeClass('current')
			} ).bind(this)
		} );

		this.current_callout.tween( 'opacity' , 0 );

		n.set('tween' , {
			duration : 400,
			onComplete : function(){
				n.addClass('current');
			}
		});

		n.tween( 'opacity' , 1 );
		
		this.current_callout = n;
		this.current_callout_offset = i;

		if ( this.call_buttons === null ) {
            this.interval = this.do_next.periodical( this.options.transition_every , this );
        }
	}
});

