function chama_ancora(ancora) 
	{
		this.location = "#" + ancora;
	}

function ajaxGet(url,elemento_retorno,exibe_carregando){
/******
* 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.
* Versão: 1.2 - 20/04/2006
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
* 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){
        url = antiCacheRand(url)
        ajax1.onreadystatechange = ajaxOnReady
        ajax1.open("GET", 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");
        if(exibe_carregando){ put("<img src=\"imagens/ajax_loader.gif\" border=\"0\" alt=\"\" /> Carregando ...")    }
        ajax1.send(null)
        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
        }else if(exibe_carregando){//para mudar o status de cada carregando
                put("<img src=\"imagens/ajax_loader.gif\" border=\"0\" alt=\"\" /> 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&ccedil;&atilde;o incompreensível"; break;
            case 403: case 404: return "404: N&atilde;o foi encontrada a URL solicitada"; break;
            case 405: return "405: O servidor n&atilde;o suporta o m&eacute;todo solicitado"; break;
            case 500: return "500: Erro desconhecido de natureza do servidor"; break;
            case 503: return "503: Capacidade m&aacute;xima do servidor alcançada"; break;
            default: return "Erro " + stat + ". Mais informa&ccedil;&otilde;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 José C. Guimarães - micoxjcg@yahoo.com.br
* 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
            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.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

// FUNÇÕES
function question(frase,endereco)
	{
		if(confirm(frase))
			{
				window.location=endereco;
			}
	}
	
function verifica_usuario(div,usuario_ate_atual)
	{
		var usuario_ate = document.getElementById("usuario_ate").value;
		var url;
		alvo = document.getElementById(div);
		url = "atendente.php?action=verifica_usuario&usuario_ate="+usuario_ate+"&usuario_ate_atual="+usuario_ate_atual;
		ajaxGet(url,alvo,false);
	}

function prepara_relatorio(div,opcao)
	{
		var url;
		alvo = document.getElementById(div);
		url = "relatorio.php?action=prepara_relatorio&opcao="+opcao;
		ajaxGet(url,alvo,false);
	}
	
function insere_resposta_pronta()
	{
		if(document.getElementById("desc_res").value != "")
			{
				document.getElementById("mensagem_msg").value = document.getElementById("desc_res").value;
			}
		document.getElementById("desc_res").selectedIndex = 0;
		document.getElementById("mensagem_msg").focus();
	}
	
function verifica_limite_caracteres()
	{
		if(document.getElementById("mensagem_msg").value.length >= 500)
			{
				document.getElementById("mensagem_msg").value = document.getElementById("mensagem_msg").value.substr(0,499);
			}
	}
	
function atualiza_sessao_ate(div)
	{
		if(document.getElementById("situacao_ate").checked == true)
			{
				var situacao_ate = 0;
			}
		else
			{
				var situacao_ate = 1;
			}
		var id_cla = document.getElementById("id_cla").value;
		var id_atm = document.getElementById("id_atm").value;
		var id_ate_destino_msg = document.getElementById("id_ate_destino_msg").value;
		var url;
		alvo = document.getElementById(div);
		url = "atendimento.php?action=atualiza_sessao_ate&id_cla="+id_cla+"&id_atm="+id_atm+"&id_ate_destino_msg="+id_ate_destino_msg+"&situacao_ate="+situacao_ate;
		ajaxGet(url,alvo,false);
	}

function cliente_atualiza_sessao_atm(div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "cliente_atm.php?action=cliente_atualiza_sessao_atm";
		ajaxGet(url,alvo,false);
	}
	
function cliente_verifica_sessao_ate(id_ide,div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "cliente_atm.php?action=cliente_verifica_sessao_ate&id_ide="+id_ide;
		ajaxGet(url,alvo,false);
	}
	
function envia_msg(origem_msg,div)
	{
		var id_cla = document.getElementById("id_cla").value;
		var id_atm = document.getElementById("id_atm").value;
		var id_ate_destino_msg = document.getElementById("id_ate_destino_msg").value;
		var mensagem_msg =  document.getElementById("mensagem_msg").value;
		mensagem_msg = mensagem_msg.replace("&",'[comercial]');
		mensagem_msg = mensagem_msg.replace("+",'[mais]');
		var url;
		alvo = document.getElementById(div);
		url = "cliente_atm.php?action=envia_msg&mensagem_msg="+mensagem_msg+"&origem_msg="+origem_msg+"&id_cla="+id_cla+"&id_atm="+id_atm+"&id_ate_destino_msg="+id_ate_destino_msg;
		ajaxGet(url,alvo,false);
		document.getElementById("mensagem_msg").value = '';
		document.getElementById("mensagem_msg").focus();
	}
	
function clientes_disponiveis_atm(div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "atendimento.php?action=clientes_disponiveis_atm";
		ajaxGet(url,alvo,false);
	}

function atendentes_disponiveis(div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "atendimento.php?action=atendentes_disponiveis";
		ajaxGet(url,alvo,false);
	}
	
function muda_cor_atendimento_ico(cor,id_ide_sessao,div)
	{
		document.getElementById("cor").value = cor;
		if(cor == "")
			{
				cor = '006699';
			}
		if(document.getElementById("icone").checked == true)
			{
				var icone = 1;
			}
		else
			{
				var icone = 0;
			}
		document.getElementById("codigo").value = '<script type="text/javascript" src="http://atendimento.samuca.eti.br/verifica_status.php?id_ide='+id_ide_sessao+'&cor=\''+cor+'\'&icone='+icone+'"></script>';
		var url;
		alvo = document.getElementById(div);
		url = "configuracao.php?action=muda_cor_atendimento_ico&cor="+cor;
		ajaxGet(url,alvo,false);
	}
	
function busca_lista_espera(id_ide,id_cla,id_dep,div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "espera.php?action=busca_lista_espera&id_ide="+id_ide+"&id_cla="+id_cla+"&id_dep="+id_dep;
		ajaxGet(url,alvo,false);
	}
	
function verifica_tecla(origem,event)
	{
		var keynum;  
		if(window.event) 
			{ //IE   
				keynum = event.keyCode;
				if(keynum == 13)
					{
						envia_msg(origem,'divEnvioMensagem');
						document.getElementById('divMensagem').innerHTML = '<textarea name="mensagem_msg" cols="45" id="mensagem_msg" style="height:75%;width:100%;padding:2px;background-color:#FFFFFF;border:none;" onkeypress="verifica_tecla('+origem+',event);" onkeyup="verifica_limite_caracteres();"></textarea>';
						document.getElementById("mensagem_msg").focus();
					}

			} 
		else if(event.which) 
			{ // Netscape/Firefox/Opera 
				keynum = event.which;
				if(keynum == 13)
					{
						envia_msg(origem,'divEnvioMensagem');
						document.getElementById('divMensagem').innerHTML = '<textarea name="mensagem_msg" cols="45" id="mensagem_msg" style="height:75%;width:100%;padding:2px;background-color:#FFFFFF;border:none;" onkeypress="verifica_tecla('+origem+',event);" onkeyup="verifica_limite_caracteres();"></textarea>';
						document.getElementById("mensagem_msg").focus();
					}
			}
		document.getElementById("mensagem_msg").focus();
	}
	
function seleciona_cliente(id_atm,id_cla,nome_cla,email_cla,div)
	{
		document.getElementById("id_cla").value = id_cla;
		document.getElementById("id_atm").value = id_atm;
		document.getElementById("id_ate_destino_msg").value = 0;
		document.getElementById(div).innerHTML = '<strong>Voc&ecirc; est&aacute; falando com: </strong>'+nome_cla+' ('+email_cla+')';
		document.getElementById("rolagem").disabled = false;
		//document.getElementById("som").disabled = false;
		document.getElementById("mensagem_msg").disabled = false;
		document.getElementById("butEnviar").disabled = false;
		document.getElementById("butFinalizar").disabled = false;
		document.getElementById("butTrasferir").disabled = false;
		document.getElementById("desc_res").disabled = false;
		document.getElementById("mensagem_msg").focus();
		document.getElementById("mensagem").innerHTML = 'Carregando...';
	}
	
function seleciona_atendente(id_ate,nome_ate,div)
	{
		document.getElementById("id_cla").value = 0;
		document.getElementById("id_atm").value = 0;
		document.getElementById("id_ate_destino_msg").value = id_ate;
		document.getElementById(div).innerHTML = '<strong>Voc&ecirc; est&aacute; falando com o(a) atendente: </strong>'+nome_ate;
		document.getElementById("rolagem").disabled = false;
		//document.getElementById("som").disabled = false;
		document.getElementById("mensagem_msg").disabled = false;
		document.getElementById("butEnviar").disabled = false;
		document.getElementById("butFinalizar").disabled = true;
		document.getElementById("butTrasferir").disabled = true;
		document.getElementById("desc_res").disabled = false;
		document.getElementById("mensagem_msg").focus();
		document.getElementById("mensagem").innerHTML = 'Carregando...';
	}

function ate_finaliza_atm(frase,div)
	{
		var id_cla = document.getElementById("id_cla").value;
		var id_atm = document.getElementById("id_atm").value;
		if((id_cla != '') && (id_atm != ''))
			{
				if(confirm(frase))
					{
						document.getElementById("titulo").innerHTML += '<font style="color:#FF0000"> Finalizado</font>';
						var url;
						alvo = document.getElementById(div);
						url = "atendimento.php?action=ate_finaliza_atm&id_atm="+id_atm;
						ajaxGet(url,alvo,false);
						document.getElementById("mensagem_msg").focus();
					}
			}
	}
	
function toca_som(div)
	{
		if(document.getElementById("som").checked == true)
			{
				var url;
				alvo = document.getElementById(div);
				url = "cliente_atm.php?action=toca_som";
				ajaxGet(url,alvo,false);
			}
	}
	
function toca_som_novo_cliente(div)
	{
		if(document.getElementById("som").checked == true)
			{
				var url;
				alvo = document.getElementById(div);
				url = "cliente_atm.php?action=toca_som_novo_cliente";
				ajaxGet(url,alvo,false);
			}
	}
	
function toca_som_novo_visitante(div)
	{
		if(document.getElementById("som").checked == true)
			{
				var url;
				alvo = document.getElementById(div);
				url = "cliente_atm.php?action=toca_som_novo_visitante";
				ajaxGet(url,alvo,false);
			}
	}
	
function historico_atm(id_atm,div,div2)
	{
		document.getElementById(div).innerHTML = '<a href="javascript:historico_atm_fechar('+id_atm+',\''+div+'\',\''+div2+'\');">Fechar (x)</a>';
		document.getElementById(div2).style.display = '';
		var url;
		alvo = document.getElementById(div2);
		url = "historico.php?action=historico_atm&id_atm="+id_atm;
		ajaxGet(url,alvo,true);
	}
	
function historico_atm_fechar(id_atm,div,div2)
	{
		document.getElementById(div).innerHTML = '<a href="javascript:historico_atm('+id_atm+',\''+div+'\',\''+div2+'\');">Visualizar</a>';
		document.getElementById(div2).style.display = 'none';
	}
	
function muda_status_digitacao(origem_sts,div)
	{
		var id_cla = document.getElementById("id_cla").value;
		var id_atm = document.getElementById("id_atm").value;
		if((id_cla != '') && (id_cla != 0) && (id_atm != '') && (id_atm != 0))
			{
				if(document.getElementById("mensagem_msg").value.length > 1)
					{
						var url;
						alvo = document.getElementById(div);
						url = "atendimento.php?action=muda_status_digitacao&origem_sts="+origem_sts+"&id_cla="+id_cla+"&id_atm="+id_atm;
						ajaxGet(url,alvo,false)
					}
			}
	}
	
function verifica_status_digitacao(origem_sts,div)
	{
		var id_cla = document.getElementById("id_cla").value;
		var id_atm = document.getElementById("id_atm").value;
		if((id_cla != '') && (id_cla != 0) && (id_atm != '') && (id_atm != 0))
			{	
				var url;
				alvo = document.getElementById(div);
				url = "cliente_atm.php?action=verifica_status_digitacao&origem_sts="+origem_sts+"&id_cla="+id_cla+"&id_atm="+id_atm;
				ajaxGet(url,alvo,false)
			}
	}
	
function mostra_esconde_div(opcao,fundo,div)
	{
		if(opcao == 1)
			{
				document.getElementById(div).style.visibility = "hidden"; 
			}
		else
			{
				document.getElementById(div).style.visibility = "visible";
			}
		if(fundo == 1)
			{
				document.getElementById("divFundo").style.visibility = "hidden"; 
			}
		else
			{
				document.getElementById("divFundo").style.visibility = "visible";
			}
		// p/ ter certeza que vai parar a verificação dos atendentes disponíveis
		document.getElementById('verifica_atendentes_transferencia').value = '0'
	}
	
function atendentes_disponiveis_transferencia(div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "atendimento.php?action=atendentes_disponiveis_transferencia";
		ajaxGet(url,alvo,false);
	}
	
function visitantes_online_atm(div)
	{
		var url;
		alvo = document.getElementById(div);
		url = "atendimento.php?action=visitantes_online_atm";
		ajaxGet(url,alvo,false);
	}
	
function transfere_atendimento(id_ate,frase,div)
	{
		if(confirm(frase))
			{
				var id_atm = document.getElementById("id_atm").value;
				var id_cla = document.getElementById("id_cla").value;
				var url;
				alvo = document.getElementById(div);
				url = "atendimento.php?action=transfere_atendimento&id_ate="+id_ate+"&id_atm="+id_atm+"&id_cla="+id_cla;
				ajaxGet(url,alvo,false);
				mostra_esconde_div(1,1,'divTransferencia');
			}
	}
	
function seta_altura_div(altura,div)
	{
		document.getElementById(div).style.height = ''+altura+'px';
	}
	
function convidar_visitante(id_vis,frase,div,div2)
	{
		if(confirm(frase))
			{
				document.getElementById(div2).innerHTML = '<font style="color:#660099;">» Convidado, aguardando resposta...</font>';
				var url;
				alvo = document.getElementById(div);
				url = "atendimento.php?action=convidar_visitante&id_vis="+id_vis;
				ajaxGet(url,alvo,false);
			}	
	}
	
function mostra_esconde_div_geral(opcao,div)
	{
		var div_c = document.getElementById(div);
		if(opcao == 0)
			{
				div_c.style.display = 'none';
			}
		else
			{
				div_c.style.display = '';
			}
	}
/*function verifica_bloqueador_popup()
	{
		var pop = window.open("about:blank","_blank","width=10,height=100,top=0,left=0");
		if (null == pop || true == pop.closed)
			{
				h = 1;
				if(msg == 1)
					{
						alert("Atenção! Detectamos que você está com seu anti-popup ativado, para o perfeito funcionamento do sistema, habilite este popup ou desative seu anti-popup.");
						msg = 2;
					}
			} 
		else
			{
				h = 0;
				pop.close();
			}
	}*/
