$(document).ready(function(){

	var categoryBrandModelWidgets = {
        bindEvents: function(){
			$( "#SELFMotoTraderSelect_category" ).bind( "change", {that: this}, this.optionSelected );
			$( "#SELFMotoTraderSelect_brand_id" ).bind( "change", {that: this}, this.optionSelected );
			$( "#SELFMotoTraderSelect_model_id" ).bind( "change", {that: this}, this.optionSelected );
		},
		
		unbindEvents: function(){
			$( "#SELFMotoTraderSelect_category" ).unbind();
			$( "#SELFMotoTraderSelect_brand_id" ).unbind();
			$( "#SELFMotoTraderSelect_model_id" ).unbind();
		},
		
		updateForm: function( html ){
			$( "#ajaxcategorybrandmodel" ).replaceWith( '<div id="ajaxcategorybrandmodel">' + html + '</div>' );	 		
		},
		
		selectedOption: function( id ){
			var selectedOption;
			 $.each( $( "#" + id ).children(), function( key, option ){
				 if( $(option).attr('selected') ){
					selectedOption = $(option).val();
				 }
			 });
			 return selectedOption;
		},
		
		optionSelected: function( event ){
			 var that = event.data.that;
			 var target = $( event.currentTarget ).attr( 'id' ); 
			 var category = that.selectedOption( "SELFMotoTraderSelect_category" );
			 var brandId = that.selectedOption( "SELFMotoTraderSelect_brand_id" );
			 var modelId = that.selectedOption( "SELFMotoTraderSelect_model_id" );
			 var formIdentifier = that.calculateFromHiddenHTML( 'category_brand_model_form_identifier' );

			 $.ajax({
	                type: "POST",
					url: that.calculateFromHiddenHTML( 'category_brand_model_ajax_url' ),
					data: {
				 		target: target,
				 		category: category,
				 		brand_id: brandId,
				 		model_id: modelId,
				 		form_identifier: formIdentifier,
				 	},
					dataType: "html",
				    success: function( html ){
				 		that.updateForm( html );
				 	},
					error: function( XMLHttpRequest, textStatus ){
						var errorMessage = "Problemy techniczne";
					},
					beforeSend: function(){
						that.unbindEvents();
						that.setCursor('wait');
						$( "#SELFMotoTraderSelect_category" ).attr('disabled', 'disabled');
						$( "#SELFMotoTraderSelect_brand_id" ).attr('disabled', 'disabled');
						$( "#SELFMotoTraderSelect_model_id" ).attr('disabled', 'disabled');
						$( "#ajaxcategorybrandmodel" ).fadeTo( 'slow', 0.3, function(){});
					},
					complete: function(){
						that.setCursor('default');
						that.bindEvents();
					}
				});
		},
		
		setCursor: function ( type ){
			$('body').css('cursor', type);
			$(this).css('cursor', type);
		},
		
		calculateFromHiddenHTML: function( identifier ){
			return $( '#' + identifier ).text();
		}			
	};
	
	categoryBrandModelWidgets.bindEvents();
	categoryBrandModelWidgets.setCursor( 'default' );
});
