/**
 * Funções para tratamento de eventos relacionados à busca de sets
 * (implantadas no novo layout - bioetheme).
 * @author Felipe Zap de Mello
 */

/**
 * 
 * AJAX da busca de sets na página inicial
 * Filtrando o vocabulário controlado, conforme o selecionado
 * nos selects.
 * 
 * a requisição é processada pela servlet LoadControlledVocabullary
 */
$(document).ready(function(){
	var idTipoPesquisa 	=  "aspect_artifactbrowser_FrontPageSearch_field_tipo_pesquisa";
	var idComponenteCurricular = "aspect_artifactbrowser_FrontPageSearch_field_componente_curricular";
	var idTemaPesquisa = "aspect_artifactbrowser_FrontPageSearch_field_tema_pesquisa";
	
	$("#"+idTipoPesquisa).change(function() {
		$("#"+idComponenteCurricular).empty();
		$("#"+idTemaPesquisa).empty();
		processAJAXVocabullary(idTipoPesquisa, idComponenteCurricular);
	});
	
	$("#"+idComponenteCurricular).change(function() {
		$("#"+idTemaPesquisa).empty();
		processAJAXVocabullary(idComponenteCurricular, idTemaPesquisa);
	});
});

function processAJAXVocabullary(sourceSelect, destSelect) {
	$("#"+sourceSelect+" option:selected").each(function() {
		if(isValidOption($(this).text())){
			$.getJSON( $("#context-path").val() + "/loadVocabullary", 
					"vocabullary=" + escape($(this).text()),
					function(json){
						$("#"+destSelect).append("<option value=''></option>");
						$.each(json.options, function(index,option) {
							$("#"+destSelect).append("<option value='"+option+"'>"+option+"</option>");
					       }
					    );
	        });
		}		
	});
}

/**
 * Veririca se a string str é valida para dar inicio
 * a requisição AJAX.
 * 
 * @param str
 * @return
 */
function isValidOption(str){
	switch(str) {
		case "":
		case "Nível de Ensino":
			return false;
	}
	
	return true;
}
