/**
 * Remove espaços no começo e no final da string
 *
 * Uso: strVariavelTipoString.trim();
 */
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

/**
 * Gera a Janela para um Boleto!
 */
function gerarBoleto( strDocumento )
{
    var address    = 'loadlib/financeiro/gerarBoleto.php?strDocumento='+strDocumento;
    var windowName = 'boleto'+strDocumento;
    var width      = 800;
    var height     = 580;
    var menuBar    = 'no';
    var location   = 'no';
    var resizeable = 'yes';
    var scrollbars = 'yes';
    var status     = 'no';
    var params     = 'menubar=' + menuBar + ',location=' + location +
	',resizable=' + resizeable + ',scrollbars=' + scrollbars + ',status=' +
	status + ',width=' + width + ',height=' + height + ',top=' + top +
	',left=' + left;
    var top	   = (screen.availHeight/2)-(height/2);
    var left	   = (screen.availWidth/2)-(width/2);

    window.open( address, windowName, params);
}

/**
 * Confirma deletar um Boleto!
 */
function confirmaDeletarBoleto( strDocumento )
{
	
	var r= confirm('Deletar boleto: '+(strDocumento)+' ?');
	
	if (r==true){
		 document.location.href = 'transacoesDeletaBoleto.php?strDocumento=' + (strDocumento) ;
	  
	}else{
		alert('Operação cancelada!');
	}
}

/**
 * Envia um formulário através do seu Id
 */
function submitForm(idForm, fncValida)
{
    var validaForm = eval(fncValida);
    var booRetorno = false;

    // Testa se a validação do form foi bem sucedida
    if (validaForm)
    {
        // Testa se existe o form para o submit
        if ( $(idForm) != 'undefined' )
        {
            $(idForm).submit();

            booRetorno = true;
        }
    }

    return booRetorno;
}

/**
 * Exibe uma janela modal de confirmação para o usuário
 */
function showAlertModal(strDivName, strTitle, strMsg)
{
    if (typeof(strDivName) !== 'undefined') {
        Windows.close('winAlert');
    
        var win = new Window('winAlert',
        {
            className: "spread",
            title: strTitle,
            width:290,
            height:80,
            resizable: false,
            draggable: false,
            closable: true,
            minimizable: false,
            maximizable: false,
            destroyOnClose: true
        });

        if ($(strDivName)) {
            $(strDivName).innerHTML = strMsg;

            win.getContent().innerHTML= $(strDivName).innerHTML;
            win.showCenter(true);
        }
    }
}

/**
 * Altera a imagem antiBot
 */
function getNewBotImage()
{
    var data = new Date();

    $('imgNoBot').src = 'antiBotImage.php?new=' + data.getTime();
}

/**
 * Testa a força de uma senha e altera a imagem de acordo
 */
function testPasswordStatus(passwd, idImg)
{
    var intScore   = 0
    var strVerdict = "1"

    if (passwd.length<5)
        intScore = (intScore+3)
    else if (passwd.length>4 && passwd.length<8)
        intScore = (intScore+6)
    else if (passwd.length>7 && passwd.length<16)
        intScore = (intScore+12)
    else if (passwd.length>15) intScore =
        (intScore+18)

    if ( passwd.match(/[a-z]/) )
        intScore = (intScore+1)
    if ( passwd.match(/[A-Z]/) )
        intScore = (intScore+5)
    if ( passwd.match(/\d+/) )
        intScore = (intScore+5)
    if ( passwd.match(/(.*[0-9].*[0-9].*[0-9])/) )
        intScore = (intScore+5)
    if ( passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/) )
        intScore = (intScore+5)
    if ( passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/) )
        intScore = (intScore+5)
    if ( passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) )
        intScore = (intScore+2)
    if ( passwd.match(/(\d.*\D)|(\D.*\d)/) )
        intScore = (intScore+2)
    if ( passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/) )
        intScore = (intScore+2)
    if ( intScore < 25)
        strVerdict = "2"
    else if ( intScore > 24 && intScore < 30 )
        strVerdict = "3"
    else
        strVerdict = "4"
    if ( !passwd )
        strVerdict = "1";

    $(idImg).src = '/img/ico_pwd_' + strVerdict + '.gif';
}

/**
 * Compara se duas senhas são iguais e retorna a mensagem de acordo com o resultado
 */
function comparaSenhas(idPasswd1, idPasswd2, idDisplay)
{
    var strSenha1 = $F(idPasswd1);
    var strSenha2 = $F(idPasswd2);

    if (strSenha1 != strSenha2)
    {
        $(idDisplay).show().update('Senhas não conferem');

        return false;
    }
    else
    {
        $(idDisplay).show().update('Senhas OK');

        return true;
    }
}

function validaAddGrupo()
{
    if($('txtGrupo').value == '')
    {
        status('NOME DO GRUPO: preenchimento obrigatório');
        $('txtGrupo').focus();
        return false;
    }

    return true;
}

/**
 * Valida os dados do cadastro de um novo contato para o usuário
 */
function validaAddContato()
{
    /**
     * @author matheus
     *
     * Adicionando para caso que seja possível a inserção de contatos que possuam somente email
     */
    if ( $('txtTelefone').value == '' && $('txtEmail').value == '')
    {
        status('O preenchimento de um TELEFONE ou EMAIL VÁLIDO é obrigatório');
        $('txtTelefone').focus();

        return false;
    }

    var boxes = $$('input');
    var selecionar = false;

    for(var i=0; i<boxes.length; i++)
    {
        if(boxes[i].type == 'checkbox')
        {
            if(boxes[i].id.substr(0,8) == 'chkGrupo')
            {
                if(boxes[i].checked == true)
                {
                    selecionar = true;
                    break;
                }
            }
        }
    }

    if(selecionar == false)
    {
        status('GRUPOS: você deve selecionar ao menos 1 grupo para o contato');

        return false;
    }

    return true;
}

/**
 * Valida os campos do formulár de fale conosco
 */
