
/******************************************************************************/
/*	UTILS.JS
	Responsavel: Jefferson José Gomes
	Setor: Informática
	Ultima Atualizacao: 27/11/2006
*/
/******************************************************************************/



// Removes leading whitespaces
function LTrim( value ) {
   
   var re = /\s*((\S+\s*)*)/;
   return value.replace(re, "$1");
   
}

// Removes ending whitespaces
function RTrim( value ) {
   
   var re = /((\s*\S+)*)\s*/;
   return value.replace(re, "$1");
   
}

// Removes leading and ending whitespaces
function trimALL( value ) {
   
   return LTrim(RTrim(value));
   
}

//String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };




/******************************************************************************/
/*	Funcoes: w(<texto>) e wln(<texto>)
	Parametros: 
		- texto: Texto html a ser inserido na pagina
	Retorno: nenhum
	Descricao: Simplificam a sintaxe no codigo javascript*/
/******************************************************************************/
function w( texto)
{
	document.write( texto);
}

function wln( texto)
{
	document.writeln( texto);
}

/******************************************************************************/
/*	Funcao: popup(<url>, <nome_janela>[,atributos])
	Parametros:
		- url: Url a ser aberta na nova janela
		- janela: Nome da janela que sera' criada
		- atributos: Caracteristicas da janela, que devem ser seguir a sintaxe da
		funcao padrao window.open
	Retorno: O objeto correspondente a janela criada.
*/
/******************************************************************************/
function popup(url,janela,atributos)
{
	var WinPop =  window.open(url, janela, atributos);
	WinPop.focus();
}

/******************************************************************************/
/*	Funcao: random(n1, n2)
	Parametros:
		- n1: intervalo inferior
		- n2: intervalo superior
	Retorno: Inteiro
	Descricao: Retorna um valor inteiro randomico entre os valores especificados.
*/
/******************************************************************************/
function random(r1, r2) {
  if (r2 > r1) return (Math.round(Math.random()*(r2-r1))+r1);
  else return (Math.round(Math.random()*(r1-r2))+r2);
}

   function copiaArray(baseArray)
   {
      var novoArray = new Array();
      for(var i=0; i < baseArray.length; i++)
      {
         novoArray[i] = new String (baseArray[i]);
      }
      return novoArray;
   }


   function isSelect( campo, arraySelects) {
      if( arraySelects == null) return false;
      for( var i=0; i< arraySelects.length; i++)
      {
         if( arraySelects[i] == campo)
         {
            return true;
         }
      }
      return false;
   } 


   function isNull(checkString)
   {	
      var nulo=true,
          ch,
          str= new String(checkString);
      if(str.length == 0)
         return true;
      else
      {
         for (i=0; i<str.length; i++)
         {
            ch=str.substring(i,i+1);
            if (ch!='\r' && ch!='\n' && ch!=' ')
               return false;
         }
         return true;
      }
   }

/******************************************************************************/
/*        Funcao: isValidEmail(s)
        Parametros:
                - s: string contendo o email a ser verificado
        Retorno: boolean
        Descricao: Retorna um valor booleano se o email está dentro dos padrões
*/
/******************************************************************************/
   function isValidEmail(s) {

       if (s.indexOf("@") == -1) return false;
       if (s.indexOf(".") == -1) return false;
       at=false;
       dot=false;
       if (s.charAt(s.length-1) == '.'){
          return false;
       }
       for (var i = 0; i < s.length; i++) {
           ch = s.substring(i, i + 1)
           if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z")
                   || (ch == "@") || (ch == ".") || (ch == "_")
                   || (ch == "-") || (ch >= "0" && ch <= "9")) {
                   if (ch == "@"){
                     if (at) return false;
                     else at=true;
                   }
                   if ((ch==".") && at)
                      dot=true;
           }
           else return false;
       }

      return dot;
   }


