/*===============================================
Biblioteca de funções em javascript
Conselho Regional de Contabilidade de SP
Outubro/2008
================================================*/

function StringToXml(text) {
if (window.DOMParser)
  {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(text,"text/xml");
  }
else // Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text);
  }
return xmlDoc;  
}

// 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 PadDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

function especiaisChars(source)
{ 
    i = 0;
    while (i < source.length) {
        if (source.charCodeAt(i) > 255 || source.charCodeAt(i) == 180 || source.charAt(i) == '<' || source.charAt(i) == '>') {
            return source.charAt(i);
        } else if (source.charAt(i) == '&' && source.charAt(i+1) == '#')
            return "&#";
        i = i+1;
    }    
    return "";
}

function LimpaChars(obj)
{
    ch = especiaisChars(obj.value);
    while ( ch != "") {
        obj.value = obj.value.replace(ch,"");
        ch = especiaisChars(obj.value);
    }
}

// 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];
}

function addDate(dateObject, numDays) {
    dateObject.setDate(dateObject.getDate() + numDays);
    return dateObject;
}

function Trim(str){return str.replace(/^\s+|\s+$/g,"");}

function getNextDate(campoOrigem, campoDestino, totalDias) {                
    if (document.getElementById(campoDestino) != null && document.getElementById(campoDestino).value == '') {
        var strDataOrigem = document.getElementById(campoOrigem).value;
        if (IsDate(strDataOrigem)) {
            var dia = strDataOrigem.substr(0,2);
            var mes = strDataOrigem.substr(3,2);
            var ano = strDataOrigem.substr(6,4);
            
            var data = new Date(ano, Number(mes)-1, dia);
            data = addDate(data, totalDias);         

            dia = "0" + data.getUTCDate().toString();
            mes = "0" + Number(data.getMonth()+1).toString();
            ano = "000" + data.getFullYear().toString();
            
            dia = dia.substr(dia.length-2, 2);
            mes = mes.substr(mes.length-2,2);
            ano = ano.substr(ano.length-4,4);
                                                          
            document.getElementById(campoDestino).value = dia + '/' + mes + '/' + ano;
        }
    }
}

function IsDate(v) 
{
        var bissexto = 0;
        var data = v; 
        var tam = data.length;
        if (tam == 10) 
        {
                var dia = data.substr(0,2)
                var mes = data.substr(3,2)
                var ano = data.substr(6,4)
                if ((ano > 1900)||(ano < 2100))
                {
                        switch (mes) 
                        {
                                case '01':
                                case '03':
                                case '05':
                                case '07':
                                case '08':
                                case '10':
                                case '12':
                                        if  (dia <= 31) 
                                        {
                                                return true;
                                        }
                                        break
                                
                                case '04':              
                                case '06':
                                case '09':
                                case '11':
                                        if  (dia <= 30) 
                                        {
                                                return true;
                                        }
                                        break
                                case '02':
                                        /* Validando ano Bissexto / fevereiro / dia */ 
                                        if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) 
                                        { 
                                                bissexto = 1; 
                                        } 
                                        if ((bissexto == 1) && (dia <= 29)) 
                                        { 
                                                return true;                             
                                        } 
                                        if ((bissexto != 1) && (dia <= 28)) 
                                        { 
                                                return true; 
                                        }                       
                                        break                                           
                        }
                }
        }       
        return false;
}

// 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(evt) {    
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if (evt.keyCode == 13) {return false;}      
}

// 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) 
{
    // Caso passe o ID, e não o objeto (calendario passa ID)
    if (document.getElementById(campo) != null)
     campo = document.getElementById(campo);

    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 (x == "hora") {
			sMask = "99: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;
}

function left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

/*Usada no MsgUsuario e no Calendário*/
function muda_opacidade(id,opacity,modo) 
{ 
	if(opacity>100){
		opacity=100;
	}
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100); 
	object.MozOpacity = (opacity / 100); 
	object.KhtmlOpacity = (opacity / 100); 
	// No msgusuario dá pau no IE
	if (modo == 1)
	    object.filter = "alpha(opacity=" + opacity + ")"; 
} 

/*FUNCOES DO CALENDARIO JS*/
function iniciaCalendario(calend, obj, acaoPosterior) {
    obj = document.getElementById(obj);
    // Testo pois pode ser q o objeto não seja desenhado (visible=false)
    if ( obj != null ) {
        obj.onkeyup = new Function("DigitaData('"+obj.id+"', false);");
        obj.onclick = new Function("exibeCalendario(true,'"+obj.id+"','"+calend+"', '" + acaoPosterior + "');");
        obj.onfocus = new Function("exibeCalendario(true,'"+obj.id+"','"+calend+"', '" + acaoPosterior + "');");
        obj.onkeydown = new Function("exibeCalendario(false,'"+obj.id+"','"+calend+"', '" + acaoPosterior + "');");
    }
}

