var NXC = NXC || {};
NXC.AJAXContainer = new Class( {

	Implements: [Options, Events],

	container: false,
	loadMore: false,
	loader: false,

	displayed: 0,
	portion: 10,

	options: {
		'loaderID'  : 'nxc-ajaxcontainer-loader',
		'ajaxURL'   : 'get_elements.php?offset=%displayed%&limit=%portion%',
		'displayed' : 0,
		'portion'   : 10,
		'onLoad'    : $empty
	},

    initialize: function( containerID, loadMoreID, options ) {
    	this.setOptions( options );

		this.container = document.id( containerID );
		this.loadMore  = document.id( loadMoreID );
		this.loader    = document.id( this.options.loaderID );
		if( $type( this.loader ) == 'element' ) {
			this.loader.setStyle( 'display', 'none' );
		}

		this.displayed = this.options.displayed;
		this.portion   = this.options.portion;

		this.installEvents();

		if( this.displayed == 0 ) {
			this.loadElements();
		}
    },

	installEvents: function() {
		this.loadMore.addEvent( 'click', function( e ) {
			this.loadElements();e.stop();
		}.bind( this ) );
	},

	loadElements: function() {
		this.loadMore.setStyle( 'display', 'none' );
		if( $type( this.loader ) == 'element' ) {
			this.loader.setStyle( 'display', 'block' );
		}

		var url = this.options.ajaxURL.replace( '%displayed%', this.displayed ).replace( '%portion%', this.portion );
		new Request.JSON( {
			url: url,
			onSuccess: function( response ) {
				response = new Hash( response );
				if( $type( this.loader ) == 'element' ) {
					this.loader.setStyle( 'display', 'none' );
				}

				this.container.set( 'html', this.container.get( 'html' ) + response.get( 'html' ) );
				this.displayed += this.portion;

				if( response.has( 'totalObjectsCount' ) === false ) {
					this.loadMore.setStyle( 'display', 'block' );
				} else if( response.get( 'totalObjectsCount' ) > this.displayed ) {
					this.loadMore.setStyle( 'display', 'block' );
				}

				this.fireEvent( 'load' );
			}.bind( this )
		} ).send();
	}
} );
