var NXC = NXC || {};
NXC.RelatedSelects = new Class( {
	Implements: [Options, Events],

	options: {
		'defaultChildText':  '-- all --',
		'defaultChildValue': 0,
		'getChildsURL':      'index.php/getchildes/',
		'loaderBlockID':     'filterFormLoader'
	},
	
    initialize: function( parentSelectID, childSelectID, options ) {
    	this.parentSelect = $( parentSelectID );
    	this.childSelect  = $( childSelectID );

    	this.setOptions( options );

		this.loader = $( this.options.loaderBlockID );

    	this.parentSelect.addEvent( 'change', function() {
    		this.resetChild();

    		if( this.parentSelect.get( 'value' ) != 0 ) {
    			this.showLoader();
				new Request.JSON( {
					'url': this.options.getChildsURL + '/' + this.parentSelect.get( 'value' ),
					onSuccess: function( childNodes ) {
						childNodes.each( function( el ) {
							this.addChildOption( el.name, el.value, el.url );
						}.bind( this ) );

						if( this.parentSelect.get( 'id' ) == 'baseNodeID' ) {
							if( childNodes.length > 0 ) {
								$( 'selectObjectClassBlock' ).setStyle( 'display', 'block' );
							} else {
								$( 'selectObjectClassErrorBlock' ).setStyle( 'display', 'block' );								
							}
						}
						this.hideLoader();
					}.bind( this )
				} ).send();
    		}
    	}.bind( this ) );
    },

    resetChild: function() {
    	this.childSelect.empty();
    	if( this.parentSelect.get( 'id' ) != 'baseNodeID' ) {
    		this.addChildOption( this.options.defaultChildText, this.options.defaultChildValue, false );
    	}
    	this.childSelect.fireEvent( 'change' );
	},
	
	addChildOption: function( html, value, url ) {
    	var option = new Element( 'option', {
    		'html': html,
    		'value': value
    	} ).inject( this.childSelect );
    	option.store( 'url', url );
	},
	
	showLoader: function() {
		this.loader.setStyle( 'width', this.loader.getParent().getStyle( 'width' ) );
		this.loader.setStyle( 'height', this.loader.getParent().getStyle( 'height' ) );
		this.loader.setStyle( 'opacity', 0.4 );
		this.loader.setStyle( 'display', 'block' );
		$( 'filterForm' ).getChildren( 'input' ).each( function( el ) {
			el.set( 'disabled', true );
		} );
	},

	hideLoader: function() {
		this.loader.setStyle( 'display', 'none' );
		$( 'filterForm' ).getChildren( 'input' ).each( function( el ) {
			el.set( 'disabled', false );
		} );
	}
} );
