/*===============================================
Biblioteca de funções em javascript
Conselho Regional de Contabilidade de SP
Outubro/2008
================================================*/


// Funcao que pega um atributo dentro de uma string
// Exemplo: getAttString("url=www.crcsp.org.br;width=790;height=550", "width")
//    Retorna "790" 
function getAttString(sString, sAttribute)
{
        //          10        20        30        40        50        60        70        80
        // 01234567890123456789012345678901234567890123456789012345678901234567890123456789012
        //'0;url=http://online.crcsp.org.br/registrados/menu/inicio.aspx;width=790;height=550'

        if (sString.indexOf(sAttribute) == -1)
        {
                return '';
        }
        else
        {
                var posAtt = sString.indexOf(sAttribute);
                var posIniValue = sString.indexOf('=', posAtt)+1;
                var qtdValue = (sString.indexOf(';', posIniValue) == -1 ? sString.length-posIniValue : sString.indexOf(';', posIniValue)-posIniValue);
                return sString.substr(posIniValue, qtdValue);
        }
}

function especiaisChars(sValue)
{
    return ((sValue.indexOf('<') >= 0) || (sValue.indexOf('>') >= 0) || (sValue.indexOf('&#') >= 0));
}

function LimpaChars(obj)
{
    if (especiaisChars(obj.value))
    {
        obj.value = obj.value.replace("<","").replace(">","").replace("&#","")
    }
}

// Função para retirar a acentuação de um texto
function retiraAcentuacao(texto)
{
    var vRetorno = texto;

    vRetorno = vRetorno.replace("à", "a");
    vRetorno = vRetorno.replace("á", "a");
    vRetorno = vRetorno.replace("à", "a");
    vRetorno = vRetorno.replace("â", "a");
    vRetorno = vRetorno.replace("ä", "a");
    vRetorno = vRetorno.replace("ã", "a");
    vRetorno = vRetorno.replace("é", "e");
    vRetorno = vRetorno.replace("è", "e");
    vRetorno = vRetorno.replace("ê", "e");
    vRetorno = vRetorno.replace("ë", "e");
    vRetorno = vRetorno.replace("í", "i");
    vRetorno = vRetorno.replace("ì", "i");
    vRetorno = vRetorno.replace("î", "i");
    vRetorno = vRetorno.replace("ï", "i");
    vRetorno = vRetorno.replace("ó", "o");
    vRetorno = vRetorno.replace("ò", "o");
    vRetorno = vRetorno.replace("ô", "o");
    vRetorno = vRetorno.replace("ö", "o");
    vRetorno = vRetorno.replace("õ", "o");
    vRetorno = vRetorno.replace("ú", "u");
    vRetorno = vRetorno.replace("ù", "u");
    vRetorno = vRetorno.replace("û", "u");
    vRetorno = vRetorno.replace("ü", "u");
    vRetorno = vRetorno.replace("Á", "A");
    vRetorno = vRetorno.replace("À", "A");
    vRetorno = vRetorno.replace("Â", "A");
    vRetorno = vRetorno.replace("Ä", "A");
    vRetorno = vRetorno.replace("Ã", "A");
    vRetorno = vRetorno.replace("É", "E");
    vRetorno = vRetorno.replace("È", "E");
    vRetorno = vRetorno.replace("Ê", "E");
    vRetorno = vRetorno.replace("Ë", "E");
    vRetorno = vRetorno.replace("Í", "I");
    vRetorno = vRetorno.replace("Ì", "I");
    vRetorno = vRetorno.replace("Î", "I");
    vRetorno = vRetorno.replace("Ï", "I");
    vRetorno = vRetorno.replace("Ó", "O");
    vRetorno = vRetorno.replace("Ò", "O");
    vRetorno = vRetorno.replace("Ô", "O");
    vRetorno = vRetorno.replace("Ö", "O");
    vRetorno = vRetorno.replace("Õ", "O");
    vRetorno = vRetorno.replace("Ú", "U");
    vRetorno = vRetorno.replace("Ù", "U");
    vRetorno = vRetorno.replace("Û", "U");
    vRetorno = vRetorno.replace("Ü", "U");
    vRetorno = vRetorno.replace("Ç", "C");
    vRetorno = vRetorno.replace("ç", "c");
    vRetorno = vRetorno.replace("\'", " ");    
    vRetorno = vRetorno.replace("\"", " ");

    return vRetorno;
}

// Função que pega um atributo de da query string
function queryString(name)
{  
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    
    if( results == null )
        return "";
    else
        return results[1];
}

