// JavaScript Document

//Objecto-Ferramenta para os ComboBoxs do filtro do acervo de artigos
var ListUtil = new Object();

//Função para adicionar options aos combos
ListUtil.add = function (oListbox, sName, sValue) {
	
	var oOption = document.createElement("option");
	oOption.appendChild(document.createTextNode(sName));
	if (arguments.length == 3) {
		oOption.setAttribute("value", sValue);
	}
	oListbox.appendChild(oOption);
};

//Remove um Item do ComboBox
ListUtil.remove = function (oListbox, iIndex){;
	oListbox.remove(iIndex);
};

//Limpa o ComboBox deixando só um primeiro item, que é uma linha em branco.
ListUtil.clear = function (oListbox) {
	for (var i=oListbox.options.length-1; i >= 0; i--) {
		//alert(i);
		//if (i != 0){
			ListUtil.remove(oListbox, i);
		//}
	}
};

/////////////////////////////////////////////////////////////////////////////////////////////


var getBairros = function(obj){
	
	ob("bairro").disabled=false;
	
	ListUtil.clear(ob("bairro"));
	ListUtil.add(ob("bairro"), "Aguarde...", "");
	
	var args = "&id="+obj.value+"&";
	fnConexao(args, "xml/bairros_xml.php", "responseBairros", "xml");
}

var responseBairros = function(xml){
	var num=xml.getElementsByTagName("item").length;
	if(num && num>0){
		
		ListUtil.clear(ob("bairro"));
		
		for(var i=0; i<num; i++){
			name=xml.getElementsByTagName("bairro").item(i).firstChild.data;
			value=xml.getElementsByTagName("id").item(i).firstChild.data;
			ListUtil.add(ob("bairro"), name, value);
		}
	}
}

function fnConexao(args, file, retorno, tipo){
	var req = null;
	
	if (window.XMLHttpRequest){
	
		req = new XMLHttpRequest();
		if (req.overrideMimeType){
			req.overrideMimeType('text/xml');
		}
	} 
	
	else if (window.ActiveXObject){
	
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e){
		
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	req.onreadystatechange = function() { 
	
		if(req.readyState == 4)	{
			if(req.status == 200) {
				
				if(tipo){
					tipo=tipo.toLowerCase();
					var doc = null;
					if("text"==tipo){
						doc = req.responseText;
					} else if("xml"==tipo){
						doc = req.responseXML;
						//doc2 = req.responseText;
						//alert(doc2);
						//alert(doc.childNodes[0].firstChild.data);
					}
					//alert(retorno);
					if(retorno){
						retorno = retorno + "(doc)";
						eval(retorno);
					}
				}				
			}
		}
	};
	
	req.open("POST", file, true);
	req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	req.send(args);
}

var ob = function(id){
	return document.getElementById(id);
}
