function httpStatus(stat) {
	switch(stat){
		case 0: return "Erro desconhecido de javascript";
		case 400: return "400: Solicitação incompreensível"; break;
		case 403: case 404: return "404: Não foi encontrada a URL solicitada"; break;
		case 405: return "405: O servidor não suporta o método solicitado"; break;
		case 500: return "500: Erro desconhecido de natureza do servidor"; break;
		case 503: return "503: Capacidade máxima do servidor alcançada"; break;
		default: return "Erro " + stat + ". Mais informações em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
	}
}

var reqs = Array();
var times = Array();
var abort = false;
/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/
function ajax() {
	try {
		var req = null;
		if(window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		return req;
	} catch(e) {
		alert("Ocorreu um erro inesperado! Por favor, tente novamente.");
		return null;
	}
}

/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/
function post(page, destination, parameters) {
	abort = true;
	
	for(var i=reqs.length-1; i>=0; i--) {
		if(reqs[i]) {
			reqs[i].abort();
			reqs[i] = null;
		}
		reqs.pop();
	}

	for(var i=times.length-1; i>=0; i--) {
		if(times[i]) {
			clearTimeout(times[i]);
			clearInterval(times[i]);
			times[i] = null;
		}
		times.pop();
	}
	
	var req = this.ajax();
	
	if(req) {
		req.onreadystatechange = processReqChange;

		req.open("POST", page, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", parameters.length);
		req.setRequestHeader("Connection", "close");
		
		if(document.getElementById(destination))
			document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'></div>";
		
		req.send(parameters);
	} else {
		alert("Seu browser não suporta AJAX. Por favor, atualize-o.");
	}
	
	function processReqChange() {
		if(req.readyState == 0) {
			if(document.getElementById(destination))
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 1) {
			if(document.getElementById(destination))
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 2) {
			if(document.getElementById(destination))
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 3) {
			if(document.getElementById(destination))
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 4) {
			if((req.status == 200) && ((req.responseText) != "UNKNOWN")) {
				if(document.getElementById(destination))
					document.getElementById(destination).innerHTML = req.responseText;
				
				exeScript(req.responseText);
				
				//new Effect.ScrollTo(destination);
				return false;
			} else {
				setPage('bad.inc.php', 'conteudo');
			}
		}
	}
}

/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/
function setPage(page, destination, show, auto_scroll, store, event) {
	abort = true;

	for(var i=reqs.length-1; i>=0; i--) {
		if(reqs[i]) {
			reqs[i].abort();
			reqs[i] = null;
		}
		reqs.pop();
	}

	for(var i=times.length-1; i>=0; i--) {
		if(times[i]) {
			clearTimeout(times[i]);
			clearInterval(times[i]);
			times[i] = null;
		}
		times.pop();
	}
	
	var req = this.ajax();

	if(show == undefined)
		show = true;
	
	if(auto_scroll == undefined)
		auto_scroll = false;
	
	if(store == undefined)
		store = false;
		
	if(req) {
		req.onreadystatechange = processReqChange;
		
		var navs = window.document.navigators;
		if(navs) {
			if(destination == navs.settings.div_main) {
				navs.last_page = base64_encode(page);
				if(navs.is_ie) {
					navs.iframe.src = navs.settings.iframe_src + "?id="+navs.last_page;
					document.getElementById('iframe_ajax_ie').src = navs.settings.iframe_src + "?id="+navs.last_page;
				}
				
				window.location.hash = "#"+navs.last_page;
				document.title = navs.title;
			}
		}
		
		req.open("GET", page, true);
			
		if(document.getElementById(destination) && show)
			document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'></div>";	
		
		req.send(null);
	} else {
		alert("Seu browser não suporta AJAX. Por favor, atualize-o.");
	}
	
	function processReqChange() {
		if(req.readyState == 0) {
			if(document.getElementById(destination) && show)
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 1) {
			if(document.getElementById(destination) && show)
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 2) {
			if(document.getElementById(destination) && show)
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 3) {
			if(document.getElementById(destination) && show)
				document.getElementById(destination).innerHTML = "<div align='center'><img src='/images/aguarde.gif' align='center'><br><font face='Verdana' style='font-size:10px; font-weight:bold'>Aguarde...</font></div>";
		} else if(req.readyState == 4) {
			if((req.status == 200) && ((req.responseText) != "UNKNOWN")) {
				//req.getAllResponseHeaders()
				//req.getResponseHeader("Last-Modified")
				
				if(document.getElementById(destination)) {
					/*document.getElementById(destination).style.opacity = 0;
					document.getElementById(destination).style.visibility = 'hidden';
					new Effect.Opacity(destination, { from: 1, to: 0, duration: 0.1 });*/
					document.getElementById(destination).innerHTML = req.responseText;
					/*document.getElementById(destination).style.opacity = 0;
					document.getElementById(destination).style.visibility = 'hidden';*/
				}
					
				exeScript(req.responseText);
				
				if(document.forms[0] != null) {
					var obj = document.forms[0][0]; 
					if(obj != null) {
						window.focus();
						if(obj.type == 'text' || obj.type == 'textarea')
							obj.select();
		
						obj.focus();
					}
				}
				
				if(auto_scroll && document.body.scrollTop > 220) {
					//new Effect.ScrollTo(destination);
					document.body.scrollTop = 120;
				}
				
				//document.getElementById(destination).style.visibility = 'visible';
				//new Effect.Opacity(destination, { from: 0, to: 1, duration: 0.5 });
				//document.getElementById(destination).style.display = 'block';
				//return false;
			} else if(req.status == 400) {
				alert('Endereço não existe!');
				setPage('bad.inc.php', 'conteudo');
			}
		} else {
			setPage('bad.inc.php', 'conteudo');
		}
	}
}

/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/
function countGroup(page, destination) {
	var req = null;
	try {
		if(window.XMLHttpRequest) {
			req = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	} catch(e) {
		alert("Ocorreu um erro inesperado! Por favor, tente novamente.");
	}

	if(req) {
		reqs.push(req);
		req.onreadystatechange = processReqChange;
		req.open("GET", page, true);
		req.send(null);
	} else {
		alert("Seu browser não suporta AJAX. Por favor, atualize-o.");
	}
	
	function processReqChange() {
		if(req.readyState == 4) {
			if((req.status == 200) && ((req.responseText) != "UNKNOWN")) {
				if(document.getElementById(destination))
					document.getElementById(destination).innerHTML = req.responseText;
					
				exeScript(req.responseText);
			}
		}
	}
}

function addTime(time) {
	times.push(time);
}

/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/

var opcao = null;
var combo = null;
var tag = null;
var div = null;
/* PARAMETROS:
   1 - pagina
   2 - nome do segundo combo
   3 - o id da primeira opção do segundo combo
   4 - a tag pai q deve estar os objetos
   5 - parametro para ser carregado na pagina
*/
function carregaCombo(pcPagina, combo, opcao, tag, parameters) {
	this.opcao = opcao;
	this.combo = combo;
	this.tag = tag;
	
	var req = this.ajax();
	
	/* CASO VERDADE */
	if(req) {
		/* CHAMADA PARA A PAGINA DE EXECUÇÃO DA OPERAÇÃO COM PASSAGENS DE PARAMETROS PERTINENTES */
		req.open("POST", pcPagina, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", parameters.length);
		
		req.onreadystatechange = processReqChange;

		/* COLOCANDO O TEXTO 'ENVIANDO ...' ENQUANTO A TRANSAÇÃO NÃO É FINALIZADA */
		for(var i = 0; i < opcao.length; i++) {
			document.getElementById(opcao[i]).innerText = "Carregando...";
		}
		
		if(document.getElementById('divCombo'))
			document.getElementById('divCombo').innerHTML = "<img src='/images/aguarde_combo.gif' align='center'>";
		
		/* EXECUTANDO A REQUISIÇÃO */
		req.send(parameters);
	} else {
			alert("Seu browser não suporta AJAX. Por favor, atualize.");
	}
	
	function processReqChange() {
		if(req.readyState == 1) {
			for(var i = 0; i < opcao.length; i++)
				document.getElementById(opcao[i]).innerText = "Carregando...";
		}
		if(req.readyState == 4) {
			//alert(req.responseText);
			if(req.responseXML) {
				processXML(req.responseXML);
			} else {
				setPage('bad.inc.php', 'conteudo');
			}
		}
	}
}

function processXML(obj) {
	try {
		//pega a tag cidade
		var dataArray = obj.getElementsByTagName(tag);
		//total de elementos contidos na tag
		if(dataArray.length > 0) {
			//percorre o arquivo XML paara extrair os dados
			for(var i = 0; i < dataArray.length; i++) {
				var item = dataArray[i];
				//contéudo dos campos no arquivo XML
				var codigo    =  item.getElementsByTagName('id')[0].firstChild.nodeValue;
				var descricao =  item.getElementsByTagName('descricao')[0].firstChild.nodeValue;
			
				for(var j = 0; j < this.combo.length; j++) {
					//cria um novo option dinamicamente  
					var novo = document.createElement('option');
					//atribui um ID a esse elemento
					novo.setAttribute('id', this.opcao[j]);
					//atribui um valor
					novo.value = codigo;
					//atribui um texto
					novo.text  = descricao;
					novo.title  = descricao;
					
					//finalmente adiciona o novo elemento
					document.getElementById(this.combo[j]).options.add(novo);
				}
			 }
		}
		//caso o XML volte vazio, printa a mensagem abaixo
		for(var i = 0; i < this.opcao.length; i++)
			document.getElementById(this.opcao[i]).innerText = "-- SELECIONE --";
			
		if(document.getElementById('divCombo'))
			document.getElementById('divCombo').innerText = "&nbsp;";
	} catch(e) {
		alert("Exception: " + e);
	}
}

/****************************************************************************************************************************
*****************************************************************************************************************************
*****************************************************************************************************************************/

function exeScript(texto) {
	var ini=0;
    while (ini != -1) {
		ini = texto.indexOf('<script', ini);
        if (ini >= 0) {//Define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            //Procura o final do script
            var fim = texto.indexOf('</script>', ini);
            codigo = texto.substring(ini,fim);
            //eval(codigo);
			var novo = document.createElement("script");
            novo.text = codigo;
            document.body.appendChild(novo);
		}
	}
}