// Funcao que retorna se o texto passado é numérico ou não
function IsNumeric(sText)
{
        var ValidChars = "0123456789";
        var IsNumber=true;
        var Char;

        for (i = 0; i < sText.length && IsNumber == true; i++)
        {
                Char = sText.charAt(i);
                if (ValidChars.indexOf(Char) == -1)
                {
                        IsNumber = false;
                }
        }
        return IsNumber;
}

// Funcao que so permite digitacao somente de numeros 
function SomenteNumero(evtKeyPress) 
{
    var key = '';
    var strCheck = '0123456789';
    var nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;    
  
    //alert(nTecla);
    //return true;  
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // nTecla==0 faz com que seja possivel usar todas as teclas como delete, setas, etc  
    if ((nTecla == 13) || (nTecla == 0) || (nTecla == 8) || (nTecla == 35) || 
        (nTecla == 36) || (nTecla == 37) || (nTecla == 39) || (nTecla == 46))
    	return true;
    	
    key = String.fromCharCode(nTecla); // Valor para o código da Chave
    	
    if (strCheck.indexOf(key) == -1)
    	    return false; // Chave inválida
}

// Função para desabilitar a tecla Enter
function desabilitaEnter(evtKeyPress) {
    if (evtKeyPress.keyCode == 13)
    {
        evtKeyPress.returnValue=false;
        evtKeyPress.cancel = true;
    }
}

// Função para submeter um form quando um enter for pressionado em um textbox
function submeterTextBox(evtKeyPress, funcaoSubmit)
{    
    var nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;  
     
    if (nTecla == 13)
    {        
        funcaoSubmit();
        return false;
    }
}

// Funcao que permite que seja aplicado uma máscara para um textbox de data
// Usar no onKeyUp Ex: onKeyUp="DigitaData(this, false)"
function DigitaData(campo, somenteMesAno) 
{
    var data = new String( campo.value );
    var wData = '';
    var cont = 0;

    for (i=0; i<data.length ; i++) 
    {
        if (i <= 1) 
        {
            if ( data.charAt(i) >= '0' && data.charAt(i) <= '9' )	
                wData += data.charAt(i);
            else 
                cont++;
        }
	  
        if (i == 2) 
        {	  
            if (data.charAt(i) == '/') 
                wData += data.charAt(i);
            else 
            {
                if (data.charAt(i) >= '0' && data.charAt(i) <= '9') 
                {
                    wData += '/';
                    wData += data.charAt(i);
                    cont ++;
                }
                else 
                {
                    wData += '/';
                    cont ++;
                }
            }
        }

        if (i > 2 && (i <= 4 || somenteMesAno)) 
        {
            if (data.charAt(i) >= '0' && data.charAt(i) <= '9') 
                wData += data.charAt(i);
           else
                cont++;       
        }
    	  
    	if (!somenteMesAno)
    	{
            if (i == 5) 
            {	  
                if (data.charAt(i) == '/')
                    wData += data.charAt(i);
                else 
                {
                    if (data.charAt(i) >= '0' && data.charAt(i) <= '9') 
                    {
                        wData += '/';
                        wData += data.charAt(i);
                        cont++;
                    }
                    else 
                    {
                        wData += '/';
                        cont++;
                    }
                }
            }

            if (i > 5 && i <= 9) 
            {
                if (data.charAt(i) >= '0' && data.charAt(i) <= '9')
                    wData += data.charAt(i);
                else 
                    cont++;
            }
        	  
            if (i > 9)
                cont++;
        }                
    }
	
    if (cont > 0) 
    {
        // Atualiza o campo 
        campo.value = wData;
    }
}

