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

	Implements: [Options, Chain],

	wrapper: false,
	bar: false,
	image: false,
	test: false,

	options: {
		'transitionDuration': 500,
		'textPattern': 'Loading... %loadPercent%%',
		'barCSSPath': 'div.nxc-progress-bar',
		'imageCSSPath': 'img.nxc-progress-bar-image',
		'textCSSPath': 'div.nxc-progress-bar-text'
	},

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

		this.wrapper = document.id( wrapper );
		this.bar     = this.wrapper.getElement( this.options.barCSSPath );
		this.image   = this.wrapper.getElement( this.options.imageCSSPath );
		this.text    = this.wrapper.getElement( this.options.textCSSPath );

		this.image.setStyle( 'margin-left', -1 * this.image.getStyle( 'width' ).toInt() );
    },

    progress: function( loadPercent, fx ) {
    	if( fx === undefined ) {
    		fx = true;
    	}

    	if( loadPercent <= 0 || loadPercent > 100 ) {
    		return false;
    	}

		var newBarImageMargin = this.getImageOffset( loadPercent );
		if( fx ) {
			this.image.get( 'tween', { property: 'margin-left', duration: this.options.transitionDuration } ).start( newBarImageMargin );
		} else {
			this.image.setStyle( 'margin-left', newBarImageMargin );
		}

		this.text.set( 'html', this.options.textPattern.replace( '%loadPercent%', loadPercent.toFixed( 0 ) ) );
    },

	getImageOffset: function( loadPercent ) {
		var barWidth          = this.bar.getStyle( 'width' ).toInt();
		return ( barWidth * ( loadPercent / 100 ) ).toInt() - barWidth;
	},

	remove: function() {
		this.wrapper.get( 'tween', { property: 'opacity', duration: this.options.transitionDuration } ).start( 0 ).chain( function() {
			this.wrapper.destroy();
		}.bind( this ) );
	}
} );
