function ajaxGet(url,elemento_retorno,exibe_carregando, divCarregando){
/******
* ajaxGet - Coloca o retorno de uma url em um elemento qualquer
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* A função é grande, coloque-a em um arquivo .js separado.
* Versão: 1.2 - 20/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - elmicox.blogspot.com
* Parametros:
* url: string; elemento_retorno: object||string; exibe_carregando:boolean
*  - Se elemento_retorno for um elemento html (inclusive inputs e selects),
*    exibe o retorno no innerHTML / value / options do elemento
*  - Se elemento_retorno for o nome de uma variavel
*    (o nome da variável deve ser declarado por string, pois será feito um eval)
*    a função irá atribuir o retorno à variável ao receber a url.
*******/
    var ajax1 = pegaAjax();
    if(ajax1){
        var url = antiCacheRand(url);
        ajax1.onreadystatechange = ajaxOnReady;
        ajax1.open("POST", url ,true);
        //ajax1.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");//"application/x-www-form-urlencoded");
        ajax1.setRequestHeader("Cache-Control", "no-cache");
        ajax1.setRequestHeader("Pragma", "no-cache");

        //alert(url);
        //alert(exibe_carregando);
        //alert(divCarregando);

        if(exibe_carregando){
           if (divCarregando != null && divCarregando != 0 && divCarregando != '' && divCarregando != 'undefined'){
	           document.getElementById(divCarregando).innerHTML="<span class='carregando'>Carregando...</span>";
           }else{
	           put("Carregando ...");
           }
        }

        //alert(divCarregando);
        ajax1.send(null);

        if (divCarregando != null && divCarregando != 0 && divCarregando != '' && divCarregando != 'undefined'){
			//document.getElementById(divCarregando).innerHTML=".";
		}

        return true;
    }else{
        return false;
    }
    function ajaxOnReady(){
        if (ajax1.readyState==4){
            if(ajax1.status == 200){
                var texto=ajax1.responseText;
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");
                //texto=unescape(texto); //descomente esta linha se tiver usado o urlencode no php ou asp
                put(texto);
                extraiScript(texto);
            }else{
                if(exibe_carregando){put("Falha no carregamento. " + httpStatus(ajax1.status));}
            }
            ajax1 = null;

            if (document.getElementById(divCarregando)){
	            document.getElementById(divCarregando).innerHTML="";
            }

        }else if(exibe_carregando){//para mudar o status de cada carregando
                   if (divCarregando != null && divCarregando != 0 && divCarregando != '' && divCarregando != 'undefined'){
			           document.getElementById(divCarregando).innerHTML="<span class='carregando'>Carregando...</span>";
		           }else{
			           put("Carregando ...");
		           }
        }
    }
    function put(valor){ //coloca o valor na variavel/elemento de retorno
        if((typeof(elemento_retorno)).toLowerCase()=="string"){ //se for o nome da string
            if(valor!="Falha no carregamento"){
                eval(elemento_retorno + '= unescape("' + escape(valor) + '")');
            }
        }else if(elemento_retorno.tagName.toLowerCase()=="input"){
            valor = escape(valor).replace(/\%0D\%0A/g,"");
            elemento_retorno.value = unescape(valor);
        }else if(elemento_retorno.tagName.toLowerCase()=="select"){
            select_innerHTML(elemento_retorno,valor)
        }else if(elemento_retorno.tagName){
            elemento_retorno.innerHTML = valor;
            //alert(elemento_retorno.innerHTML)
        }
    }
    function pegaAjax(){ //instancia um novo xmlhttprequest
        //baseado na getXMLHttpObj que possui muitas cópias na net e eu nao sei quem é o autor original
        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;
    }
    function httpStatus(stat){ //retorna o texto do erro http
        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;
        }
    }
    function antiCacheRand(aurl){
        var dt = new Date();
        if(aurl.indexOf("?")>=0){// já tem parametros
            return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
        }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}
    }
}
function select_innerHTML(objeto,innerHTML){
/******
* select_innerHTML - altera o innerHTML de um select independente se é FF ou IE
* Corrige o problema de não ser possível usar o innerHTML no IE corretamente
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Use a vontade mas coloque meu nome nos créditos. Dúvidas, me mande um email.
* Versão: 1.0 - 06/04/2006
* Autor: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br - elmicox.blogspot.com
* Parametros:
* objeto(tipo object): o select a ser alterado
* innerHTML(tipo string): o novo valor do innerHTML
*******/
    objeto.innerHTML = "";
    var selTemp = document.createElement("micoxselect");
    var opt;
    selTemp.id="micoxselect1";
    document.body.appendChild(selTemp);
    selTemp = document.getElementById("micoxselect1");
    selTemp.style.display="none";
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
        innerHTML = "<option>" + innerHTML + "</option>";
    }
    innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span");
    selTemp.innerHTML = innerHTML;
    for(var i=0;i<selTemp.childNodes.length;i++){
        if(selTemp.childNodes[i].tagName){
            opt = document.createElement("OPTION");
            for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){
                opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true));
            }
            opt.value = selTemp.childNodes[i].getAttribute("value");
            opt.text = selTemp.childNodes[i].innerHTML;
            if(document.all){ //IEca
                objeto.add(opt);
            }else{
                objeto.appendChild(opt);
            }
        }
    }
    document.body.removeChild(selTemp);
    selTemp = null;
}