// Funcao que permite que seja aplicado uma máscara para um textbox
function Mask_onkeypress(x, sMask, evtKeyPress, objForm) 
{
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
    
    /* PARA DATA USAR FUNÇÃO DigitaData
    =====================================
    if (x == "data") {
        sMask="99/99/9999";
    }
    */    
     
    if (x == "fone") {
            sMask = "(99)9999-9999";
    }
    if (x == "cep") {
            sMask = "99999-999";
    }
    if (x == "mes_ano") {
            sMask = "99/9999";
    }
    if (x == "cpf") {
            sMask = "999.999.999-99";
    }
    if (x == "cnpj") {
            sMask = "99.999.999/9999-99";
    }    
    if (x == "rg") {
            sMask = "99999999-9";
    }
    if (x == "val") {
            sMask = "999999,99";
    }
	if (x == "horas") {
			sMask = "999:99";
	}	

    if(window.event) {
         nTecla = evtKeyPress.keyCode;
    }
    else if(evtKeyPress.which) {
         nTecla = evtKeyPress.which;
    }
    
    //window.alert("nTecla = " + nTecla + "\nobjForm.value = " + objForm.value);

    sValue = objForm.value;
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );	
    sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );	
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( ":", "" );	
    fldLen = sValue.length;
    mskLen = sMask.length;
    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) 
    {
        //window.alert("nTecla = " + nTecla + "\nsValue = " + sValue + "\nnCount = " + nCount + "\nsCod = " + sCod + "\ni = " + i + "\nmskLen = " + mskLen + "\nsMask.charAt(i) = " + sMask.charAt(i));    
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
        if (bolMask) 
        {
            //window.alert("entrou no bolMask! sCod antes = " + sCod);
            sCod += sMask.charAt(i);
            mskLen++; 
            //window.alert("entrou no bolMask! sCod depois = " + sCod);
        }
        else 
        {
            sCod += sValue.charAt(nCount);
            nCount++;
        }
        i++;
    }

    objForm.value = sCod;

    if (nTecla != 8 && nTecla != 0 && nTecla != 35 && nTecla != 36 && nTecla != 37 && nTecla != 39)
    {
        if (sMask.charAt(i-1) == "9") {
            return ((nTecla > 47) && (nTecla < 58)); }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}

// Funcao que retorna se o texto passado é um endereço de e-mail válido
function EmailValido(email)
{
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return filter.test(email);
}

// Funções para desabilitar o ctrl+C, ctrl+V e menu de contexto
// para impedir o copy e paste (não funciona no Opera).
function whichButton(event)
    {
        if (event.button==2)//RIGHT CLICK
        {
            return false;
        }
    }

function noCTRL(e)
{
    var code = (document.all) ? event.keyCode:e.which;
    if (parseInt(code)==17) //CTRL
    {
        window.event.returnValue = false;
    }
}

// Função que formata valor conforme digitado
function formataValor(campo) {
        campo.value = filtraCampo(campo);
        vr = campo.value;
        tam = vr.length;

        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 <= 18) ){
               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 ) ;}
               
}

// limpa todos os caracteres especiais do campo solicitado
function filtraCampo(campo){
        var s = "";
        var cp = "";
        vr = campo.value;
        tam = vr.length;
        for (i = 0; i < tam ; i++) {  
               if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
                       s = s + vr.substring(i,i + 1);}
        }
        campo.value = s;
        return cp = campo.value
}

// muda foco para outro componente
function MudaFocoComponente(nform, obj, evtKeyPress, qtdeCaracteres, nomeComponente) {
        var nTecla = (evtKeyPress.which) ? evtKeyPress.which : evtKeyPress.keyCode;    

		if ((obj.value.length == qtdeCaracteres) && (nTecla != 9) && (nTecla != 16))
		{
			for (var i=0; i<nform.elements.length; i++)
			{
				var e = nform.elements[i];
				if (e.name == nomeComponente)
				{
					e.focus();
				}
			}
		}
}

function anima() {
	if ( document.getElementById('processando').style.visibility == 'hidden' ) {
		document.getElementById('processando').style.visibility = 'visible';
		if (!pararAnima)		
		{
    		setTimeout('anima()',1500);
    	}
	} else {
		document.getElementById('processando').style.visibility = 'hidden';
		if (!pararAnima)
		{
		    setTimeout('anima()',300);
		}
	}
	if (pararAnima)
	{
        document.getElementById('processando').style.visibility = 'hidden';
	}
}

/***************************************************
 * Esta função verifica se os valores informados   *
 * no parâmetro celulas já estão presentes na      *
 * tabela informada no parâmetro tbl.              *
 * Esta função irá verificar somente as colunas    *
 * do parâmetro colsVerificar, por exemplo:        *
 * Tendo uma tabela com os valores abaixo:         *
 *   Linha1xCol1   Linha1xCol2   Linha1xCol3       *
 *   Linha2xCol1   Linha2xCol2   Linha2xCol3       *
 * Se quisesse saber se tem uma linha com as       *
 * colunas 1 e 3 com os valores Linha2xCol2 e      *
 * Linha2xCol3 faria desta forma:                  *
 *  cverifica = new Array(0,2);                    *
 *  cels = new Array("Linha1xCol1", "Linha1xCol3");*
 *  existe = verificarExistencia(<nome_tabela>,    *
 *                      cverifica, cels);          *
 * Que faria existe ficar true pois as colunas 1 e *
 * 3 tem os valores informados em cels.            *
 * Por: Marco Aurélio Aloise Filho                 *
 ***************************************************/        