function validaFaleConosco()
{
    if ($('txtNome').value == '')
    {
        status('NOME: preenchimento obrigatório !');
        $('txtNome').focus();
        return false;
    }

    if($('txtCelular').value == '' && $('txtEmail').value == '')
    {
        status('O preenchimento de um TELEFONE ou EMAIL VÁLIDO é obrigatório!');
        $('txtCelular').focus();
        return false;
    }

    if($('txtTelefone').value == '' && $('txtEmail').value == '')
    {
        status('O preenchimento de um TELEFONE ou EMAIL VÁLIDO é obrigatório!');
        $('txtTelefone').focus();
        return false;
    }

    if($('txtEmail').value.indexOf('@') == -1)
    {
        status('E-MAIL: inválido !');
        $('txtEmail').focus();
        return false;
    }

    if($('txtRazaoSocial') != 'undefined' && $('txtRazaoSocial') == '')
    {
        status('RAZÃO SOCIAL: preenchimento obrigatório !');
        $('txtRazaoSocial').focus();
        return false;
    }

    if($('lstTipoMensagem').value == '')
    {
        status('TIPO DA MENSAGEM: obrigatório selecionar uma opção !');
        $('lstTipoMensagem').focus();
        return false;
    }

    if($('txtTitulo').value == '')
    {
        status('TÍTULO: preenchimento obrigatório !');
        $('txtTitulo').focus();
        return false;
    }

    if($('txtMensagem').value == '')
    {
        status('MENSAGEM: preenchimento obrigatório !');
        $('txtMensagem').focus();
        return false;
    }

    return true;
}

/**
 * Valida o login do usuário
 */
function validaLogin()
{
    if($('txtLogin').value == '')
    {
        status('LOGIN: preenchimento obrigatório !');
        $('txtLogin').focus();
        return false;
    }

    if($('txtSenha').value == '')
    {
        status('SENHA: preenchimento obrigatório !');
        $('txtSenha').focus();
        return false;
    }

    return true;
}

/**
 * Valida os campos de esqueci senha do usuário
 */
function validaEsqueciSenha()
{
    if($('lstDddCelular').value == '')
    {
        status('DDD CELULAR: seleção obrigatória !');
        $('lstDddCelular').focus();
        return false;
    }

    if($('txtCelular').value == '')
    {
        status('CELULAR: preenchimento obrigatório !');
        $('txtCelular').focus();
        return false;
    }

    if($('txtNoBot').value == '')
    {
        status('TEXTO DA IMAGEM: preenchimento obrigatório !');
        $('txtNoBot').focus();
        return false;
    }

    return true;
}

/**
 * Valida os campos de esqueci senha do usuário
 */
function validaTrocaSenha()
{
    if($('txtSenha').value == '')
    {
        status('SENHA: preenchimento obrigatório !');
        $('txtSenha').focus();
        return false;
    }

    if($('txtVerificaSenha').value == '')
    {
        status('VERIFICAÇÃO DA SENHA: preenchimento obrigatório !');
        $('txtVerificaSenha').focus();
        return false;
    }

    if($('txtNoBot').value == '')
    {
        status('TEXTO DA IMAGEM: preenchimento obrigatório !');
        $('txtNoBot').focus();
        return false;
    }

    return true;
}

/**
 * Valida os campos de esqueci senha do usuário
 */
function validaTrocaSenhaLogado()
{
    if($('txtSenhaAntiga').value == '')
    {
        status('SENHA ANTIGA: preenchimento obrigatório !');
        $('txtSenhaAntiga').focus();
        return false;
    }

    if($('txtSenha').value == '')
    {
        status('SENHA: preenchimento obrigatório !');
        $('txtSenha').focus();
        return false;
    }

    if($('txtVerificaSenha').value == '')
    {
        status('VERIFICAÇÃO DA SENHA: preenchimento obrigatório !');
        $('txtVerificaSenha').focus();
        return false;
    }

    if($('txtNoBot').value == '')
    {
        status('TEXTO DA IMAGEM: preenchimento obrigatório !');
        $('txtNoBot').focus();
        return false;
    }

    return true;
}

/**
 * Valida o cadastro do usuário
 */
function validaCadastro()
{
    if($('txtLogin').value == '')
    {
        status('LOGIN: preenchimento obrigatório !');
        $('txtLogin').focus();
        return false;
    }

    if($('txtSenha').value == '')
    {
        status('SENHA: preenchimento obrigatório !');
        $('txtSenha').focus();
        return false;
    }

    if($('txtVerificaSenha').value == '')
    {
        status('VERIFICAÇÃO DE SENHA: preenchimento obrigatório !');
        $('txtVerificaSenha').focus();
        return false;
    }

    if($('txtSenha').value != $('txtVerificaSenha').value)
    {
        status('AS DUAS SENHAS NÃO CONFEREM !');
        $('txtVerificaSenha').value = '';
        $('txtVerificaSenha').focus();
        return false;
    }

    // Valida o tipo de pessoa
    if($('rbtPessoaFisica').checked == false)
    {
        if($('txtRazaoSocial').value == '')
        {
            status('RAZÃO SOCIAL: preenchimento obrigatório !');
            $('txtRazaoSocial').focus();
            return false;
        }
        if($('txtCnpj').value == '')
        {
            status('CNPJ: preenchimento obrigatório !');
            $('txtCnpj').focus();
            return false;
        }
        if($('chkIsentoIE').checked == false)
        {
            if($('txtIe').value == '')
            {
                status('IE: preenchimento obrigatório !');
                $('txtIe').focus();
                return false;
            }
        }
        else
        {
            $('txtIe').value = '';
        }

        if($('txtNomeResp').value == '')
        {
            status('NOME RESPONSÁVEL: preenchimento obrigatório !');
            $('txtNomeResp').focus();
            return false;
        }

        if($('txtSobrenomeResp').value == '')
        {
            status('SOBRENOME RESPONSÁVEL: preenchimento obrigatório !');
            $('txtSobrenomeResp').focus();
            return false;
        }

        if($('txtCpfResp').value == '')
        {
            status('CPF RESPONSÁVEL: preenchimento obrigatório !');
            $('txtCpfResp').focus();
            return false;
        }

        if($('txtRgResp').value == '')
        {
            status('RG RESPONSÁVEL: preenchimento obrigatório !');
            $('txtRgResp').focus();
            return false;
        }

        if($('dat_niver_resp_Day').value == '' || $('dat_niver_resp_Month').value == '' || $('dat_niver_resp_Year').value == '')
        {
            status('DATA NASCIMENTO RESPONSÁVEL: preenchimento obrigatório !');
            $('dat_niver_Day').focus();
            return false;
        }
    }
    else
    {
        if($('txtNome').value == '')
        {
            status('NOME: preenchimento obrigatório !');
            $('txtNome').focus();
            return false;
        }

        if($('txtSobrenome').value == '')
        {
            status('SOBRENOME: preenchimento obrigatório !');
            $('txtSobrenome').focus();
            return false;
        }

        if($('txtCpf').value == '')
        {
            status('CPF: preenchimento obrigatório !');
            $('txtCpf').focus();
            return false;
        }

        if($('txtRg').value == '')
        {
            status('RG: preenchimento obrigatório !');
            $('txtRg').focus();
            return false;
        }

        if($('dat_niver_Day').value == '' || $('dat_niver_Month').value == '' || $('dat_niver_Year').value == '')
        {
            status('DATA NASCIMENTO: preenchimento obrigatório !');
            $('dat_niver_Day').focus();
            return false;
        }

    }

    if($('txtCep').value == '')
    {
        status('CEP: preenchimento obrigatório !');
        $('txtCep').focus();
        return false;
    }

    if($('txtEmail').value == '')
    {
        status('E-MAIL: preenchimento obrigatório !');
        $('txtEmail').focus();
        return false;
    }

    if($('txtCelular').value == '')
    {
        status('CELULAR: preenchimento obrigatório !');
        $('txtCelular').focus();
        return false;
    }

    if($('txtNoBot').value == '')
    {
        status('TEXTO DA IMAGEM: preenchimento obrigatório !');
        $('txtNoBot').focus();
        return false;
    }

    return true;
}