function fechaCalendario(calend, obj) {
  if ((document.getElementById(calend).style.zIndex != '298') && (document.activeElement.getAttribute("id") != obj)){
   document.getElementById(calend).style.display = 'none';
  }
}

function exibeCalendario(exibe, obj, calend, acaoPosterior) {
    obj = document.getElementById(obj);
	if ((exibe == true) && (document.getElementById(calend).style.display != 'inline') && (!obj.readOnly)){
		var d = new Date();
		if (obj.value.length == 10)
		    desenhaCalendario(Number(obj.value.substring(3,5))-1, obj.value.substring(6,10), obj.id, calend, acaoPosterior);
		else
		    desenhaCalendario(d.getMonth(), d.getFullYear(), obj.id, calend, acaoPosterior);
		funcbody = eval(document.body.onmouseup);
		if (funcbody != null)
		    funcbody();
	    document.body.onmouseup = new Function('fechaCalendario("'+calend+'","'+obj.id+'");');
		document.getElementById(calend).style.top=(Number(obj.style.top.replace("px",""))-10)+"px";
		document.getElementById(calend).style.left=(Number(obj.style.left.replace("px",""))+Number(obj.style.width.replace("px","")))+"px";
		document.getElementById(calend).style.display = 'inline';
		animaCalendario(calend,0);
	} else if (exibe == false) {
		document.getElementById(calend).style.display = 'none';
	}	
}

function animaCalendario(calend,c,sobe) {
    muda_opacidade(calend,c,1);
    c = Number(c)+10;
    if (c<110)
       setTimeout("animaCalendario('" + calend + "','" + c + "')", 30);   
}

