//Cria variavel global que recebera o array com os dados do CEP
//var dadosDiretorio = null;

//Tenta criar o objeto xmlHTTP
try{
    xmlhttpcidade = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttpcidade = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttpcidade = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttpcidade = false;
        }
    }
}

//Fila de conexões
filacid=[];
ifilacid=0;

//Carrega via XMLHTTP a url recebida e coloca seu valor
//no objeto com o id recebido
function carregaCidades(uf, id, vlrDefault) {
	if ( uf != '' ) {
		//Adiciona à fila
		filacid[filacid.length]=[id, '/xmldata/' + uf.toLowerCase() + '.xml', vlrDefault];
		//Se não há conexões pendentes, executa
		if((ifilacid+1)==filacid.length) ajaxRunCidade();
	}
	else { 
		alert('Estado inválido.'); 
		input = document.getElementById(id);
		input.options.length = 0;
		input.options[0] = new Option(" ", '0'); 
	}
}

//Executa a próxima conexão da fila
function ajaxRunCidade(){
    //Abre a conexão
	//alert(fila[ifila][1]);
    xmlhttpcidade.open("GET",filacid[ifilacid][1],true);
    //Função para tratamento do retorno
    xmlhttpcidade.onreadystatechange=function() {
        if (xmlhttpcidade.readyState==4 && xmlhttpcidade.status == 200) {
            //Mostra o HTML recebido
            //--  retorno=unescape(xmlhttp.responseText.replace(/\+/g," "))
			var result = xmlhttpcidade.responseXML;
			var cidXml = result.getElementsByTagName("cid");
			input = document.getElementById(filacid[ifilacid][0]);
			input.options.length = 0;
			input.disabled = true;
			input.options[0] = new Option("Selecione a cidade", '0'); 

			for (var x = 0; x < cidXml.length; x++) {
				//cidXml[x].getAttribute('cod');
				input.options[x+1] = new Option(cidXml[x].firstChild.nodeValue, cidXml[x].getAttribute('cod')); 
			}
			input.disabled = false;
			if (filacid[ifilacid][2] > 0) input.value = filacid[ifilacid][2];

            //Roda o próximo
            ifilacid++;
            if(ifilacid<filacid.length)setTimeout("ajaxRunCidade()",20);
        }
    }
    //Executa
    xmlhttpcidade.send(null);
}