function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277&
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        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);
            // extrai apenas o script
			var codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            var novo = document.createElement("script");
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}



/*==========================================================================================*/
/*==========================================================================================*/
/*==========================================================================================*/

function getRadioValue(radioName) {
	var valor;
	var radio = document.getElementsByName(radioName);

	for(i = 0; i < radio.length; i++){
		if(radio[i].checked) {
			valor = radio[i].value;
		}
	}

	return valor;
}


function mostra(div) {
	document.getElementById(div).style.display = 'block';
}

function esconde(div) {
	document.getElementById(div).style.display = 'none';
}

function mostraEsconde(div) {
	if(document.getElementById(div).style.display == 'none') {
		document.getElementById(div).style.display = 'block';
	}
	else{
		if(document.getElementById(div).style.display == 'block') {
			document.getElementById(div).style.display = 'none';
		}
	}

}

function buildParameterUrl(form, outrosParams, retiraNomeForm, debugUrl){
//retiraNomeForm = se true faz com que quando o js monta url passa os parametros sem o nome do form
//ex.: se retiraNomeForm == true o nome do parametro inves de ir 'form:param' ele vao apenas 'param'

	var urlParam = '?';
	var param = '';
	var debug = '';

	if (isExists(outrosParams)){
		urlParam = urlParam + outrosParams;
		debug = urlParam + outrosParams + '\n';
	}

	var parametroRequest = true;
	for (i=0;i<document.getElementById(form).elements.length;i++){
		parametroRequest = true;

		//se for check, so pega os que estao marcados
		if(document.getElementById(form).elements[i].type == "checkbox" &&
		   document.getElementById(form).elements[i].checked == 0){
		   parametroRequest = false;
		}

		if (parametroRequest == true){
			if (retiraNomeForm){
				if (isExists(document.getElementById(form).elements[i].id)){
					param = document.getElementById(form).elements[i].id.split(':');

					urlParam = urlParam + param[1] + '=' + escape(document.getElementById(form).elements[i].value ) + '&';

					debug = debug + param[1] + '=' +
										  document.getElementById(form).elements[i].value + '&\n';
				}
			}else{
				if (isExists(document.getElementById(form).elements[i].id)){
					urlParam = urlParam + document.getElementById(form).elements[i].id + '=' + escape(document.getElementById(form).elements[i].value ) + '&';

					debug = debug +       document.getElementById(form).elements[i].id + '=' +
										  document.getElementById(form).elements[i].value + '&\n';

				}
			}
		}
	}

	if (urlParam != '?'){
		urlParam = urlParam.substring(0, urlParam.length-1);
		debug = debug.substring(0, debug.length-1);
	}

	if (debugUrl){
		alert('DEBUG URL > \n' + debug);
	}

	return urlParam;
}