/**
 * Valida a atualização do cadastro do usuário
 */
function validaUpdateCadastro()
{
    if ($('rbtPessoaFisica').checked == false)
    {
        if ($('txtRazaoSocial').value == '')
        {
            status('RAZÃO SOCIAL: preenchimento obrigatório !');
            $('txtRazaoSocial').focus();
            return false;
        }

        if ($('txtCnpj').value == '')
        {
            status('CNPJ: preenchimento obrigatório !');
            $('txtCnpj').focus();
            return false;
        }

        if ($('chkIsentoIE').checked == false)
        {
            if($('txtIE').value == '')
            {
                status('IE: preenchimento obrigatório !');
                $('txtIE').focus();
                return false;
            }
        }
        else
        {
            $('txtIE').value = ''
        }
    }

    if ($('txtNome').value == '')
    {
        status('NOME: preenchimento obrigatório !');
        $('txtNome').focus();
        return false;
    }

    if($('txtSobrenome').value == '')
    {
        status('SOBRENOME: preenchimento obrigatório !');
        $('txtSobrenome').focus();
        return false;
    }

    if($('txtCpf').value == '')
    {
        status('CPF: preenchimento obrigatório !');
        $('txtCpf').focus();
        return false;
    }

    if($('txtRg').value == '')
    {
        status('RG: preenchimento obrigatório !');
        $('txtRg').focus();
        return false;
    }

    if($('strNascimento').value == '')
    {
        status('DATA NASCIMENTO: preenchimento obrigatório !');
        $('strNascimento').focus();
        return false;
    }

    if($('txtEmail').value == '')
    {
        status('E-MAIL: preenchimento obrigatório !');
        $('txtEmail').focus();
        return false;
    }

    if($('txtCelular').value == '')
    {
        status('CELULAR: preenchimento obrigatório !');
        $('txtCelular').focus();
        return false;
    }

    if($('txtNoBot').value == '')
    {
        status('TEXTO DA IMAGEM: preenchimento obrigatório !');
        $('txtNoBot').focus();
        return false;
    }

    return true;
}

/**
 * Valida a resposta de um chamado enviado pelo usuário
 */
function validaRespostaChamado()
{
    if($('txtMensagem').value == '')
    {
        status('MENSAGEM: preenchimento obrigatório !');
        $('txtMensagem').focus();
        return false;
    }

    return true;
}

/**
 * Valida a abertura de um novo ticket de suporte
 */
function validaAberturaChamado()
{
    if($('txtNome').value == '')
    {
        status('NOME: preenchimento obrigatório !');
        $('txtNome').focus();
        return false;
    }

    if($('txtEmail').value == '')
    {
        status('E-MAIL: preenchimento obrigatório !');
        $('txtEmail').focus();
        return false;
    }

    if($('txtTelefone').value == '')
    {
        status('TELEFONE: preenchimento obrigatório !');
        $('txtTelefone').focus();
        return false;
    }

    if($('lstArea').value == '')
    {
        status('ÁREA: obrigatório selecionar ao menos uma opção !');
        $('lstArea').focus();
        return false;
    }

    if($('txtTitulo').value == '')
    {
        status('TÍTULO: preenchimento obrigatório !');
        $('txtTitulo').focus();
        return false;
    }

    if($('txtMensagem').value == '')
    {
        status('MENSAGEM: preenchimento obrigatório !');
        $('txtMensagem').focus();
        return false;
    }

    return true;
}

/**
 * Testa o evento KeyCode de acordo com o tipo de browser e evento do campo
 */
function testaKeyCode(evnt)
{
    var booRetorno = null;

    if (window.event)
        booRetorno = window.event.keyCode;
    else if (evnt)
        booRetorno = evnt.which;

    return booRetorno;
}

