﻿// Arquivo com JavaScripts utilizados pelo  DJE

/*
    Mostra prévia da impressão
*/
function PrintPreview(sender, OLECMDID) 
{  
    //var OLECMDID = 10; 
     
    /* OLECMDID values:  
    * 6 - Imprimir 
    * 7 - Imprimir com pré-visualização
    * 8 - Ajuste da página antes da impressão 
    * 1 - Nova Janela 
    * 4 - Salvar Como  
    * 10 - Propriedades  
    */
    /*document.getElementById(sender).style.visibility='hidden'; */
    document.getElementById(sender).style.display = 'none';
   
    try 
    { 
        var PROMPT = 1; //consultar usuário = 1, não consultar = 0 
        var oWebBrowser = document.getElementById("WebBrowser1");
    
        if(oWebBrowser == null)
        { 
            var sWebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; 
            document.body.insertAdjacentHTML('beforeEnd', sWebBrowser); 
            oWebBrowser = document.getElementById("WebBrowser1");        
        }
 
        oWebBrowser.ExecWB(OLECMDID,PROMPT); 
    } 
    catch(e)
    {
        //se ocorreu erro, usa a impressão padrão
        var intVersaoNavegador = parseInt(navigator.appVersion); 

        if (intVersaoNavegador >= 4) 
            window.print();     
    } 
    
    return false;
} 

/*
    Mostra uma divisória
*/
function MostraDiv ( _divId )
{
    document.getElementById(_divId).style.display = "block";
}

/*
    Esconde uma divisória
*/
function EscondeDiv ( _divId )
{
    document.getElementById(_divId).style.display = "none";
}

/*
    Testa se a tecla digitada é numérica
*/
function IsNumeric(e) 
{    
    var keynum;
    
    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }       
   
    
    if ((keynum == 45 && e.shiftKey) /* shift + ins */
        || (keynum == 86 && e.ctrlKey) /* ctrl + c */
        || (keynum == 36 && e.shiftKey) /* shift + home */
        || (keynum == 35 && e.shiftKey) /* shift + end */
        )
    {
        return true;
    }
    
    if (keynum == 8 || keynum == 9 /* tab */ || keynum == 16 /* shift */ || keynum == 17 /* ctrl */ 
        || keynum == 37 /* < */ || keynum == 39 /* > */ || keynum == 46 /* del */
        || keynum == 36 /* Home */ || keynum == 35 /* End */
        || (keynum > 47 && keynum <58) || (keynum > 95 && keynum < 106))
    {    
        return true;
    }
    else
    {
        return false;
    }
}

// Limita tamanho máximo de uma TextBox, mostrando uma mensagem de aviso
function TamanhoMaximo_Mensagem ( _ctrTextBox, _intTamanhoMaximo, _ctrMensagem, _strMensagem )
{
    if ( _ctrTextBox.value.length > _intTamanhoMaximo )
    {
        _ctrTextBox.value = _ctrTextBox.value.substring(0, _intTamanhoMaximo);
        document.getElementById(_ctrMensagem).textContent = _strMensagem;
        document.getElementById(_ctrMensagem).innerText = _strMensagem;
    }
    else
    {
        document.getElementById(_ctrMensagem).textContent = "";
        document.getElementById(_ctrMensagem).innerText = "";
    }
}

// Limita tamanho máximo de uma TextBox, sem mostrar mensagem de aviso
function TamanhoMaximo_SemMensagem ( _ctrTextBox, _intTamanhoMaximo )
{
    if ( _ctrTextBox.value.length > _intTamanhoMaximo )
    {
         _ctrTextBox.value = _ctrTextBox.value.substring ( 0, _intTamanhoMaximo );
    }
}

// Verifica se o campo de confirmação de senha deve estar habilitado
function VerificaCampoConfirmacao( _ctrTxtSenha, _ctrTxtConfirmacaoSenha )
{
    if(document.getElementById(_ctrTxtSenha).value != "")
    {
        document.getElementById(_ctrTxtConfirmacaoSenha).disabled = 0;
    }
    else
    {
        document.getElementById(_ctrTxtConfirmacaoSenha).value = "";
        document.getElementById(_ctrTxtConfirmacaoSenha).disabled = 1; 
    }
}

/*
    Abre um arquivo em nova janela
*/
function Abre_Arquivo( _arquivo ){
    window.open(_arquivo);
}