/* verifica se o valor passado é válido */
function isExists(valor) {
	return (valor != null && valor != 0 && valor != '' && valor != 'undefined');
}

function mostrar(idElement, style) {
	document.getElementById(idElement).style.display = style;
}

function fecharFlush(idElement) {
	var element = document.getElementById(idElement);
	element.style.display = "none";
	element.innerHTML = "";
}


/* Função usada para limitar tamanho de texto em um textarea */
function maxLength(element, limite, idLabel) {
	if(element.value.length > limite) {
		element.value = element.value.substring(0, limite);
		element.blur();
	}

	var indicador = document.getElementById(idLabel);
	if(indicador != null) {
		indicador.innerHTML = (parseInt(limite) - (element.value.length));
	}
}

/*===============================================================================================*/


//Tenta criar o objeto xmlHTTP
function getXmlhttp() {
	try{
	    var objXmlhttp = new XMLHttpRequest();
	} catch(ee) {
		objXmlhttp = null;
	   	axO = ['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
		var i = 0;

		while(objXmlhttp == null && i <= axO.length) {
			try {
				objXmlhttp = new ActiveXObject(axO[i]);
				i++;
			} catch(e) {
				objXmlhttp = null;
			}
		}
	}

	return objXmlhttp;
}

//Função que retorna o objeto fonte que disparou o evento
function getElementByEvent(e){

    //Correção para eventos quebrados da Microsoft
    if(typeof(e)=='undefined')var e=window.event
    source=e.target?e.target:e.srcElement
    //Correção para o bug do Konqueror/Safari
    if(source.nodeType==3)source=source.parentNode

    return source;
}

function showCarregando(idElement, load) {
	if(load!=false) {
		document.getElementById(idElement).innerHTML = "<span class='carregando'>Carregando...</span>";
    }
}

function ajaxExec(url) {
	ajaxHTMLTag('none', url, null, false);
}

//Carrega via XMLHTTP a url recebida e coloca seu valor no objeto com o id recebido
function ajaxHTML(idElement, url) {
	ajaxHTMLTag(idElement, url, "ajax_response", false);
}

// execução sincronizada
function sjaxHTMLTag(idElement, url, ajaxTag, load) {
	showCarregando(idElement, load);
	ajaxRun(idElement, url, ajaxTag, false, false);
}

function ajaxHTMLTag(idElement, url, ajaxTag, load) {
	showCarregando(idElement, load);
	ajaxRun(idElement, url, ajaxTag, false, true);
}

function ajaxHTMLTagAppend(idElement, url, ajaxTag, load) {
	showCarregando(idElement, load);
	ajaxRun(idElement, url, ajaxTag, true, true);
}

function ajaxRun(idElement, url, ajaxTag, ajax_append, assincrono) {

	//Abre a conexão
	var objXmlhttp = getXmlhttp();

	if(objXmlhttp) {
		objXmlhttp.open("POST", url, assincrono);

		//objXmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
		objXmlhttp.setRequestHeader("Cache-Control", "no-cache");
		objXmlhttp.setRequestHeader("Pragma", "no-cache");

		//Função para tratamento do retorno
		objXmlhttp.onreadystatechange=function() {
			if(objXmlhttp.readyState == 4) {
				checkResponse(objXmlhttp, idElement, ajaxTag, ajax_append);
	        }

			return true;
	    }

		//Executa
		objXmlhttp.send(null);

		if(!assincrono) {
			checkResponse(objXmlhttp, idElement, ajaxTag, ajax_append);
		}

	}

}

function checkResponse(objXmlhttp, idElement, ajaxTag, ajax_append) {

	if(objXmlhttp.status == 200) {
		//Mostra o HTML recebido
		var retorno = unescape(objXmlhttp.responseText.replace(/\+/g," "));

		// Atualiza div mensagensSistema
		showMensagens(retorno);

		// Tempo de vida da sessão
		timeToLive(0);

		retorno = getByTag(retorno,ajaxTag);

		if(ajax_append){
			document.getElementById(idElement).innerHTML += retorno;
		}
		else{
			if (idElement != 'none') {
				document.getElementById(idElement).innerHTML = retorno;
			}
		}
	}
	else {
		document.getElementById(idElement).innerHTML = "<span class='carregando'>Falha no carregamento!</span>";
	}

}

function getByTag(textHtml,ajaxTag){

	var tag		= '<!--'+ajaxTag+'-->';
	var endTag	= '<!--/'+ajaxTag+'-->';

	if(textHtml.indexOf(tag,0) >= 0 && textHtml.indexOf(endTag,0) >= 0) {
		textHtml = textHtml.substring(textHtml.indexOf(tag,0)+tag.length ,textHtml.indexOf(endTag,0));
	}
	else {
		textHtml = '';
	}

	return textHtml;
}



/* MENSAGENS */

function showMensagens(conteudo) {
	// Atualiza div mensagensSistema
	if(isExists(document.getElementById('mensagensSistema'))) {
		var conteudo = getByTag(conteudo,"ajax_mensagensSistema");

		if(isExists(conteudo)) {
			document.getElementById("mensagensSistema").innerHTML = conteudo;

			contagemRegressivaMensagem();
		}
	}
}


// Este atributo pode ser parametrizado em cada sistema.
var tempoMensagem = 2; //segundos
var timeOutMensagem;

function contagemRegressivaMensagem() {
	// testa se existe a div mensagens
	var elMensagensSistema = document.getElementById('mensagensSistema');
	if(isExists(elMensagensSistema) && isExists(elMensagensSistema.innerHTML)) {
		mostrar('mensagensSistema', 'block');
		clearTimeout(timeOutMensagem);
		timeOutMensagem = setTimeout("fecharMensagem()", tempoMensagem * 1000);
	}
}

function fecharMensagem() {
	fecharFlush('mensagensSistema');
}

/**/



/* TEMPO DE VIDA DA SESSÃO */
// Este atributo pode ser parametrizado em cada sistema.
var ativarTimeToLive = true;
var tempoExpira = 30; //minutos
var intervaloKeepAlive = 9; //minutos
var countKeepAlive = 0;
var timeOutExpira;

function timeToLive(contador) {
	if(ativarTimeToLive) {

		if(contador != null) {
			countKeepAlive = contador
		}

		countKeepAlive += intervaloKeepAlive;

		if(countKeepAlive <= tempoExpira) {
			clearTimeout(timeOutExpira);
			timeOutExpira = setTimeout("keepAlive()", intervaloKeepAlive * 60000);
		}
		else {
			expirarSessao();
		}
	}
}

function keepAlive() {
	timeToLive();
	callURL("/keepAlive.jsf");
}

function expirarSessao() {
	alert("Sessão expirada!");
	window.location.href = '/' + document.URL.split('/')[3] + '/cadastro/Usuario/sairPortal.jsf';
}

/**/



//-------AUTO COMPLETE-----//

var index = 0;
var UlList = Array();
document.onkeyup=Navigator;
var List;
var Imput;
var Dest;
function AjaxAutoComplete(input,list,destino,qtdC,url,e){

	List = $(list);
	Imput = $(input);
	Dest = $(destino);

	if(window.event){//IE
		key = e.keyCode;
	}else{//MOZILA
		key = e.which
	}

	if(Imput.value.length % qtdC == 0 && key != 40 && key != 38){

			ajaxHTML(list,url+'?query='+$(input).value);
			UlList = $(list).getElementsByTagName('li');
			index = 0;
			List.style.display = 'block';
	}

}
function clearColor(list){
	for(i=0;i<list.length;i++){
		list[i].style.color='';
	}
}
function Navigator(e){

	var key;

	if(isExists(window.event)){//IE
		key = window.event.keyCode;
	}else{//MOZILA
		key = e.which;
	}

	if(key==40 && index< UlList.length-1){

		index++;
		List.focus();
		Li = UlList[index];

		Dest.value = Li.getElementsByTagName('input')[0].value;
		Imput.value = Li.getElementsByTagName('span')[0].innerHTML;

	}else if(key==38 && index>0){
		index--;
		List.focus();
		Li = UlList[index];
		//Imput.value = Li.innerHTML;
		Dest.value = Li.getElementsByTagName('input')[0].value;
		Imput.value = Li.getElementsByTagName('span')[0].innerHTML;
	}
	if(UlList.length>0){
		clearColor(UlList)
		UlList[index].style.color='red';

	}
}


    function callURL(url) {

        http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            return false;
        }
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', url, true);
        http_request.send(null);

    }


