main.addFunction("initProdutosEServicos()");

var prodEServ;
function initProdutosEServicos(){
	prodEServ = new ProdutosEServicos();
}

function ProdutosEServicos(){

	//(construtor)
	this.init = function(){
		if($("setores-atividade")) {
			if($("setores-atividade").options[$("setores-atividade").selectedIndex].value != "null") {
				$("setores-atividade").removeChild($("setores-atividade").options[0]);
			}

			this.attachEvents();
		}
	}

	//adiciona os eventos aos componentes...
	this.attachEvents = function(){
		$("setores-atividade").onchange = function() {
			if(this.options[0].value == "null")
				this.removeChild(this.options[0]);

			prodEServ.atualizaSegmentos();
		}
	}


	this.atualizaSegmentos = function(){
		var indice = document.getElementById('setores-atividade').selectedIndex;
		var setor = document.getElementById('setores-atividade').options[indice].getAttribute('value');

		//Crio um com valor "Carregando..."
		document.getElementById('segmentos-atividade').innerHTML = "";
		var new_opcao = document.createElement("option");
		var texto = document.createTextNode("Carregando...");

		new_opcao.setAttribute("value", "null");
		new_opcao.appendChild(texto); //Adiciona o texto a OPTION.
		document.getElementById('segmentos-atividade').appendChild(new_opcao);
		//Fim.....

		ajax = ajaxInit();
		if(ajax) {
			ajax.open("GET", "./__model/business/xml/?action=segmentos-fornecedor&setor=" + setor, true);
			ajax.onreadystatechange = function()
			{
				if(ajax.readyState == 4)
				{	if(ajax.status == 200)
					{
						var result = ajax.responseXML;
						var segmentos = result.getElementsByTagName("segmento");

						document.getElementById('segmentos-atividade').innerHTML = "";

						var todosOpcao = document.createElement("option");
						todosOpcao.setAttribute("value", "null");
						todosOpcao.appendChild(document.createTextNode("Todos os segmentos")); //Adiciona o texto a OPTION.
						document.getElementById('segmentos-atividade').appendChild(todosOpcao);

						for (var i = 0; i < segmentos.length; i++) {
							new_opcao = prodEServ.createOption(segmentos[i]);
							document.getElementById('segmentos-atividade').appendChild(new_opcao);
						}
					}
					else{
						alert(ajax.statusText);
					}
				}
			}
			ajax.send(null);
			return;
		}
	}

	this.createOption = function(cidade) {
		var new_opcao = document.createElement("option");

		var texto = document.createTextNode(cidade.childNodes[0].data);

		new_opcao.setAttribute("value", cidade.getAttribute("codigo"));
		new_opcao.appendChild(texto); //Adiciona o texto a OPTION.

		return new_opcao; // Retorna a nova OPTION.
	}

	//processamento...
	this.init();
}