/*
   Abre um documento para visualização
*/
function Visualizar_Arquivo( _controle ) {  

    var OFFICE2000 = 9;
    var OFFICE2007 = 12;
            
    if (document.getElementById(_controle)){
        var arquivo = document.getElementById(_controle).value;
        
        //verifica se existe um arquivo a ser exibido
        if (arquivo != ""){    
            var blnAbriuArquivo = false;
        
            //verifica se o navegador dá suporte
            if(window.ActiveXObject){
            
                var WScript = null;
            
                //tenta obter um objeto, se não conseguir o suporte está desabilitado
                try{
                    WScript = new ActiveXObject("WScript.Shell");
                }catch (e){
                    //irá abrir o link normal
                }
                
                if (WScript != null) {   
                    var worddir = "";
                    var versao = OFFICE2007;
                
                    //obtém o diretório de instalação do word
                    while (worddir == "" && versao >= OFFICE2000){
                        try {
                            var registro ="HKLM\\Software\\Microsoft\\Office\\" + versao + ".0\\Word\\InstallRoot\\Path";
                            worddir = WScript.regRead(registro);                        
                        } catch(e) {
                            versao--;
                        }
                    }
                
                    if (worddir != ""){
                        worddir = worddir + "WINWORD.EXE";                        
                        strComando = "\"" + worddir + " \"" + arquivo + "\"";
                        strComando = strComando.split("\\").join("\\\\"); 
            
                        //executa o office
                        try{    
                            WScript.run(strComando);
                            blnAbriuArquivo = true;
                        }catch (e){
                            //irá abrir o link normal
                        }
                    }                           
                }
            }
            
            //se não abriu usando word, abre normalmente   
            if (!blnAbriuArquivo){
                Abre_Arquivo(arquivo);
            }
            
            //Limpa o nome do arquivo                                
            document.getElementById(_controle).value = "";       
        }
    }
}   

/*
    Guarda identificador de um checkbox em um campo oculto caso ele esteja selecionado    
*/
function Guarda_Valor(_senderID, _hiddenID){

    var objSender = document.getElementById(_senderID);
    var hiddenField = document.getElementById(_hiddenID);
    
    //se tiver que colocar checkbox no viewstate
    if(objSender.checked)
    {
        hiddenField.value += (objSender.id + '#'); 
    }
    
    // se tiver que tirar checkbox do viewstate
    else
    {
        var arr = hiddenField.value.split('#');
        
        hiddenField.value = '';
        
        for(var i = 0; i<arr.length; i++)
        {
            if(arr[i] != _senderID)
                 hiddenField.value += (arr[i] + '#'); 
        }
    }
}

/*
    Controla a exibição de um calendário
*/
function ControleCalendario(_pnlCalendarioMostrar, _pnlCalendarioEsconder){
        if(document.getElementById(_pnlCalendarioMostrar).style.display == "none")
        {
            document.getElementById(_pnlCalendarioMostrar).style.display = "";
            document.getElementById(_pnlCalendarioMostrar).style.position = "absolute";
        }
        else
        {
            document.getElementById(_pnlCalendarioMostrar).style.display = "none";
        }   
        
        if (_pnlCalendarioEsconder != null)
        {
            document.getElementById(_pnlCalendarioEsconder).style.display = "none";
        }
}

/*
 * Obtém a applet do SDK de assinatura.
 */
function getApplet()
{
	return document.getElementById('assinadorDigital');
}

/**
 * @return Verdadeiro caso as bibliotecas do e-Assinador tenham sido encontradas.
 */
function existeAssinador() 
{
	var retorno = getApplet().existeAssinador();
	return (retorno && retorno.toUpperCase() == "TRUE");
}

/**
 * Assina um hash gerado usando SHA1 no formato detached usando o algoritmo RSA. 
 * parâmetros:
 * 		hash = string com o hash.
 * retorno: resultado da decriptografia em hexadecimal.
 */
function assinarHashDetached(hash) 
{
	return getApplet().assinarHashDetached(hash);
}

/**
 * Carimba um hash em forma de string.
 * parâmetros:
 * 		hash = hash que será carimbado.
 * 		oidHash = algoritmo que foi usado para gerar o hash.
 * retorno: string representado o dado carimbado em hexadecimal.
 */
function carimbarHash(hash, oidHash) 
{
	return getApplet().carimbarHash(hash, oidHash);
}