function alertContents() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                //alert(http_request.responseText);
            } else {
                alert('Erro: problema no request.');
            }
        }
}
/*
contador = 0;
function keepAliveSession(){
	tempoMaximo = 30; //Considere como minutos * 10
		if ((contador <= tempoMaximo)) {
			callURL("/keepAlive.jsf");
			setTimeout("keepAliveSession()", 60000 * 9.999); //60000 * 9.999
		} else {
			alert("Sessão expirada");
			//window.location.href = '/' + document.URL.split('/')[3] + '/cadastro/Usuario/logar.jsf';
			window.location.href = '/' + document.URL.split('/')[3] + '/sites/sistemas/autoatendimento/principal/formLogin.jsf';
		}
		contador++;
	}
*/
function confirmaRedirect(mensagem, url){
	if (confirm(mensagem)) {
			window.location.href = url;
	} else {
			window.location.href = document.URL;
	}

}


//=========================================================================================
//mostra o carregando em outra div
function ajaxHTMLTag2(id,url,ajaxTag,load, divCarregando){

	//Carregando...
	if(load!=false){
    	document.getElementById(divCarregando).innerHTML="<span class='carregando'>Carregando...</span>";
    }

    //Abre a conexão
    xmlhttp.open("POST",url,true);

    //Função para tratamento do retorno
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //Mostra o HTML recebido
            retorno=unescape(xmlhttp.responseText.replace(/\+/g," "))

			retorno = getByTag(retorno,ajaxTag);

       		document.getElementById(id).innerHTML=retorno;

			document.getElementById(divCarregando).innerHTML="";
        }
    }
    //Executa
    xmlhttp.send(AjaxPostArgs);




}