/******************************************************************************/
/*      Funcao: verificaDatas(dataI, dataF )
        Parametros:
                - dataI: string contendo a data inicial
                - dataF: string contendo a data final
        Retorno: boolean
        Descricao: Retorna um valor booleano se a data final é maior q a data inicial
*/
/******************************************************************************/
   function verificaDatas(dataI, dataF )  {
      var dataInicial = dataI.split("/");
      dataInicial = new Date(dataInicial[2], ( parseInt(dataInicial[1]) -1 ), dataInicial[0],0,0,0);

      var dataFinal = dataF.split("/");
      dataFinal = new Date(dataFinal[2], ( parseInt(dataFinal[1]) -1 ), dataFinal[0],0,0,0);
      if (dataFinal >= dataInicial) {
         return true;
      } else {
         return false;
      }
   }


   function ConSeCart(text){
      var nrLetras = '';
      for (i=0; i<text.length; i++){
         nrLetras = nrLetras + ((i+2) * text.charCodeAt(i));
      }
      return nrLetras;
   }


   function valCart(txt, campo){
      if (txt != '') {
         var dv = getDigControle( txt.substr( 0, (txt.length-1) ) );
         if ( txt.substr( 0, (txt.length-1) ) + dv  != txt ) {
           alert('O Número do cartão não é válido...');
           if (campo != undefined){
              campo.focus();
           }
           return false;
         } else {
            return true;
         }
      }
   }


   function getDigControle(txt){
      var soma = 0;
      var multI = 0;
      var multS = '';
      for (var i=0; i < txt.length; i++){
         multI = fator_dig_controle_cartoes[i] * txt.charAt(i);
         multS = new String(multI)
         for (var j=0; j < multS.length; j++){
            soma = soma + parseInt(multS.charAt(j));
         }
      }
      var dv = 10 - (soma % 10);
      if (dv > 9) {
         return 1;
      } else {
        return dv;
      }
   }


/**************************************************************************************************/
/*      Funcao: getExtensaoArq(CampoPath, ArrayExtensao){
        Parametros:
                - CampoPath: caminho do arquivo que vai ser enviado
                - ArrayExtensao: array com as extensoes que são aceitas pelo campo do arquivo
        Retorno: nenhum
        Descricao: Exibe uma mensagem se o arquivo não for do tipo
*/
/**************************************************************************************************/

   function getExtensaoArq(CampoPath, ArrayExtensao){
      if (CampoPath.value != "") {
         var extArquivo = CampoPath.value.substr(CampoPath.value.length - 3, CampoPath.value.length);
         extArquivo = extArquivo;
         var extensaoValida = false;
         var strListaExtensao = '';



         for (var i=0; i<ArrayExtensao.length; i++ ) {
            strListaExtensao = strListaExtensao + "   - " + ArrayExtensao[i] + "\n";
            if ( ArrayExtensao[i] == extArquivo.toUpperCase() ) {
               extensaoValida = true;
            }
         }

         if (ArrayExtensao.length > 0 ) {
            if (! extensaoValida ) {
               alert('O arquivo selecionado precisa ser de um desses tipos:    \n \n' + strListaExtensao );
               CampoPath.select();
               CampoPath.focus();
            }
         }
      }
   }



/******************************************************************************/
/* Funcao: adicionaCaracter(string, charAdd, qtd , posicao)
 Parametros:
  - string: valor original da string
  - charAdd  : string a ser adicionada a string original
  - qtd     : quantidade maxima que deve ter a string no retorno
  - posicao : se a string sera adicionada a direita ou a esquerda (D - E)
 Retorno: string original com a adicao das strings solicitadas.
*/
/******************************************************************************/
   function adicionaCaracter(string, charAdd, qtd , posicao){
      var adicionar = "";
      for( i=string.length; i < qtd; i++ ) {
         adicionar += charAdd;
      }
      if (posicao == "D") {
         return string + adicionar;
      } else if (posicao == "E")  {
         return adicionar + string;
      } else {
         return string;
      }
   }




