$(function(){
	
	/**
	 * Script handling dynamic categories on the search form
	 */
	if($('#dynamicCategory').attr('id')){
		function updateVariableCategories(data, discipline){
			
			var categoryCaption_0 = $(data).find('#categoryCaption_0').text();
			var categoryCaption_1 = $(data).find('#categoryCaption_1').text();

			var categoryOptions_0 = $(data).find('.option_0');
			var categoryOptions_1 = $(data).find('.option_1');
			
			
			if(discipline){
				$('#firstVariableCategoryCaption').text(categoryCaption_0);
				$('#secondVariableCategoryCaption').text(categoryCaption_1);
				
				$('.option_0').remove();
				$('.option_1').remove();
				$('#firstVariableCategory').append(categoryOptions_0);
				$('#secondVariableCategory').append(categoryOptions_1);
				
				preselectLastVariableCategories();
			
				
				$('.variableCategory').show();
			}else{
				$('.variableCategory').hide();
			}
			
		}
		
		function preselectLastVariableCategories(){
			var firstLastSelection = $('#firstVariableCategoryLastSelection').attr('name');
			var secondLastSelection = $('#secondVariableCategoryLastSelection').attr('name');
			
			var firstLength = $('#firstVariableCategory')[0].options.length;
			var secondLength = $('#secondVariableCategory')[0].options.length;
			
			var firstFound = 0;
			for (var i=0; i < firstLength; i++){
				if($('#firstVariableCategory')[0].options[i].value==firstLastSelection){
					firstFound = i;
					break;
				}
			}
			
			var secondFound = 0;
			for (var i=0; i < secondLength; i++){
				if($('#secondVariableCategory')[0].options[i].value==secondLastSelection){
					secondFound = i;
					break;
				}
			}
			
			$('#firstVariableCategory')[0].selectedIndex = firstFound;
			$('#secondVariableCategory')[0].selectedIndex = secondFound;
		}
		
		function getOptionsForCategory(categoryName){
			
			$.get('getVariableCategoryAsSelectOptions.htm',
					{	discipline: categoryName
					},
					function(data){
						 			updateVariableCategories(data, categoryName);
								  }
				  );
		}
		
		if($('#dynamicCategory').attr('value')){
			getOptionsForCategory($('#dynamicCategory').attr('value'));
		}
		
		

		$('#dynamicCategory').bind('change',
				function(event){
					getOptionsForCategory($(event.target).attr('value'));
				}
			);
		
		
	}
	
})