function verificarExistencia(tbl, colsVerificar, celulas) {
    table = document.getElementById(tbl);
    row_count = table.rows.length;                        
                
    for (l=0;l<row_count;l++) {
        row = table.rows[l];
        retorno = true;
             
        for (cv=0;cv<colsVerificar.length;cv++) {
            col = colsVerificar[cv];            
            cell = row.cells[col];
            val = celulas[cv];
            valCell = cell.firstChild.nodeValue;   
            retorno = retorno && (val == valCell)
        }               
        
        if (retorno)
            return true;
    }
    
    return false;
}

/*****************************************************
 * Esta função converte o código de um estado na sua *
 * sigla quando o número de registro for preenchido  *
 * com o código.                                     *
 * Por: Marco Aurélio Aloise Filho                   *
 *****************************************************/
function codigoToSiglaEstado(numero_registro)
{
    var nreg = numero_registro;
    if (numero_registro > 3) {
        cod = numero_registro.substring(1,3);
        
        sigla = cod;               
        
        if (IsNumeric(cod)) {
            if (cod == "28") sigla = "-";
            else if (cod == "27") sigla = "AC";
            else if (cod == "09") sigla = "AL";
            else if (cod == "01") sigla = "AM";
            else if (cod == "29") sigla = "AP";
            else if (cod == "11") sigla = "BA";
            else if (cod == "05") sigla = "CE";
            else if (cod == "21") sigla = "DF";
            else if (cod == "12") sigla = "ES";
            else if (cod == "22") sigla = "GB";
            else if (cod == "20") sigla = "GO";
            else if (cod == "03") sigla = "MA";
            else if (cod == "18") sigla = "MG";
            else if (cod == "23") sigla = "MS";
            else if (cod == "19") sigla = "MT";
            else if (cod == "02") sigla = "PA";
            else if (cod == "07") sigla = "PB";
            else if (cod == "08") sigla = "PE";
            else if (cod == "04") sigla = "PI";
            else if (cod == "15") sigla = "PR";
            else if (cod == "13") sigla = "RJ";
            else if (cod == "06") sigla = "RN";
            else if (cod == "26") sigla = "RO";
            else if (cod == "25") sigla = "RR";
            else if (cod == "17") sigla = "RS";
            else if (cod == "16") sigla = "SC";
            else if (cod == "10") sigla = "SE";
            else if (cod == "14") sigla = "SP";
            else if (cod == "24") sigla = "TO";
            
            nreg = numero_registro.substring(0,1) + sigla + numero_registro.substring(3);
        }        
    }
    
    return nreg;
}

/************************************************
 * Verifica se o número de registro informado é *
 * válido, seguindo o padrão 9ZZ999999.         *
 * Por: Marco Aurélio Aloise Filho              * 
 ************************************************/
function validaNumeroRegistro(numero_registro)
{
    var regExMask = /\d{1}[A-Z|a-z]{2}\d{6}/g;
    var result = regExMask.exec(numero_registro);
    var passou = result != null;
    return passou;
}

/***********************************************
 * Esta função converte uma data texto em Date *
 * utilizando o formado dd/mm/yyyy.            *
 ***********************************************/
function retornaData(data) 
{       
    if (data.length == 10) {
        try {
            var dia = new Number(data.substring(0,2));
            var mes = new Number(data.substring(3,5));
            var ano = new Number(data.substring(6,10));                                   
                        
            if (ano > 1900) {
                var retData = new Date(ano, mes-1, dia, 0, 0, 0, 0);
                return retData;
            } else {
                return null;
            }
        } catch (err) {
            return null;
        }
    } else {
        return null;
    }
}

/*************************************************
 * Esta função compara duas data, o retorno pode *
 * ser: 1  - se a primeira data for maior        *
 *      -1 - se a primeira data for menor        *
 *      0  - se as datas forem iguais.           *
 ************************************************/
function compararPeriodo(strData1, strData2)
{
    var dataIni = retornaData(strData1);
    var dataFim = retornaData(strData2);
    
    if (dataIni < dataFim)
        return 1;
    else if (dataIni > dataFim)
        return -1;
    else
        return 0;
}