/**************************************************************************************************/
/*      Funcao: imgDbManager(acao, NmeCampo, TituloCampo, tamCampo, extAceitas){
        Parametros:
                - acao: string contendo a descrição da ação que vai ser executada
                - NmeCampo: string contendo o nome do campo
                - TituloCampo: string contendo o título do campo
                - tamCampo: numerico contendo o tamanho do campo para alteração do arquivo
                - extAceitas: array com as extensoes que são aceitas pelo campo do arquivo
        Retorno: nenhum
        Descricao: Exibe ferramentas pra manipular imagens como cadastro, alteração e exclusão
*/
/**************************************************************************************************/
   function imgDbManager(acao, NmeCampo, TituloCampo, tamCampo, arrayExtAceitas){
     layer = document.getElementById('LAYER_'+NmeCampo);
     var arrayExtAceitasOrig = arrayExtAceitas;

     var auxExt = '';
     for(var i=0; i<arrayExtAceitas.length; i++){
        if ( ( i > 0 ) && ( arrayExtAceitas.charAt(i) == "'" ) ) {
           if ( arrayExtAceitas.charAt(i-1) == "\\" ) {
              auxExt = auxExt + arrayExtAceitas.charAt(i);
           } else {
              auxExt = auxExt + "\\\'";
           }
        } else {
           auxExt = auxExt + arrayExtAceitas.charAt(i);
        }
     }

     arrayExtAceitas = auxExt;

     eval("var imagem = IMAGEM_"+NmeCampo+";");
     if ( acao == 'troca_imagem' ) {
        layer.innerHTML = '    <div id="div_Img_'+NmeCampo+'"><input class="formulario" type="file" name="'+NmeCampo+'" size="'+tamCampo+'" onblur="getExtensaoArq(this, '+arrayExtAceitasOrig+')"><br>'+
                          '     <a href="javascript:void(0)" onclick="imgDbManager(\'\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\')"><span class="fonte_formato">não alterar imagem</span></a></div>';
     /* } else if ( acao == 'exclui_imagem' ) {
        layer.innerHTML = ' <table border=\"0\" cellpadding=\"0\" cellspacing=\"3\">'+
                          '   <tr>'+
                          '     <td>'+
                          '       <table border=\"0\" class=\"bordaImg\" cellpadding=\"0\" cellspacing=\"3\">'+
                          '         <tr>'+
                          '            <td align=\"center\" valign=\"middle\"><img src=\"../imagens/sem_imagem.gif\"><input type=\"hidden\" name=\"'+NmeCampo+'\"></td>'+
                          '         </tr>'+
                          '       </table>'+
                          '     </td>'+
                          '     <td>'+
                          '       <div id="div_Img_'+NmeCampo+'">'+
                          '       <table border=\"0\" cellpadding=\"0\" cellspacing=\"5\">'+
                          '         <tr>'+
                          '            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\')\"><span class=\"fonte_normal\">não excluir imagem</a></span></td>'+
                          '         </tr>'+
                          '       </table>'+
                          '       </div>'+
                          '     </td>'+
                          '   </tr>'+
                          ' </table>';
        */
     } else {
        layer.innerHTML = ' <table border=\"0\" cellpadding=\"0\" cellspacing=\"3\">'+
                          '   <tr>'+
                          '     <td>'+
                          '       <table border=\"0\" class=\"bordaImg\" cellpadding=\"0\" cellspacing=\"3\">'+
                          '         <tr>'+
                          '            <td>'+imagem+'</a></td>'+
                          '         </tr>'+
                          '       </table>'+
                          '     </td>'+
                          '     <td>'+
                          '       <div id="div_Img_'+NmeCampo+'"> '+
                          '       <table border=\"0\" cellpadding=\"0\" cellspacing=\"5\">'+
                          '         <tr>'+
                          '            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'troca_imagem\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\')\"><span class=\"fonte_normal\">alterar imagem</span></a><input type=\"hidden\" value=\"img_nao_alterada\"  name=\"'+NmeCampo+'\"></td>'+
                          '         </tr>'+
                          
//                          '         <tr>'+
//                          '            <td><a href=\"javascript: void(0)\" onclick=\"imgDbManager(\'exclui_imagem\', \''+NmeCampo+'\', \''+TituloCampo+'\', \''+tamCampo+'\', \''+arrayExtAceitas+'\')\"><span class=\"fonte_normal\">excluir imagem</a></span></td>'+
//                          '         </tr>'+
                          '       </table>'+
                          '       </div> '+
                          '     </td>'+
                          '   </tr>'+
                          ' </table>';
     }
  }



  var nmeCampoDivImg = new Array();

  function trataTravamentoImagens(){
    for (var i=0; i<nmeCampoDivImg.length; i++) {
       div = document.getElementById('div_Img_'+nmeCampoDivImg[i]);
       if (div != null) {
          if ( div.style.display == '' ) {
             div.style.display = 'none';
          } else {
             div.style.display = '';
          }
       }
    }
  }
  


