$(function(){
	
	var questions = $('#contener');
	
	function refreshSelects(){
		var selects = questions.find('select');
		
		// Improve the selects with the Chose plugin
		selects.chosen();
		
		// Listen for changes
		selects.unbind('change').bind('change',function(){
			
			// The selected option
			var selected = $(this).find('option').eq(this.selectedIndex);
			// Look up the data-connection attribute
			var connection = selected.data('connection');
			
			
			// Removing the li containers that follow (if any)
			selected.closest('#contener li').nextAll().remove();
			
			if(connection){
				fetchSelect(connection);
			}

		});
	}
	
	var working = false;
	 
	function fetchSelect(val){
		
		if(working){
			return false;
		}
		working = true;
			
			var connection, options = '';
			
			refreshSelects();
			
			working = false;
	
		
	}
	
	$('#preloader').ajaxStart(function(){
		$(this).show();
	}).ajaxStop(function(){
		$(this).hide();
	});
	
	// Initially load the product select
	fetchSelect('productSelect');
});

