var AdvertisingSource = {
	'source' : $('comboFontePubblicitaria'),
	'dest' : $('comboFontePubblicitaria2'),
	'throbber': $('fontePubblicitariaThrobber'),
	
	'name' : $('comboFontePubblicitaria').name ,
	
	'init': function(){
		this.disableDest();
		this.source.loadAdvSource = this.loadAdvSource.bind( this );
		this.source.addEvent( 'change' , this.loadAdvSource.bindWithEvent( this ) );
		
		this.source.addEvent( 'change' , function(){
			$('comboFontePubblicitariaError').setStyle( 'display' , 'none' );
		});
		this.dest.addEvent( 'change' , function(){
			$('comboFontePubblicitariaError').setStyle( 'display' , 'none' );
		});
		
		
		return this;
	},

	'loadAdvSource': function( ev ){
		if ( ! this.source.value ) return this.disableDest();
		new Request.JSON({
			'url': host,
			'data': JSON.encode({
				'id':2,
				'method': 'jsonFactory.filterAdvertisingSource' ,
				'params':[ this.source.value ]
			}),
			'onRequest': this.disableDest.bind( this , [ true ] ),
			'onError':this.throbber.setStyle.bind( this.thobber , [ 'visibility' , 'hidden' ] ),
    		'onComplete': this.showAdvSource.bind( this )
		}).send();

	},

	'disableDest': function( showLoading ){
		if ( showLoading )
			this.throbber.setStyle( 'visibility' , '' );

		this.source.name = this.name ;
		this.dest.name = "";

		this.dest.empty();
		
		
		this.dest.setProperty( 'disabled' , 'disabled' );
		this.dest.setStyle( 'visibility' , 'hidden' );
		this.dest.removeClass( 'displayed' );

	},


	'showAdvSource' : function( json ){

		new Element( 'option', {'value':''} ).set('html' , "Seleziona fonte" ).inject( this.dest );

		json = json || {};
		json.result = json.result || {};
		json.result.result = JSON.decode( json.result.result || [] );
	
		$each( json.result.result , function( opt ){

			new Element( 'option' , {
				'value' : opt.code
			} ).set( 'html' , opt.label ).inject( this.dest );

		}, this );

		/** Fat: show 'FontePubblicitaria2' combo */
		if ( this.dest.getChildren().length > 1 ){
			this.dest.addClass( 'displayed' );
			this.dest.removeProperty( 'disabled' );
			this.dest.setStyle( 'visibility' , '' );
			this.source.name = "" ;
			this.dest.name = this.name;
		}
		
		this.throbber.setStyle( 'visibility' , 'hidden' );

	},

	'onLoadPage': function(){
		if ( this.source.value ){
			if ( !this.source.loadAdvSource )
				this.init();
			this.source.loadAdvSource();
		}
		return this;
	}
	
};

AdvertisingSource.init().onLoadPage();
