// JavaScript Document

// SAIR DO GERENCIADFOR
function sairGerenciador(){
	if(confirm("Deseja sair do gerenciador?")){
		window.location='sair.php'	
	}
}

// TROCA IMGEME
function trocaImgSair1(){
	document.all.sair.src='imagens/sair1.png'
}

// SAIR NORMAL
function trocaImgSair2(){
	document.all.sair.src='imagens/sair.png'
}

// TROCA IMGEME
function trocaImgHome1(){
	document.all.inicial.src='imagens/home1.jpg'
}

// SAIR NORMAL
function trocaImgHome2(){
	document.all.inicial.src='imagens/home.jpg'
}

// LINHA SELECIONA
function M_over(src,clrOver) {
 if (!src.contains(event.fromElement)) {
  src.style.cursor = 'default';
  src.bgColor = clrOver;
 }
}
function M_out(src,clrIn) {
 if (!src.contains(event.toElement)) {
  src.style.cursor = 'default';
  src.bgColor = clrIn;
 }
}

// NOVA JANELA
function NovaJanela(mypage, myname, w, h, scroll, status) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+', status='+status+''
win = window.open(mypage, myname, winprops)
if (parseInt(navigator.appVersion) >= 4) { win.window.focus();
}
}

// janela menu
function JanelaMenu(mypage, myname, w, h, scroll, status, menu) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+', status='+status+', menubar='+menu+''
win = window.open(mypage, myname, winprops)
	if(parseInt(navigator.appVersion) >= 4){
		win.window.focus();
	}
}

// FAVORITOS
function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
}

// RELOGIO
function atualizarelogio(){
var hoje=new Date()
var hora=hoje.getHours()
var minuto=hoje.getMinutes()
var seconds=hoje.getSeconds()

  if(hora<10){hora="0" + hora}
  if(minuto<10){minuto="0" + minuto}
  if(seconds<10){seconds="0" + seconds}

relog.innerText = hora + ":" + minuto // + ":" + seconds

setTimeout("atualizarelogio()",1000)
}

// RELOGIO
function atualizarelogio1(){
var hoje=new Date()
var hora=hoje.getHours()
var minuto=hoje.getMinutes()
var seconds=hoje.getSeconds()

  if(hora<10){hora="0" + hora}
  if(minuto<10){minuto="0" + minuto}
  if(seconds<10){seconds="0" + seconds}

relog.innerText = hora + ":" + minuto

setTimeout("atualizarelogio1()",1000)
}

// FRASE DO RODAPE
var hellotext=""
var thetext=""
var started=false
var step=0
var times=1
 function welcometext()
    {
      times--
      if (times==0)
      {
        if (started==false)
        {
          started = true;
          window.status = hellotext;
          setTimeout("anim()",1);
        }
        thetext = hellotext;
      }
    }
 function showstatustext(txt)
    {
      thetext = txt;
      setTimeout("welcometext()",4000)
      times++
    }
 function anim()
    {
     step++
      if (step==7) {step=1}
      if (step==1) {window.status='>==='+thetext+'===<'}
      if (step==2) {window.status='=>=='+thetext+'==<='}
      if (step==3) {window.status='>=>='+thetext+'=<=<'}
      if (step==4) {window.status='=>=>'+thetext+'<=<='}
      if (step==5) {window.status='==>='+thetext+'=<=='}
      if (step==6) {window.status='===>'+thetext+'<==='}
      setTimeout("anim()",200);
    }
//welcometext();

// MASCARA MOEDA
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // PRECO para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

// tira o controle do flash
function flash(arqflash,largura,altura) {
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="' + largura + '" height="' + altura + '">');
	document.write('<param name="movie" value="' + arqflash + '" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="menu" value="false" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('<embed src="' + arqflash + '" width="' + largura + '" height="' + altura + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false" wmode="transparent"></embed>');
	document.write('</object>');
}

// MOSTRA LAYER DO GERENCIADOR
var top = ((screen.height-95)/3)-20;
var left = (screen.width-228)/2;
function show(){ 
	Layer1.style.visibility="visible";
	Layer1.style.top=top;
	Layer1.style.left=left;
}

function hide(){ 
	Layer1.style.visibility="hidden"; 
}

// EMAIL
function mail(email){
	var email = decode64(email);
	document.location.href='mailto:'+email;
}


// 
var keyStr = "ABCDEFGHIJKLMNOP" +
               "QRSTUVWXYZabcdef" +
               "ghijklmnopqrstuv" +
               "wxyz0123456789+/" +
               "=";

function encode64(input) {
     input = escape(input);
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
           enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
           enc4 = 64;
        }

        output = output +
           keyStr.charAt(enc1) +
           keyStr.charAt(enc2) +
           keyStr.charAt(enc3) +
           keyStr.charAt(enc4);
		   
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

     } while (i < input.length);

     return output;

}