function desenhaCalendario(mes, ano, obj, calend, acaoPosterior){

	if (acaoPosterior == null || acaoPosterior == "undefined") 
	    acaoPosterior = "";

	var day_of_week = new Array('D','S','T','Q','Q','S','S');
	var month_of_year = new Array('Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');
	//var feriados = ",1/1,3/1,10/1,17/1,24/1,25/1,31/1,7/2,14/2,16/2,17/2,21/2,28/2,7/3,14/3,21/3,28/3,2/4,4/4,11/4,18/4,21/4,25/4,1/5,2/5,9/5,16/5,23/5,30/5,3/6,6/6,13/6,20/6,27/6,4/7,9/7,11/7,18/7,25/7,1/8,8/8,15/8,22/8,29/8,5/9,7/9,12/9,19/9,26/9,3/10,10/10,12/10,17/10,24/10,31/10,2/11,7/11,14/11,15/11,20/11,21/11,28/11,5/12,12/12,19/12,25/12,26/12,";
	
	var Calendar = new Date();
	
	var DAYS_OF_WEEK = 7; // valor constante para o numero de dias na semana
	var DAYS_OF_MONTH = 31; // valor para o numero de dias no mês
	var cal; // imprime o calendario na tela
	
	var today = Calendar.getDate();
	var mtoday = Calendar.getMonth();
	var ytoday = Calendar.getFullYear();
	
	Calendar.setYear(ano);
	
	Calendar.setDate(1); // Começa o calendario no dia '1'
	Calendar.setMonth(mes); // Seta o calendario para determinado mês
	
	var month = Calendar.getMonth(); // Retorna o mês (0-11)
	var weekday = Calendar.getDay(); // Retorna o dia da semana (0-6)

	mes_posterior = mes + 1;
	mes_anterior = mes - 1;
	ano_posterior = ano;
	ano_anterior = ano;
	
	if (mes_posterior > 11) {
		mes_posterior = 0;
	}
	
	if (mes_anterior < 0) {
		mes_anterior = 11;
	}	
	
	if (mes_posterior == 0) {
	    ano_posterior = ano + 1;
	}
	
	if (mes_anterior == 11) {
	    ano_anterior = ano - 1;
	}	
	
//	cal = '<TABLE id="tabela_calendario" cellspacing="0" cellpadding="2" style="width: 154px; border:solid; border-width:1px; border-color:#555753; background-color:#aaaaaa; border: solid 1px #ff0000">';
		cal = '<TABLE width="150" cellspacing="0" cellpadding="2" style="font-size:10px" border="0" >';
			cal += '<TR bgcolor="#555753">'
				cal += '<TD style="font-size:11px; color: #ff9900;" colspan="7">';
				cal += '<div style="position: relative; width: 150px; height: 15px;">';
				cal += '<div style="position: absolute; width: 25px; height: 15px; top:0px; left: 0px; text-align: left; padding: 1px 0px 0px 0px;">';				
				cal += '<a href="#" onClick="desenhaCalendario('+ mes +','+ Number(Number(ano)-1) +',\''+ obj +'\',\''+ calend +'\',\''+acaoPosterior+'\');"><img src="/imagens/seta_volta_dupla.gif" border="0"/></a>&nbsp;';			
				cal += '<a href="#" onClick="desenhaCalendario('+ mes_anterior +','+ ano_anterior +',\''+ obj +'\',\''+ calend +'\',\''+acaoPosterior+'\');"><img src="/imagens/seta_volta.gif" border="0"/></a>';
				cal += '</div>';
				cal += '<div style="position: absolute; width: 100px; height: 15px; top:0px; left: 25px; text-align: center;">' + month_of_year[mes] + '&nbsp;' + ano + '</div>';
				cal += '<div style="position: absolute; width: 25px; height: 15px; top:0px; right: 0px; text-align: right; padding: 1px 0px 0px 0px;">';
				cal += '<a href="#" onClick="desenhaCalendario('+ mes_posterior +','+ ano_posterior +',\''+ obj +'\',\''+ calend +'\',\''+acaoPosterior+'\');"><img src="/imagens/seta_escolha.gif" border="0"/></a>&nbsp;';
				cal += '<a href="#" onClick="desenhaCalendario('+ mes +','+ Number(Number(ano)+1) +',\''+ obj +'\',\''+ calend +'\',\''+acaoPosterior+'\');"><img src="/imagens/seta_escolha_dupla.gif" border="0"/></a>';
				cal += '</div></div>';
				cal += '</TD>';
			cal += '</TR>';
		
			// ******  cria o cabeçalho com as iniciais dos nomes dos dias da semana ******
			cal += '<TR style="font-weight:bold">';
	
				for(index=0; index < DAYS_OF_WEEK; index++) 
				{
					if(weekday == index)
						cal += '<td style="text-align:center">' + day_of_week[index] + '</td>';
					else
						cal += '<td style="text-align:center">' + day_of_week[index] + '</td>';
				}
	
			cal += '</TR>';
	
			// ******  cria as células dos dias do mês ******
		if (Calendar.getDay() != 0) {
	
			cal += '<TR>';
	
			for(index=0; index < Calendar.getDay(); index++) // cria células vazias até o 1° dia
				cal += '<td>' + '&nbsp;' + '</td>';
		}
	
		for(index=0; index < DAYS_OF_MONTH; index++)
		{
		
			if ( Calendar.getDate() > index )
			{
				week_day = Calendar.getDay(); 
			
				if(week_day == 0)
					cal += '<TR">';
	
				if(week_day != DAYS_OF_WEEK)
				{
					var day = Calendar.getDate();								
			    				    				
  			        cal += "<td style=\"text-align:center\"><a href='#' style='"+ ((today == day) && (mtoday == month) && (ytoday == ano) ? 'color:#ff9900; ' : ((week_day == 0) ? 'color:#CC0000; ' : '')) +" font-size:11px; text-decoration: none;'" + " onClick='document.getElementById(\""+obj+"\").value = \""+ right("0"+day,2) + "/" + right("0"+(Number(month)+1),2) + "/" + ano + "\"; " + acaoPosterior + " document.getElementById(\""+calend+"\").style.zIndex = \"297\"; exibeCalendario(false,\"\",\""+calend+"\", \"" + acaoPosterior + "\");'>" + day + "</a></td>";
				}
					
				if(week_day == 6)
					cal += '</TR>';
				}
					
			Calendar.setDate(Calendar.getDate()+1);		
		}		
		cal += '</TABLE>';
		
		objcal = document.getElementById(calend);		
		objcal.innerHTML = cal;
			
		objcal.onmousemove = new Function('document.getElementById("'+obj+'").focus();');
		objcal.onmousedown = new Function('document.getElementById("'+obj+'").focus();');
		objcal.onmouseover = new Function('document.getElementById("'+calend+'").style.zIndex = "298";');
		objcal.onmouseout = new Function('document.getElementById("'+calend+'").style.zIndex = "297";');	
}