/**************************************************************************************************/
/*      Funcao: retiraAcentos(texto){
        Parametros:
                   - texto: campo string com o conteúdo a ser verificado
        Retorno: string convertida em sem acentuação
        Descricao: Converte uma string para maiúsculo e remove acentuações e caracteres delimitadores de String
*/
/**************************************************************************************************/
   function retiraAcentos(texto){
      texto = texto.toUpperCase();    
      var novoTexto = '';   
      for (i=0; i<texto.length; i++) {
         switch (texto.charAt(i)) {
            case "Á" : novoTexto = novoTexto + 'A'; break;
            case "É" : novoTexto = novoTexto + 'E'; break;
            case "Í" : novoTexto = novoTexto + 'I'; break;
            case "Ó" : novoTexto = novoTexto + 'O'; break;
            case "Ú" : novoTexto = novoTexto + 'U'; break;
            case "Ý" : novoTexto = novoTexto + 'Y'; break;
            
            case "Ä" : novoTexto = novoTexto + 'A'; break;
            case "Ë" : novoTexto = novoTexto + 'E'; break;
            case "Ï" : novoTexto = novoTexto + 'I'; break;
            case "Ö" : novoTexto = novoTexto + 'O'; break;
            case "Ü" : novoTexto = novoTexto + 'U'; break;
            case "Ÿ" : novoTexto = novoTexto + 'Y'; break;
            
            case "À" : novoTexto = novoTexto + 'A'; break;                 
            case "È" : novoTexto = novoTexto + 'E'; break;
            case "Ì" : novoTexto = novoTexto + 'I'; break;
            case "Ò" : novoTexto = novoTexto + 'O'; break;
            case "Ù" : novoTexto = novoTexto + 'U'; break;               
            
            case "Â" : novoTexto = novoTexto + 'A'; break;                           
            case "Ê" : novoTexto = novoTexto + 'E'; break;
            case "Î" : novoTexto = novoTexto + 'I'; break;
            case "Ô" : novoTexto = novoTexto + 'O'; break;
            case "Û" : novoTexto = novoTexto + 'U'; break;
            
            case "Ã" : novoTexto = novoTexto + 'A'; break;
            case "Õ" : novoTexto = novoTexto + 'O'; break;
            case "Ñ" : novoTexto = novoTexto + 'N'; break;
            
            case "Ç" : novoTexto = novoTexto + 'C'; break;
            
            default: novoTexto = novoTexto + texto.charAt(i);
         }
      }

      return novoTexto;
   }


                            

//*****************************************************************************
//* Funções o <tr> da lista
//*****************************************************************************
                var objOn=null;