function decode64(input) {
     var output = "";
     var chr1, chr2, chr3 = "";
     var enc1, enc2, enc3, enc4 = "";
     var i = 0;

     // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
     var base64test = /[^A-Za-z0-9\+\/\=]/g;
     if (base64test.exec(input)) {
        alert("There were invalid base64 characters in the input text.\n" +
              "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
              "Expect errors in decoding.");
     }

     input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

     do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

    	if (enc3 != 64) {
           output = output + String.fromCharCode(chr2);
        }

        if (enc4 != 64) {
           output = output + String.fromCharCode(chr3);
        }

        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";

     } while (i < input.length);

     return unescape(output);

}

// TROCA ENTRE
function trocaEnter(campo, evt) {
    var e = evt || event;
    k = e.keyCode;
    
    if(k == 13) {
		buscar();
        return false;
    }
}


// POSIÇÃO LAYER INICIAL
function pos(){
	document.getElementById("logo").style.left = ((screen.width - 520) / 2);
	document.getElementById("logo").style.top = 60;

	document.getElementById("logoPortal").style.left = 10;
	document.getElementById("logoPortal").style.bottom = 10;
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
                    return true; 
                }
    }else{
        return false;
        }
}
function cancelarContato(){
	if(confirm("Deseja realmente cancelar seu contato?")){
		window.top.location = "index.php";
	}
}
function confirmarContato(){
	nome = document.frmContato.NOME.value;
	empresa = document.frmContato.EMPRESA.value;
	cidade = document.frmContato.CIDADE.value;
	estado = document.frmContato.ESTADO.value;
	assunto = document.frmContato.ASSUNTO.value;
	mensagem = document.frmContato.MENSAGEM.value;
	retorno = document.frmContato.RETORNO.value;
	telefone = document.frmContato.TELEFONE.value;
	email = document.frmContato.EMAIL.value;
	motivo = document.frmContato.MOTIVO.value;
		
		if((nome != "") && (cidade != "") && (assunto != "") && (mensagem != "") && (telefone != "") && (email != "")){
			if(checkMail(email)) {
				document.frmContato.submit();
			} else {
				alert("O email informado não é válido!")
			}
		} else {
			alert("Preencha todos os campos marcados com asterisco (*)!")
		}
}

// EXECUTA AÇÃO
function executeAcao(acao){
	var head 	= document.getElementsByTagName('head').item(0);
	var eScript = document.createElement("script");

	// BUSCA RAPIDA
	if(acao == 'boletoBB'){
		idConv = document.pagamento.idConv.value;
		refTran = document.pagamento.refTran.value;
		valor = document.pagamento.valor.value;
		dtVenc = document.pagamento.dtVenc.value;
		tpPagamento = document.pagamento.tpPagamento.value;
		numPedido = document.pagamento.numPedido.value;

		// CARREGA A PAGINA DE INSETIR VEICULOS
		eScript.setAttribute('src','acoes.php?idConv='+idConv+'&refTran='+refTran+'&valor='+valor+'&dtVenc='+dtVenc+'&tpPagamento='+tpPagamento+'&numPedido='+numPedido+'&acao='+acao);
	}
	
	head.appendChild(eScript);

}

// de 30 a 0 //
var segundos = 60;
var minutos = 59;

function startCountdown(){
	if((minutos > 0) || (segundos > 0)){
		
		segundos = segundos - 1;
		segMostra = segundos;
		minMostra = minutos;
	   
			if(segundos == 0){
				minutos = minutos - 1;
				segundos = 60;
			}
			
			if(segundos < 10){ segMostra = '0'+segundos; }
			if(segundos == 60){	segMostra = '00'; }
			if(minutos < 10){
				minMostra = '0'+minMostra;
			}
			
	   // mostra
	   mostra = minMostra+':'+segMostra;
	   document.getElementById("mostraClock").innerText = mostra;
	   
			// para a index
			if(mostra == "00:00"){
				window.location='index.php?erro=Sua sessão expirou!';
			}
	   
	   setTimeout('startCountdown()',1000);
	   
	}
}

function OpenSaibaMais(){
	window.open('http://www.visa.com.br/vbv/vbv_saibamais.asp','principal','height=435,width=270,top=0,left=0,resizable=no,status=1')
}

function somente_numero(campo){

	var digits="0123456789"
	var campo_temp 

	for (var i=0;i<campo.value.length;i++){
		
		campo_temp=campo.value.substring(i,i+1) 
		
		if (digits.indexOf(campo_temp)==-1){
			campo.value = campo.value.substring(0,i);
			break;
		}
	}
}

function ajustaLayer(){
	var larguraLayerTitulo = document.getElementById("principalMeio").offsetWidth;
	document.getElementById("principalMeioImagem").style.width = larguraLayerTitulo;
//	alert(larguraLayerTitulo);
}


// EXECUTA AÇÃO
function gravaCor(cor,descricao){
	linkNovo = document.getElementById("linkCarrinho").href;
	document.getElementById("linkCarrinho").href = linkNovo + '&corSel='+cor;
	alert("Você selecionou a cor " + descricao);
}

