//
function getHTTPObject() 
{
		if(typeof(XMLHttpRequest)!='undefined')
		{
			return new XMLHttpRequest();
		}
        var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
        for(var i=0;i<axO.length;i++)
		{
			try
				{ 
					return new ActiveXObject(axO[i]);
				}
			catch(e)
				{
				} 
		}
		return null;
}

//Declara Variável
//var http;

//*** Código base do Ajax
function abreAjax(url, div , method)
{
	var http;
	//Variável
	http = getHTTPObject();
	
	//Tratamento de URL
	url = antiCacheRand(url)
	
	//Variáveis de Ajuda para envio GET ou POST
	var sendvars = null;	
		
	// se conectar, executa...
	http.onreadystatechange = function()
	{
		// chama a função que colocará o conteúdo
		conteudoPagina(http , div);
	};
	
	//Verifica se Existe Parâmetros
	//True = POST
	//False = GET
	
	if (method == "GET") {
		method = 'GET';
		sendvars = null;
	}
	else
	{
		method = 'POST';
		sendvars = url;
	}
	
	http.open(method, url, true);
	
	//Limpeza do Cash ,  Header para MEthod POST
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
	http.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	http.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	http.setRequestHeader("Pragma", "no-cache");
	
	http.send(sendvars);
	
}

//*** função para exibição da página
function conteudoPagina(http, div)
{

	// se estiver carregando...
	if(http.readyState == 1)
	{
			// Quando estiver carregando, exibe: carregando...
			//document.getElementById(div).innerHTML = "<center><font color='red'>Carregando...</font></center>";
			//document.getElementById(div).innerHTML = "<center><img src=imagens/ajax-loader.gif><span style='color:#FF0000;font-size:11px;'>Carregando ...</span></center>";
			//addItem(document.form.cidades,"Carregando...","",false,0)
			//document.getElementById(div).options[0] = new Option("Carregando...","");
	}

	// quando tiver terminado de carregar
	if (http.readyState == 4)
	{
			// checagem de status
			if (http.status == 200)
			{

				// Aqui é onde se mostra a página carregada

				// Conteúdo da página chamada
				var resultado = http.responseText;

				// Resolve o problema dos acentos
				resultado = resultado.replace(/\+/g," ");
				resultado = unescape(resultado);
				extraiScript(resultado);
				// Coloca na página atual o conteúdo da página requisitada pelo AJAX
				document.getElementById(div).innerHTML = resultado;
			}

			// se checagem de status falhar...
			else
			{
				//alert('ERRO!' + httpStatus(http.status));//Descrição do Erro
				document.getElementById(div).innerHTML = 'ERRO!' + httpStatus(http.status);
			}
	}

}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Padrão de Chamada do AJAX
function fnPadrao(id,url,div,method){
	//Mostra DIV Caso Esteja Oculta
	try
	{
		document.getElementById(id).style.display = '';
	}
	catch(e)
	{
		//ERRO
	}
	//Chama Ajax	
	setTimeout("abreAjax('" + url + "','" + div + "' , '" + method + "')",100);
}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Limpa Conteúdo da DIV
function fnLimpa_Div(id)
{
	//Limpa Conteúdo da Div
	document.getElementById(id).innerHTML = "";
	//Esconde a Div
	document.getElementById(id).style.display = 'none';
}

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Verifica Descrição do Erro
function httpStatus(erro){ //retorna o texto do erro http
        switch(erro){
            case 0: return "Erro Desconhecido";
            case 400: return "400: Solicitação incompreensível"; break;
            case 403: return "403: Você Não tem permissão para acessar essa página"; break;
			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: " + erro + ". Mais informações em http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html"; break;
        }
    }
	
/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Permite Uso de JS no AJAX
function extraiScript(texto){
    // Início
    var inicio = 0;
    // loop enquanto achar um script
    while (inicio!=-1){
        // procura uma tag de script
        inicio = texto.indexOf('<script', inicio);
        // se encontrar
        if (inicio >=0){
            // define o inicio para depois do fechamento dessa tag
            inicio = texto.indexOf('>', inicio) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', inicio);
            // extrai apenas o script
            codigo = texto.substring(inicio,fim);
            // executa o script
            //eval(codigo);
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}	

/////////////////////////////////////////////////////////////////////////////////////////////
//Função Que Evita Parâmetros Repetidos no CACHÊ
function antiCacheRand(url)
{
	var data = new Date();
	//Verifica se o Link(URL) possui parâmetros
	if(url.indexOf("?")>=0)
	{// já tem parametros
		return url + "&" + encodeURI(Math.random() + "_" + data.getTime());
	}
	else
	{ 
		return url + "?" + encodeURI(Math.random() + "_" + data.getTime());
	}
}
	
/////////////////////////////////////////////////////////////////////////////////////////////	
//Função Para Inserção de Varios Options em um Select
	function addItem(obj,strText,strValue,blSel,intPos)
	{
    	var newOpt,i,ArTemp,selIndex; 
		selIndex = (blSel)?intPos:obj.selectedIndex; 
		newOpt = new Option(strText,strValue); 
		Len = obj.options.length+1 
		if (intPos > Len) return 
		obj.options.length = Len 
		if (intPos != Len)
		{ 
        	ArTemp = new Array(); 
			for(i=intPos;i<obj.options.length-1;i++) 
            	ArTemp[i] = Array(obj.options[i].text,obj.options[i].value); 
			for(i=intPos+1;i<Len;i++) 
				obj.options[i] = new Option(ArTemp[i-1][0],ArTemp[i-1][1]); 
		} 
		obj.options[intPos] = newOpt; 
		if (selIndex > intPos) 
        	obj.selectedIndex = selIndex+1; 
		else if (selIndex == intPos)  
        	obj.selectedIndex = intPos; 
	}