//*****************************************************************************
//* Utilizado para mudar o estilo conforme passa-se sobre o item
//*****************************************************************************
    function ChangeClass(obj, classe) {
            if (!obj.contains(event.fromElement)) {
               if (obj.className != 'gridListSelected') {
                 obj.className=classe+'On';  //usa o estilo que indica que está sobre ele
               }
            }
    }

//*****************************************************************************
//* Utilizado para mudar o estilo ao default após ter mudado de item (chamado pela função ChangeClass()
//*****************************************************************************
    function ChangeClassOff(obj,classe) {
            if (!obj.contains(event.toElement)) {
               if (obj.className != 'gridListSelected') {
                  obj.className=classe;
               }
            }
    }



/**************************************************************************************************/
/*      Funcao: habilitaCampos(form){
        Parametros:
                - form: Formulário em que seus campos serão ativados/desativados
        Retorno: nenhum
        Descricao: Desativa/Ativa todos os campos de um formulário
*/
/**************************************************************************************************/
   function habilitaCampos(form){
      for (var i=0; i<form.elements.length; i++) {
         form.elements[i].disabled = !form.elements[i].disabled;
         if ( form.elements[i].type != "button") {
            if ( (form.elements[i].type != "radio") && (form.elements[i].type != "checkbox") ){
               if (form.elements[i].disabled) {
                  form.elements[i].style.border = "1px solid #CCCCCC";
               } else {
                  form.elements[i].style.border = "1px solid #BFB8BF";
               }
            }
            if (form.elements[i].disabled) {
               form.elements[i].style.backgroundColor = "#ECECEC";
            } else {
               form.elements[i].style.backgroundColor = "#FFFFFF";
            }
         }
      }
   }


/**************************************************************************************************/
/*      Funcao: habilitaCampo(campo){
        Parametros:
                - campo: Campo será ativado/desativado
        Retorno: nenhum
        Descricao: Desativa/Ativa um determinado campo
*/
/**************************************************************************************************/
   function habilitaCampo(campo){
      if ( (campo.disabled) || (campo.readOnly) ) {
         campo.style.border = "1px solid #CCCCCC";
         campo.style.backgroundColor = "#ECECEC";
      } else {
         campo.style.border = "1px solid #BFB8BF";
         campo.style.backgroundColor = "#FFFFFF";
      }
   }


/**************************************************************************************************/
/*      Funcao: selecionaItemCombo(form){
        Parametros:
                - campo: Campo do tipo SELECT
                - valor: Valor a ser selecionado no SELECT
        Retorno: nenhum
        Descricao: Seleciona um valor em um Select
*/
/**************************************************************************************************/
   function selecionaItemCombo(campo, valor){
      for (var i=0; i<campo.options.length; i++) {
         if (campo.options[i].value == valor) {
            campo.selectedIndex = i;
            break;
         }
      }
   }



/**************************************************************************************************/
/*      Funcao: selecionaTodosChecks(form){
        Parametros:
                - form: Formulario onde os checkboxes estão
        Retorno: nenhum
        Descricao: Muda o atributo para CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
   function selecionaTodosChecks(form){
      for (var i=0; i<form.elements.length; i++) {
         if ( form.elements[i].type == "checkbox") {
            form.elements[i].checked = true;
         }
      }
   }

/**************************************************************************************************/
/*      Funcao: inverteSelecaoChecks(form){
        Parametros:
                - form: Formulario onde os checkboxes estão
        Retorno: nenhum
        Descricao: Inverte o estado de CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
   function inverteSelecaoChecks(form){
      for (var i=0; i<form.elements.length; i++) {
         if ( form.elements[i].type == "checkbox") {
            form.elements[i].checked = !form.elements[i].checked;
         }
      }
   }

/**************************************************************************************************/
/*      Funcao: retiraSelecaoCkecks(form){
        Parametros:
                - form: Formulario onde os checkboxes estão
        Retorno: nenhum
        Descricao: Muda o atributo para NÃO CHECADO de todos os checkboxes de um formulário
*/
/**************************************************************************************************/
   function retiraSelecaoCkecks(form){
      for (var i=0; i<form.elements.length; i++) {
         if ( form.elements[i].type == "checkbox") {
            form.elements[i].checked = false;
         }
      }
   }