/**
 * Máscara para formatação de datas
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtData(obj, e)
{
    // Testa se a entrada é apenas número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);
        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
            if (myVal.length > 2 && !myVal.match(/\//))
                myVal = '';
            else
            {
                // Obtém o key code
                keyCode = testaKeyCode(e);

                if ((keyCode < 48 || keyCode > 57) && (keyCode < 96 || keyCode > 105))
                    myVal = myVal.substr(0, (myVal.length - 1));

                if (myVal.length == 2 || myVal.length == 5)
                    myVal += '/';

            }
            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * M�scara de formata��o de datas
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtHora(obj, e)
{
    // Testa se a entrada é apenas número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);
        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
            if (myVal.length > 2 && !myVal.match(/:/))
                myVal = '';
            else
            {
                // Obtém o key code
                keyCode = testaKeyCode(e);

                if ((keyCode < 48 || keyCode > 57) && (keyCode < 96 || keyCode > 105))
                    myVal = myVal.substr(0, (myVal.length - 1));

                //if (myVal.length == 2 || myVal.length == 5)
                if (myVal.length == 2)
                    myVal += ':';

            }
            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * Máscara para formatação de datas
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtCep(obj, e)
{
    // Testa se a entrada é um número
    if(apenasNumeros(e))
    {
        var myVal = obj.value;
        if (myVal.length > 5 && !myVal.match(/\-/))
            myVal = '';

        var keyCode = testaKeyCode(e);
        if(!specialKeys(keyCode))
        {
            if ((keyCode < 48 || keyCode > 57) && (keyCode < 96 || keyCode > 105))
                myVal = myVal.substr(0, (myVal.length - 1));

            if (myVal.length == 5)
                myVal += '-';

            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * Máscara para formatação de CPF
 *
 * obj => HTML Object do campo a ser testado (this)
 * e => Evento do teclado
 */