function html2entities(str){
	var keys=new Array("&", " ", "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "­", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "\"", "<", ">", "");
    var values=new Array("&amp;", "&nbsp;", "&iexcl;", "&cent;", "&pound;", "&curren;", "&yen;", "&brvbar;", "&sect;", "&uml;", "&copy;", "&ordf;", "&laquo;", "&not;", "&shy;", "&reg;", "&macr;", "&deg;", "&plusmn;", "&sup2;", "&sup3;", "&acute;", "&micro;", "&para;", "&middot;", "&cedil;", "&sup1;", "&ordm;", "&raquo;", "&frac14;", "&frac12;", "&frac34;", "&iquest;", "&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Auml;", "&Aring;", "&AElig;", "&Ccedil;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Euml;", "&Igrave;", "&Iacute;", "&Icirc;", "&Iuml;", "&ETH;", "&Ntilde;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ouml;", "&times;", "&Oslash;", "&Ugrave;", "&Uacute;", "&Ucirc;", "&Uuml;", "&Yacute;", "&THORN;", "&szlig;", "&agrave;", "&aacute;", "&acirc;", "&atilde;", "&auml;", "&aring;", "&aelig;", "&ccedil;", "&egrave;", "&eacute;", "&ecirc;", "&euml;", "&igrave;", "&iacute;", "&icirc;", "&iuml;", "&eth;", "&ntilde;", "&ograve;", "&oacute;", "&ocirc;", "&otilde;", "&ouml;", "&divide;", "&oslash;", "&ugrave;", "&uacute;", "&ucirc;", "&uuml;", "&yacute;", "&thorn;", "&yuml;", "&quot;", "&lt;", "&gt;", "");
    for(var i=0; i<keys.length; i++)
        {if(keys[i]!="&nbsp;"){str=str.replace(values[i], keys[i]);}}
    return str;
}


// ATENBDIMENTO ONLINE
function executeAcao(acao, id_registro){
	var head 	= document.getElementsByTagName('head').item(0);
	var eScript = document.createElement("script");


	// status dos atendentes
	if(acao=='checaStatusVerifica'){
		url = 'atendimento_status.php?acao='+acao+'&'+Math.ceil(Math.random()*100000);
		eScript.setAttribute('src',url);
	}

	// CHECA NOVO ATENDIMENTO
	if(acao=='checaNovoVerifica'){
		idvendedor = document.getElementById('IDVENDEDOR').value;
		url = 'atendimento_status.php?idvendedor='+idvendedor+'&acao='+acao+'&'+Math.ceil(Math.random()*100000);
		eScript.setAttribute('src',url);
	}

	// NOVA MENAGEM DIGITADA
	if(acao=='novaMensagem'){
		atendimento = document.getElementById('ATENDIMENTO').value;
		origem = document.getElementById('ORIGEM').value;
		m = document.getElementById('MENSAGEM_OK').value;
		m1 = m.replace(/"/g,'');
		msg = m1.replace(/#/g,'');
		msg1 = html2entities(msg);
		
		nomecli = document.getElementById('NOMECLI').value;
		apelidocli = document.getElementById('APELIDOCLI').value;
		nomeven = document.getElementById('NOMEVEN').value;
		apelidoven = document.getElementById('APELIDOVEN').value;
		
		url = 'atendimento_status.php?atendimento='+atendimento+'&origem='+origem+'&acao='+acao+'&msg='+msg1+'&nomecli='+nomecli+'&apelidocli='+apelidocli+'&nomeven='+nomeven+'&apelidoven='+apelidoven+'&'+Math.ceil(Math.random()*100000);
		
		eScript.setAttribute('src',url);

	}

	// finaliza a função
	head.appendChild(eScript);
}


// CHEGA OS ALERTAS
function checaStatus(){
	executeAcao("checaStatusVerifica");
	setTimeout("checaStatus()",5000);
}

// CHEGA OS ALERTAS
function checaNovo(){
	executeAcao("checaNovoVerifica");
	setTimeout("checaNovo()",2000);
}

// CHEGA OS ALERTAS
function checaMensagens(atendimento, idatendente){
	
	url = "atendimento_mensagens.php?atendimento="+atendimento+'&idatendente='+idatendente+'&'+Math.ceil(Math.random()*100000);
	carregaDados("chat",url);
	setTimeout("checaMensagens('"+atendimento+"','"+idatendente+"')",2000);
}

// TROCA ENTRE
function trocaEnterChat(campo, evt) {
    var e = evt || event;
    k = e.keyCode;
    
    if(k == 13) {
		novaMensagem();
        return false;
    }
}


function criaBoleto(numpedido) {
	url="https://mup.comercioeletronico.com.br/sepsBoleto/000000931/prepara_pagto.asp?merchantid=000000931&orderid="+numpedido;
	winBol=window.open(url, 'vpos', 'toolbar=no, menubar=no, resizable=yes, status=no, scrollbars=yes, top=0, left=0, width=700, height=485');
	winBol.focus();
}  