/**************************************************************************************************/
/*      Funcao: existeCheckSelecionado(form){
        Parametros:
                - form: Formulario onde os checkboxes estão
        Retorno: existe ou não um campo checkbox selecionado
        Descricao: Retorna a existencia ou não de um campo checkbox selecionado
*/
/**************************************************************************************************/
   function existeCheckSelecionado(form){
      var retorno = false;
      for (var i=0; i<form.elements.length; i++) {
         if ( form.elements[i].type == "checkbox") {
            if (form.elements[i].checked ) {
               retorno = true;
               break;
            }
         }
      }
      return retorno;
   }



/**************************************************************************************************/
/*      Funcao: redimensionaJanelaCentralizando(width, height){
        Parametros:
                - width: nova largura
                - height: nova altura
        Retorno: nenhum
        Descricao: Redimensiona uma janela popup e a centraliza no desktop
*/
/**************************************************************************************************/
function redimensionaJanelaCentralizando(width, height){
   var screenW = screen.availWidth;
   var screenH = screen.availHeight;
   var winW;
   var winH;

   if ( (width != '') || (height != '') ) {
      self.resizeTo(width, height);
   }

   if (parseInt(navigator.appVersion)>3) {
      if (navigator.appName=="Netscape") {
         winW = window.innerWidth;
         winH = window.innerHeight;
      }
      if (navigator.appName.indexOf("Microsoft")!=-1) {
         winW = document.body.offsetWidth;
         winH = document.body.offsetHeight;
      }
   }

   self.moveTo(( (screenW - winW) / 2 ), ( (screenH - winH) / 2 ) - 15);
}


function findPosX(obj) {
        var curleft = 0;
        if (obj.offsetParent)
        {
                while (obj.offsetParent)
                {
                        curleft += obj.offsetLeft
                        obj = obj.offsetParent;
                }
        }
        else if (obj.x)
                curleft += obj.x;
        return curleft;
}

function findPosY(obj){
        var curtop = 0;
        if (obj.offsetParent)
        {
                while (obj.offsetParent)
                {
                        curtop += obj.offsetTop
                        obj = obj.offsetParent;
                }
        }
        else if (obj.y)
                curtop += obj.y;
        return curtop;
}



function preencheCombo2Niveis(Indice, CampoDest, arrayDados) {
   while ( CampoDest.options.length >0 ) {
      CampoDest.options[0] = null;
   }

   CampoDest.options[CampoDest.options.length] = new Option();

   if (parseInt(Indice) >= 0) {
      for (i=0; i<arrayDados[Indice].length; i++) {
         CampoDest.options[CampoDest.options.length] = new Option(arrayDados[Indice][i][1], arrayDados[Indice][i][0]);
      }
   }

}

function converteMaiuscula(event){
    var isNav = false, isIE = false;
    if ( navigator.appName.indexOf("Netscape") != -1 ){
       isNav = true;
    }
    else if ( navigator.appName.indexOf("Microsoft") != -1 ) {
       isIE = true;
    }

   (isNav)?tecla = event.which:tecla = event.keyCode;
   tecla = String.fromCharCode(tecla).toUpperCase();
   event.keyCode = tecla.charCodeAt(0);
}

function converteMinuscula(event){
    var isNav = false, isIE = false;
    if ( navigator.appName.indexOf("Netscape") != -1 ){
       isNav = true;
    }
    else if ( navigator.appName.indexOf("Microsoft") != -1 ) {
       isIE = true;
    }

   (isNav)?tecla = event.which:tecla = event.keyCode;
   tecla = String.fromCharCode(tecla).toLowerCase();
   event.keyCode = tecla.charCodeAt(0);
}