function fmtCpf(obj, e)
{
    // Testa se a entrada é um número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);

        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
	    
            if ( ((myVal.length > 3 || myVal.length > 7 || myVal.length > 10) && !myVal.match(/\./)) ||  (myVal.length > 14 && !myVal.match(/\-/)) )
                myVal = '';

            if (myVal.length == 3 || myVal.length == 7)
                myVal += '.';

            if(myVal.length == 11)
                myVal += '-';

            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * Máscara para formatação de CNPJ
 *
 * obj => HTML Object do campo a ser testado (this)
 * e => Evento do teclado
 */
function fmtCnpj(obj, e)
{
    // Testa se a entrada é um número
    if(apenasNumeros(e))
    {
        keyCode = testaKeyCode(e);

        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
            if ( ((myVal.length > 2 || myVal.length > 6) && !myVal.match(/\./)) ||  (myVal.length > 10 && !myVal.match(/\//)) ||  (myVal.length > 15 && !myVal.match(/\-/)) )
                myVal = '';

            if (myVal.length == 2 || myVal.length == 6)
                myVal += '.';

            if(myVal.length == 10)
                myVal += '/';

            if(myVal.length == 15)
                myVal += '-';

            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * Máscara para formatação de telefones e celulares
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtTelefone(obj, e)
{
    // Testa se a entrada é um número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);

        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
            if (myVal.length > 9 && !myVal.match(/\-/))
                myVal = '';

            if (myVal.length == 2)
            {
                var areaCode = myVal;
                myVal = '(' + areaCode +') ';
            }

            if (myVal.length == 9)
            {
                var phoneNumber = myVal;
                myVal = phoneNumber +'-';
            }
            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * Máscara para formatação de telefones e celulares
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtTelefoneSemDdd(obj, e)
{
    // Testa se a entrada é um número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);

        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;
            if (myVal.length > 9 && !myVal.match(/\-/))
                myVal = '';

            if (myVal.length == 4)
            {
                var phoneNumber = myVal;
                myVal = phoneNumber +'-';
            }
            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}

/**
 * M�scara de formata��o de valores monet�rios
 *
 * obj => HTML Object do campo a ser testado (this)
 */
function fmtValor(obj, e)
{
    // Testa se a entrada é apenas número
    if(apenasNumeros(e))
    {
        var keyCode = testaKeyCode(e);

        if(!specialKeys(keyCode))
        {
            var myVal = obj.value;

            if (myVal.length > 3 && !myVal.match(/,/))
            {
                myVal = '';
            }
            else
            {
                // Obtém o key code
                keyCode = testaKeyCode(e);

                if ((keyCode < 48 || keyCode > 57) && (keyCode < 96 || keyCode > 105))
                    myVal = myVal.substr(0, (myVal.length - 1));

                while ( myVal.indexOf( ',' ) != -1 )
                {
                    myVal = myVal.replace( ',', '');
                }

                if (myVal.length > 2)
                    myVal = myVal.substr(0,myVal.length-1) + ',' + myVal.substr(myVal.length-1);

            }

            obj.value = myVal;
        }
        return true;
    }
    else
        return false;
}


/** Exibe o KeyCode da tecla pressionada
 *
 * obj => Id do textfield onde será digitado o caracter
 * e => evento da tecla
 * idCharDisplay => Id da Div/Td/Th onde aparecerá o CARACTER pressionado
  * idKeyCodeDisplay => Id da Div/Td/Th onde aparecerá o KEY CODE pressionado
 */
function showKeyCode(obj, e, idCharDisplay, idKeyCodeDisplay)
{
    var str = '';
    // Obtém o key code
    var keyCode = testaKeyCode(e);

    $(idCharDisplay).innerHTML = obj.value;
    $(idKeyCodeDisplay).innerHTML = keyCode;

    obj.value = '';
}

/**
 * Função para restringir a digitação de caracteres númericos no campo do código
 */
function apenasNumeros(evnt)
{
    var keyCode = testaKeyCode(evnt);

    // Testa se é uma tecla de controle
    if(specialKeys(keyCode))
        return true;

    // Testa se é um número
    if( keyCode < 48 || keyCode > 57 )
        return false;
    else
        return true;
}

/**
 * Testa se a tecla pressionada é uma tecla especial
 */
function specialKeys(keyCode)
{
    var intKeyCode = parseInt(keyCode);

    // 8->Backspace | 9->Tab | 13->Enter | 13->Shift | 15-19 -> Setas do teclado | 27->Esc | 127->Delete
    if (intKeyCode == 0  || intKeyCode == 8  || intKeyCode == 9  ||
        intKeyCode == 13 || intKeyCode == 15 || intKeyCode == 16 ||
        intKeyCode == 17 || intKeyCode == 18 || intKeyCode == 19 ||
        intKeyCode == 127)
        {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Função para validar uma data
 */
function validaData(obj)
{
    var dia = parseInt(obj.value.substr(0,2));
    var mes = parseInt(obj.value.substr(3,2));
    var ano = parseInt(obj.value.substr(6,4));
    var data = new Date();
    var anoAtual = data.getFullYear();

    if(dia < 1 || dia > 31)
    {
        status('Data inválida');
        obj.value='';
        obj.focus();
        return false;
    }

    if(mes < 1 || mes > 12)
    {
        status('Data inválida');
        obj.value='';
        obj.focus();
        return false;
    }

    if(anoAtual - ano > 90)// Idade máxima de noventa anos
    {
        status('Data inválida');
        obj.value='';
        obj.focus();
        return false;
    }

    if(mes == 2)
    {
        if(ano%4 == 0 && dia > 29)
        {
            status('Data inválida');
            obj.value='';
            obj.focus();
            return false;
        }
        else if (ano%4 != 0 && dia > 28)
        {
            status('Data inválida');
            obj.value='';
            obj.focus();
            return false;
        }
    }
    else if(mes == 4 || mes == 6 || mes == 9 || mes == 11)
    {
        if(dia > 30)
        {
            status('Data inválida');
            obj.value='';
            obj.focus();
            return false;
        }
    }

    return true;
}

/**
 * Funções para a paginação
 */
function trocaPaginacao( strLink )
{
    document.location.href = strLink;
}

/**
 * Funções para a Busca Simples e Avançada
 */
function mostraBuscaSimples()
{
    $( 'buscaSimples' ).style.display  = '';
    $( 'buscaAvancada' ).style.display = 'none';
}

function mostraBuscaAvancada()
{
    $( 'buscaSimples' ).style.display  = 'none';
    $( 'buscaAvancada' ).style.display = '';
}

function limparBuscaSimples()
{
    $( 'strBuscaSimples' ).value = '';
    $( 'formBuscaSimples' ).submit();
}

function limparBuscaAvancada()
{
    if (!document.getElementsByTagName){
        return;
    }

    var allfields = $( 'formBuscaAvancada' ).getElementsByTagName( 'input' );

    for (var i=0; i<allfields.length; i++)
    {
        if ( allfields[i].name != "strBuscaSimples" && allfields[i].name != "strBuscaAvancada" && allfields[i].type == "text" && allfields[i].name.substring(0,8) == "strBusca" )
        {
            allfields[i].value = '';
        }
    }
    $( 'formBuscaAvancada' ).submit();
}

/**
 * Chama a url para troca de usu�rio
 */
function trocaUsuario( intIdUsuario )
{
    if( intIdUsuario != '' )
    {
        document.location.href = 'trocaUsuario.php?intIdUsuario=' + intIdUsuario ;
    }
}

function insertAtCursor(myField, myValue)
{
    // IE support
    if (document.selection) {
        myField.focus();

        var sel = document.selection.createRange();
        sel.text = myValue;
    }
    // MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue
        + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

function inserirNaMensagem( strConteudo )
{
    insertAtCursor($('strMensagem'), strConteudo);

    contarCaracteresMensagem();
}

var resInterval;
var intContador = 0;

function iniciaRotacaoIcones()
{
	var arrAba = ['mobilemkt', 'emailmkt', 'integracao', 'gateway', 'publicidade', 'bluetooth', 'aplicativo', 'cool'];
	var strAba;
	
	strAba = arrAba[intContador++ % (arrAba.length)];
	if($$('.on').length) {
		$$('.on').first().toggleClassName('on');
	}
	$$('.' + strAba + ' > div').first().toggleClassName('on');
	funPopulaCaseBox(strAba);
	
	resInterval = setInterval(function() {
		
		strAba = arrAba[intContador++ % (arrAba.length)];
		if($$('.on').length) {
			$$('.on').first().toggleClassName('on');
		}
		$$('.' + strAba + ' > div').first().toggleClassName('on');
		funPopulaCaseBox(strAba);
		
	}, 5000);

}

function paraRotacaoIcones()
{
	clearInterval(resInterval);
}

function contarCaracteresMensagem(event)
{
    var strConteudoAtual = null;
    var intCaracteres    = 0;
    
    if (event)
    {
        if ( event.keyCode == 13 )
        {
            Event.stop();
            event.stop();
        }
        else
        {
            var arrCamposEspeciaisString = new Array();
            var arrCamposEspeciaisLength = new Array();

            arrCamposEspeciaisString[0] = '!NOME';
            arrCamposEspeciaisLength[0] = 12;

            arrCamposEspeciaisString[1] = '!DATA_DIA';
            arrCamposEspeciaisLength[1] = 2;

            arrCamposEspeciaisString[2] = '!DATA_MES';
            arrCamposEspeciaisLength[2] = 2;

            arrCamposEspeciaisString[3] = '!DATA_ANO';
            arrCamposEspeciaisLength[3] = 4;

            intCaracteres    = 150;
            strConteudoAtual = $( 'strMensagem' ).value.replace("\n", " ");

            for ( var i = 0; i < arrCamposEspeciaisString.length; i++ )
            {
                while ( strConteudoAtual.indexOf( arrCamposEspeciaisString[ i ] ) != -1 )
                {
                    strConteudoAtual = strConteudoAtual.replace( arrCamposEspeciaisString[ i ], '');
                    intCaracteres    -= arrCamposEspeciaisLength[ i ];
                }
            }

            intCaracteres -= strConteudoAtual.length;

            $('intCaracteresRestantes').innerHTML = intCaracteres;

            if ( $('btnEnviarTorpedo') )
            {
                $('btnEnviarTorpedo').show();
            }

            $('intCaracteresRestantes').style.color = 'black';

            if ( intCaracteres <= 0 )
            {
                $('intCaracteresRestantes').style.color = 'red';

                if ( $('btnEnviarTorpedo') )
                {
                    $('btnEnviarTorpedo').hide();
                }
            }
        }
    }

    return false;
}

function selecionaForma( strForma )
{
    $( 'formaEnviaUnico' ).style.display = ( strForma == 'formaEnviaUnico' ? '' : 'none');
    $( 'formaEnvioHora' ).style.display = ( strForma == 'formaEnvioHora' ? '' : 'none');
    $( 'formaEnvioDia' ).style.display = ( strForma == 'formaEnvioDia' ? '' : 'none');
    document.location.href = 'extratoFinanceiro.php?strMesReferencia=' + strMesReferencia;
}

function agendarEnvio()
{
    $( 'strDataInicio' ).value = '';
    $( 'strHoraInicio' ).value = '';
    $( 'enviarAgora' ).style.display = 'none';
    $( 'agendarEnvio' ).style.display = 'block';
}

function enviarAgora()
{
    $( 'strDataInicio' ).value = '';
    $( 'strHoraInicio' ).value = '';
    $( 'agendarEnvio' ).style.display = 'none';
    $( 'enviarAgora' ).style.display = 'block';
}

function enviarTorpedoExpresso()
{
    var intCelular  = $('intCelular').value;
    var msg         = null;

    if (intCelular != 'Celular' || intCelular == '')
    {
        $('formTorpedoExpresso').request(
        {
            onLoading: function()
            {
                $('statusTorpedoExpresso').update('Enviando...');
            },
            onComplete: function(t)
            {
                var intStatus = t.responseText;

                switch(intStatus)
                {
                    case '0':
                        msg = 'Mensagem enviada com sucesso !';
                        break;
                    case '1':
                        msg = 'ERRO: entradas não seguem a especificação !';
                        break;
                    case '2':
                        msg = 'ERRO: serviço não habilitado !';
                        break;
                    case '3':
                        msg = 'ERRO: número inválido !';
                        break;
                    case '4':
                        msg = 'ERRO: créditos insuficientes !';
                        break;
                    case '5':
                        msg = 'ERRO: falha ao tentar inserir SMS !';
                        break;
                    case '6':
                        msg = 'ERRO: Cód. usuário e/ou Celular inválido(s) !';
                        break;
                    default:
                        msg = 'ERRO: Status não mapeado ou inicializado !';
                }

                $('statusTorpedoExpresso').update('');
                $('btnEnviarTorpedo').blur();

                showAlertModal('divAlert', 'Torpedo expresso', msg);
            }
        });
    }
    else
    {
        msg = 'CELULAR: preenchimento obrigatório';

        showAlertModal('divAlert','Torpedo expresso',msg);
    }
}

// Exibe o modal para envio de torpedo expresso
function showTorpedoExpresso(intTelefone)
{
    if(intTelefone != '')
    {
        var win = new Window('winModalTorpedoExpresso',{
            className: "spread",
            title: "Torpedo Expresso",
            width:165,
            height:310,
            resizable: false,
            draggable: false,
            closable: true,
            minimizable: false,
            maximizable: false,
            destroyOnClose: true
        });

        win.getContent().innerHTML = $("divModalTorpedoExpresso").innerHTML;

        win.showCenter(true);
        
        $('intCelular').value = intTelefone;
    }
}

function trataValores(strValor)
{
    var vr = strValor.toString();
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
    var tam = vr.length;
    
    if (vr.replace(/[^\d.]/g, '').length > 0)
    {
	if ( tam <= 2 )
	{
	    strValor = '0,' + vr;
	}

	if ( (tam > 2) && (tam <= 5) )
	{
	    strValor = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
	}

	if ( (tam >= 6) && (tam <= 8) )
	{
	    strValor  = vr.substr( 0, tam - 5 ) + '.';
	    strValor += vr.substr( tam - 5, 3 ) + ',';
	    strValor += vr.substr( tam - 2, tam );
	}

	if ( (tam >= 9) && (tam <= 11) )
	{
	    strValor  = vr.substr( 0, tam - 8 ) + '.';
	    strValor += vr.substr( tam - 8, 3 ) + '.';
	    strValor += vr.substr( tam - 5, 3 ) + ',';
	    strValor += vr.substr( tam - 2, tam );
	}

	if ( (tam >= 12) && (tam <= 14) )
	{
	    strValor  = vr.substr( 0, tam - 11 ) + '.';
	    strValor += vr.substr( tam - 11, 3 ) + '.';
	    strValor += vr.substr( tam - 8, 3 ) + '.';
	    strValor += vr.substr( tam - 5, 3 ) + ',';
	    strValor += vr.substr( tam - 2, tam ) ;
	}

	if ( (tam >= 15) && (tam <= 17) )
	{
	    strValor  = vr.substr( 0, tam - 14 ) + '.';
	    strValor += vr.substr( tam - 14, 3 ) + '.';
	    strValor += vr.substr( tam - 11, 3 ) + '.';
	    strValor += vr.substr( tam - 8, 3 ) + '.';
	    strValor += vr.substr( tam - 5, 3 ) + ',';
	    strValor += vr.substr( tam - 2, tam ) ;
	}
    }

    return strValor;
}

function formataValor(campo, tammax, teclapres)
{
    // Testa se a entrada é apenas número
    if(apenasNumeros(teclapres))
    {
        var tecla = window.event ? teclapres.keyCode : teclapres.which;
        var vr = $F(campo);
	    vr = vr.replace( "/", "" );
	    vr = vr.replace( "/", "" );
	    vr = vr.replace( ",", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
        var tam = vr.length;

        if (tam < tammax && tecla != 8){
            tam = vr.length + 1 ;
        }

        if (tecla == 8 ){
            tam = tam - 1 ;
        }

        if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
        {
            if ( tam <= 2 )
            {
                $(campo).value = vr ;
            }

            if ( (tam > 2) && (tam <= 5) )
            {
                $(campo).value = vr.substr( 0, tam - 2 ) + ',' +
		    vr.substr( tam - 2, tam ) ;
            }

            if ( (tam >= 6) && (tam <= 8) )
            {
                $(campo).value = vr.substr( 0, tam - 5 ) + '.' +
		    vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
            }

            if ( (tam >= 9) && (tam <= 11) )
            {
                $(campo).value = vr.substr( 0, tam - 8 ) + '.' +
		    vr.substr( tam - 8, 3 ) + '.' +
		    vr.substr( tam - 5, 3 ) + ',' +
		    vr.substr( tam - 2, tam ) ;
            }
	    
            if ( (tam >= 12) && (tam <= 14) )
            {
                $(campo).value = vr.substr( 0, tam - 11 ) + '.' + 
		    vr.substr( tam - 11, 3 ) + '.' +
		    vr.substr( tam - 8, 3 ) + '.' +
		    vr.substr( tam - 5, 3 ) + ',' +
		    vr.substr( tam - 2, tam ) ;
            }

            if ( (tam >= 15) && (tam <= 17) )
            {
                $(campo).value = vr.substr( 0, tam - 14 ) + '.' +
		    vr.substr( tam - 14, 3 ) + '.' +
		    vr.substr( tam - 11, 3 ) + '.' +
		    vr.substr( tam - 8, 3 ) + '.' +
		    vr.substr( tam - 5, 3 ) + ',' +
		    vr.substr( tam - 2, tam ) ;
            }
        }

        return true;
    }
    else
    {
        return false;
    }
}

function formataValorQuatroDecimais(campo, teclapres)
{
    // Testa se a entrada é apenas número
    if(apenasNumeros(teclapres))
    {
        var tecla  = window.event ? teclapres.keyCode : teclapres.which;
        var vr = $F(campo);
	    vr = vr.replace( "/", "" );
	    vr = vr.replace( "/", "" );
	    vr = vr.replace( ",", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
	    vr = vr.replace( ".", "" );
        var tam = vr.length;

        if (tam < 6)
        {
            tam = tam + 1;
        }

        if (tecla == 8 ){
            tam = tam - 1 ;
        }

        if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
        {
            if (tam <= 4)
            {
                $(campo).value = vr;
            }

            if ((tam > 4) && (tam <= 7))
            {
                $(campo).value = vr.substr(0, tam - 4) + ',' +
		    vr.substr(tam - 4, 4);
            }
        }

        return true;
    }
    else
    {
        return false;
    }
}


function trataValoresQuatroDecimais(strValor)
{
    var vr = strValor.toString();
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
    var tam = vr.length;

    if (vr.replace(/[^\d.]/g, '').length > 0)
    {
	if (tam == 1)
	{
	    strValor = '0,' + vr + '000';
	}

	if ((tam <= 2) && (tam < 4))
	{
	    strValor = '0,' + vr + '00';
	}

        if ((tam > 2) && (tam < 4))
        {
            strValor = '0,' + vr + '0';
        }

        if ((tam > 2) && (tam == 4))
        {
            strValor = '0,' + vr;
        }

        if (tam > 4)
        {
            strValor = vr.substr(0, tam - 4) + ',' + vr.substr(tam - 4, 4);
        }
    }

    return strValor;
}

/**
 * Valida se a tecla pressionada num determinado campo foi a tecla ENTER
 *
 */
function validaEnter (objEvento)
{
    var tmp = null;

    if (window.event)
        tmp = (window.event.keyCode);
    else if (objEvento)
        tmp = objEvento.which;

    if ( tmp == 13 )
    {
        return true;
    }
    else
    {
        return false;
    }
}

// função para checar se um valor existe em uma array
function in_array(value, arr)
{
    var key;

    for (key in arr)
    {
        if (arr[key] === value)
        {
            return value;
        }
    }

    return null; //false
}

function status(strMensagem)
{
    var win = new Window('status',{
        className: "spread",
        title: "Status",
        width:300,
        height:50,
        resizable: false,
        draggable: false,
        closable: true,
        minimizable: false,
        maximizable: false,
        destroyOnClose: true
    });

    win.getContent().innerHTML = strMensagem;
    win.showCenter(true);
}

// Abre a janela de recuperação de senha
function esqueciSenhaModal()
{
    var win = new Window('winEsqueciSenha',{
        className: "spread",
        title: "Esqueci minha senha",
        width:425,
        height:300,
        resizable: false,
        draggable: false,
        closable: true,
        minimizable: false,
        maximizable: false,
        destroyOnClose: true
    });

    win.getContent().innerHTML = $("divEsqueciSenha").innerHTML;
    win.showCenter(true);
}

function updateChart( id, strVariavel, strValor )
{
    eval ( strVariavel + '_' + id + ' = ' + '\'' + strValor + '\'' );

    gerarRelatorio( id, false );
}

function gerarRelatorio( id, booFirst )
{
    var i       = 0;
    var url     = 'loadlib/relatorio/getRelatorio.php?';
    var arrVars = new Array();
    var strNomeRelatorio = eval('strNomeRelatorio_'+id);
    var strCategoria1    = eval('strCategoria1_'+id);
    var strCategoria2    = eval('strCategoria2_'+id);
    var strTipo          = eval('strTipo_'+id);
    var strMascara       = eval('strMascara_'+id);
    var strFiltro        = eval('strFiltro_'+id);
    var booUseCache      = eval('booUseCache_'+id);

    if ( strNomeRelatorio.length > 0 )
    {
        arrVars[i] = 'strNomeRelatorio=' +  strNomeRelatorio;
        i++;
    }

    if ( strCategoria1.length > 0 )
    {
        arrVars[i] = 'strCategoria1=' +  strCategoria1;
        i++;
    }

    if ( strCategoria2.length > 0 )
    {
        arrVars[i] = 'strCategoria2=' +  strCategoria2;
        i++;
    }

    if ( strTipo.length > 0 )
    {
        arrVars[i] = 'strTipo=' +  strTipo;
        i++;
    }

    if ( strMascara.length > 0 )
    {
        arrVars[i] = 'strMascara=' +  strMascara;
        i++;
    }

    if ( strFiltro.length > 0 )
    {
        arrVars[i] = 'strFiltro=' +  strFiltro;
        i++;
    }

    if ( booUseCache.length > 0 )
    {
        arrVars[i] = 'booUseCache=' +  booUseCache;
        i++;
    }

    // Monta a url
    url = url + arrVars.join( '&' );

    // Efetua requisi��o para montagem do gr�fico
    new Ajax.Request
    (
        url,
        {
            method: 'get',
            onComplete: function(transport)
            {
                var arrResposta = transport.responseText.split( '$$' );

                gerarGraficoFlash( "grafico_"+id, "ChartFlash"+id, getSwfName( strTipo ), eval('intWidth_'+id), eval('intHeight_'+id), arrResposta[1] );

                if(booFirst)
                {
                    populateCombo( "categoria1_"+id, arrResposta[3].split( ',' ) );
                    populateCombo( "categoria2_"+id, arrResposta[3].split( ',' ) );
                }
            }
        }
        );
}

function getSwfName( strTipo )
{
    switch( strTipo )
    {
        case 'pizza':
            return 'Pie3D';
            break;
        case 'barrasimples':
            return 'Column3D';
            break;
        default:
            return 'MSColumn3D';
            break;
    }
}

function gerarGraficoFlash( idHtml, idGraph, swfName, width, height, xml )
{
    var chart = new FusionCharts("/swf/" + swfName + ".swf", idGraph, width, height, "0", "0");
    chart.setDataXML( xml );
    chart.render( idHtml );
}

function populateCombo( idHtml, arrFiltros )
{
    $( idHtml ).options[0]         = new Option( "Selecione" );
    $( idHtml ).options[0].value = "";

    for ( var i = 1; i < arrFiltros.length ; i++ )
    {
        adicionaElementoSelect(arrFiltros[i], arrFiltros[i], idHtml);
    }

    $( idHtml ).options[0].selected = true;
}

function adicionaElementoSelect(texto,valor,objeto)
{
    // select
    var selectsObj = $(objeto);

    // pega a quantidade de op��es do select
    var tam = selectsObj.length;

    // adiciona a op��o
    selectsObj.options[tam] = new Option(texto);
    selectsObj.options[tam].value = valor;
}

function showHideGraph(strGraphName, strModo)
{
    if(strModo == 'graph')
    {
        document.getElementById('graph'+strGraphName).style.display = 'block';
        document.getElementById('table'+strGraphName).style.display = 'none';
    }
    else
    {
        document.getElementById('graph'+strGraphName).style.display = 'none';
        document.getElementById('table'+strGraphName).style.display = 'block';
    }

    return false;
}

function selecionaMesReferencia( strMesReferencia )
{
    document.location.href = 'extratoFinanceiro.php?strMesReferencia=' + strMesReferencia;
}

function atualizaStatusServico(intIdMensagem, strStatus)
{
    new Ajax.Request(
        'loadlib/servico/update.php?intIdMensagem=' + intIdMensagem + '&strStatus=' + strStatus,
        {
            method: 'get',
            loading: $('statusMensagensRetorno').update('<div class="boxMsg">Aguarde...</div><br />'),
            onComplete: function(t)
            {
                $('statusMensagensRetorno').update('');

                var strMsg = null;

                switch(t.responseText)
                {
                    case '0':
                        window.location.href = window.location.href;
                        break;

                    case '3':
                        strMsg = 'ERRO: o serviço não pode ser trocado para o mesmo status !';
                        break;

                    default:
                        strMsg = 'ERRO: Status não mapeado ou não inicializado !';
                        break;
                }

                showAlertModal('divAlert','Exclusão de tutorial', strMsg);
            }
        });

    return false;
}

/**
 * Recupera os parâmetros passados via URL (GET)
 */
var qsParm = new Array();

function qs()
{
    var query = window.location.search.substring(1);
    var parms = query.split('&');

    for (var i=0; i<parms.length; i++)
    {
        var pos = parms[i].indexOf('=');

        if (pos > 0)
        {
            var key = parms[i].substring(0,pos);
            var val = parms[i].substring(pos+1);

            qsParm[key] = val;
        }
    }
}

function selecionaTipoPessoa()
{
    if ($('rbtPessoaFisica').checked == true)
    {
	$('pessoaJuridica').hide();
    }
    else
    {
	$('pessoaJuridica').show();
    }
}

/**
 * Preenche os dados do endereço através do cep informado pelo usuário
 */
function buscaEnderecoPeloCep()
{
    var intCep = $F('txtCep').replace('-', '');

    if (intCep > 0)
    {
	new Ajax.Request(
	'/loadlib/usuario/buscaEnderecoPeloCep.php?intCep='+intCep,
	{
	    method: 'get',
	    onLoading: function()
	    {
		$('txtRua').value = 'aguarde...';
	    },
	    onComplete: function(t)
	    {
		var arrRetorno = t.responseText.split('_');

		// Erro no retorno ou Cep Inexistente
		if ( arrRetorno.length == '1' )
		{
		    $('txtUf').value 		= '';
		    $('txtCidade').value	= '';
		    $('txtBairro').value	= '';
		    $('txtRua').value		= '';
		}
		else
		{
		    $('txtUf').value 	= arrRetorno[0];
		    $('txtCidade').value= arrRetorno[1];
		    $('txtBairro').value= arrRetorno[2];
		    $('txtRua').value	= arrRetorno[3];
		}
	    }
	});
    }
    else
    {
	showAlertModal('divAlert', 'CEP', 'CEP Inválido');

	setTimeout(function()
	{
	    Windows.close('winAlert');
	}, 2000);
    }
}
var strCaseId = 0;
var funPopulaCaseBox = function() {

	strCaseId = arguments[0];
	/**
	 * Tratamento se o strCaseId vier igual a 0
	 */
	if ( strCaseId == '0' )
	{
		strCaseId = 'padrao';
	}
	['case_conteudo_padrao','case_conteudo_mobilemkt','case_conteudo_emailmkt','case_conteudo_integracao','case_conteudo_gateway','case_conteudo_publicidade','case_conteudo_bluetooth','case_conteudo_aplicativo','case_conteudo_cool'].each(Element.hide);
	$('case_conteudo_'+strCaseId).show();
};

// tratando o 'onload' da página
Event.observe(window, 'load', function()
{
    // recuperando os parâmetros passados pela url e guardando em um array
    qs();
    
    // tratando os eventos ocorridos no submenu
    $$('div#menuLogado a.subMenuItem').each(function(objLink)
    {
        Event.observe(objLink, 'mouseover', function()
        {
            $$('div#menuLogado a.subMenuTitulo').each(function(objLinkPrincipal)
            {
                objLinkPrincipal.addClassName('ativo');
            });
        });

        Event.observe(objLink, 'mouseout', function()
        {
            $$('div#menuLogado a.subMenuTitulo').each(function(objLinkPrincipal)
            {
                objLinkPrincipal.removeClassName('ativo');
            });
        });
    });
});