//==========================================================================================


function trim(str){return str.replace(/^\s+|\s+$/g,"");}


function addslashes(str) {
   return (str).replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}


//--------------------------------------------
// Envio de email
//--------------------------------------------
function enviarEmailContato() {
	var nome       = document.getElementById("contatoNome").value;
	var email      = document.getElementById("contatoEmail").value;
	var tipo       = document.getElementById("contatoTipo").value;
	var comentario = document.getElementById("contatoComentario").value;

	fecharFlush("caixaFaleConosco");
	ajaxHTMLTag('none', '/jportal/sites/sistemas/inc/contato.jsf?enviarEmailContato=S&nome='+escape(nome)+'&email='+email+'&tipo='+tipo+'&comentario='+escape(comentario), null, false);
}

// Data e Hora atual do servidor
function getDateTime() {

	var datetime;

	//Abre a conexão
	var objXmlhttp = getXmlhttp();

	if(objXmlhttp) {
		objXmlhttp.open("POST", "/datetime.jsf", false);

		//objXmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
		objXmlhttp.setRequestHeader("Cache-Control", "no-cache");
		objXmlhttp.setRequestHeader("Pragma", "no-cache");

		//Executa
		objXmlhttp.send(null);

		datetime = unescape(objXmlhttp.responseText.replace(/\+/g," "));
	}

	return datetime;

}

function getDate() {
	var date = getDateTime();
	return date.substring(0, date.indexOf(" "));
}


