/*************************************************************************************************************************************************
Parametros extras
  FrmFormat                       = Formata campos
  Autotab      maxlength          = Faz a tabulaÃ§Ã£o automatica dos campos assim q cehga no maxlength ex.:"Autotab='documento.frm.proxcampo'"
  FmtUpperCase                    = O campo so aceita valores em caixa auta
  FmtLowerCase                    = O campo so aceita valores em caixa baixa
  FmtFloatBrasil                  = Aplica o campo com Numerico float                ex.: FmtFloatBrasil=true
  FmtDate                         = Aplica o campo como data                         ex.: FmtDate=true
  FmtFilter                       = Aplica o campo com filtro                        ex.: FmtFilter='0-9'

--> Functions existentes ----------->DescriÃ§Ã£o<------------------------------------->Exemplo<---------------------------------------->Return<--
  str_trim(aString)               = tira espaÃ§o da direita e da esquerta
  str_rtrim(aString)              = tira espaÃ§o da direita
  str_trim(aString)               = tira espalo da esquerda
  isCpf(numCPFCNPJ)               = testa se e cpf valido
  isCnpj(numCPFCNPJ)              = testa se e cnpj valido
  isCpfCnpj(numCPFCNPJ)           = testa se e cnpj ou cpf valido
  isDate(sdata)                   = testa se a data e valida                         ex.: isDate('11/19/1979')
  FtmDateBrasil(pdata)            = Formata um valor data                            ex.: 11/09/1679 
  FtmDateBrasilToAmeric(databr)   = Formata valor data do fmt Bras p/ fmt Americ     ex.: 05/24/1679      ('MM/dd/yyyy')
  FmtFloatBrasilToBrasilP(numero) = Coloca pontos de 3 em 3 casas                    ex.: 1.000.345,59
  FmtFloatBrasilPToBrasil(numero) = Tira os pontos de 3 em 3 dos campos              ex.:1000345,59
  FmtFloatAmericToBrasil(numero)  = Troca o padrao apericano por brasileiro          ex.: 1.123,45
  FmtFloatBrasilToAmeric(numero)  = Troca o padrao brasileiro pelo apericano         ex.:1123.45
  FrmValidationElement(oElement)  = Aplica os parametros extras no campo especifico  ex.:FrmValidationElement(document.frm.txt1);
  FrmValidation_all()             = Aplica os pramentros esxtras em todos os campos  ex.:FrmValidation_all();
  toRound                         = arrendonda nÂº decimal para uma qde de casas      ex.:toRound(10.66666, 2) = 10.66
  isEmail(semail)                 = testa se Ã© um email vÃ¡lido                       ex.: isEmail(document.frmcad.email)              true or false


*** A Implementar: ********       *********************                               ****************************
  FtmHora(phora)                  = Formata um valor hora                             ex.: 23:00

*************************************************************************************************************************************************/
function toRound(number,X) {
// rounds number to X decimal places, defaults to 2
X = (!X ? 2 : X);
return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
//-----------------------------------------------------------------------------------------------------------------------

function str_ltrim(aString) {
  return aString.replace(/^[\s]+/g,"");
}
//-----------------------------------------------------------------------------------------------------------------------

function str_rtrim(aString) {
  return aString.replace(/[\s]+$/g,"");
}
//-----------------------------------------------------------------------------------------------------------------------

function str_trim(aString) {
  result = String( aString ).replace( /^[\s]+/g , "" );
  return result.replace( /[\s]+$/g,"" );
}
//-----------------------------------------------------------------------------------------------------------------------

function FtmDateBrasil(pdata) {
  var today = new Date();
  var anoatual = today.getFullYear() + '0';
  var tempn = pdata.split('/');
  if(!tempn[0]){
    tempn[0] =  '';
    return '';
    exit;
  }
  else if(tempn[0].match('[^0-9]')){
    tempn[0] =  '';
    return '';
    exit;
  }
  else{
    while(tempn[0].length<2)
      tempn[0] = '0' + tempn[0];
    tempn[0] = tempn[0].substr(0,2);
  }
  if(!tempn[1]){
    tempn[1] =  '';
    return '';
    exit;
  }
  else if(tempn[1].match('[^0-9]')){
    tempn[1] =  '';
    return '';
    exit;
  }
  else{
    while(tempn[1].length<2)
      tempn[1] = '0' + tempn[1];
    tempn[1] = tempn[1].substr(0,2);
  }
  if(!tempn[2]){
    tempn[2] = anoatual.substr(0,4);
  }
  else if(tempn[2].match('[^0-9]')){
    tempn[2] = anoatual.substr(0,4);
  }
  else{
    var num = tempn[2].length;
    num = 4 - num;
    tempn[2] = anoatual.substr(0,num) + tempn[2];
    tempn[2] = tempn[2].substr(0,4);
  }    
  return tempn[0] + '/' + tempn[1] + '/' + tempn[2];
}
//-----------------------------------------------------------------------------------------------------------------------

function FtmDateBrasilToAmeric(databr) {
   dia= databr.substring(0,2);
   mes= databr.substring(3,5);
   ano= databr.substring(6,10);
   dataam= mes + "/" + dia + "/" + ano;
   dataam= new Date (dataam);
   return dataam;
 }
//-----------------------------------------------------------------------------------------------------------------------

function FmtFloatBrasilToBrasilP(numero) {
  numero = ' ' + numero;
  numero = numero.replace(/^[\s]+/g,"");
  numero = numero.replace(/[\s]+$/g,"");
  while(numero.match('[.]')){
    numero = numero.replace('.','');
  }  
  var tempn = numero.split(',');
  if(!tempn[1]){
    tempn[1] =  '00';
  }
  else if(tempn[1].match('[^0-9]')){
    tempn[1] =  '00';
  }
  else{
    tempn[1] += '00';
    tempn[1] = tempn[1].substr(0,2);
  }
  if(!tempn[0]){
    tempn[0] = '0';
  }
  else if(tempn[0]==''){
    tempn[0] = '0';
  }
  else if(tempn[0].match('[^0-9]')){
    tempn[0] = '0';  
  }
  var j = 1;
  var parte1 = '';
  for(var i=tempn[0].length-1;i>=0;i--){
    parte1 = tempn[0].substr(i,1) + parte1;
    if((j==3)&&(i!=0)){
      parte1 = '.' + parte1;
      j = 0;
    }
    j++;
  } 
  return parte1 + ',' + tempn[1];
}
//-----------------------------------------------------------------------------------------------------------------------

function FmtFloatBrasilPToBrasil(numero) {
  numero = ' ' + numero;
  numero = numero.replace(/^[\s]+/g,"");
  numero = numero.replace(/[\s]+$/g,"");
  while(numero.match('[.]')){
    numero = numero.replace('.','');
  }  
  var tempn = numero.split(',');
  if(!tempn[1]){
    tempn[1] =  '00';
  }
  else if(tempn[1].match('[^0-9]')){
    tempn[1] =  '00';
  }
  else{
    tempn[1] += '00';
    tempn[1] = tempn[1].substr(0,2);
  }
  if(!tempn[0]){
    tempn[0] = '0';
  }
  else if(tempn[0]==''){
    tempn[0] = '0';
  }
  else if(tempn[0].match('[^0-9]')){
    tempn[0] = '0';  
  }
  return tempn[0] + ',' + tempn[1];
}
//-----------------------------------------------------------------------------------------------------------------------

function FmtFloatAmericToBrasil(numero) {
  numero = ' ' + numero;
  numero = numero.replace(/^[\s]+/g,"");
  numero = numero.replace(/[\s]+$/g,"");
  var tempn = numero.split('.');
  if(!tempn[1])
  {
    tempn[1] =  '00';
  }
  else
  {
    tempn[1] = tempn[1] + '00';
    tempn[1] = tempn[1].substr(0,2);
  }
  if(!tempn[0])
  {
    tempn[0] = '0';
  }
  if(tempn[0]=='')
  {
    tempn[0] = '0';
  }
  var j = 1;
  var parte1 = '';
  for(var i=tempn[0].length-1;i>=0;i--)
  {
    parte1 = tempn[0].substr(i,1) + parte1;
    if((j==3)&&(i!=0))
    {
      parte1 = '.' + parte1;
      j = 0;
    }
    j++;
  } 
  return parte1 + ',' + tempn[1];
}
//-----------------------------------------------------------------------------------------------------------------------

function FmtFloatBrasilToAmeric(numero) {
  numero = ' ' + numero;
  numero = numero.replace(/^[\s]+/g,"");
  numero = numero.replace(/[\s]+$/g,"");
  while(numero.match('[.]'))
  {
    numero = numero.replace('.','');
  } 
  numero = numero.replace(',','.');
  var tempn = numero.split('.');
  if(!tempn[1])
  {
    tempn[1] =  '00';
  }
  else
  {
    tempn[1] += '00';
    tempn[1] = tempn[1].substr(0,2);
  }
  if(!tempn[0])
  {
    tempn[0] = '0';
  }
  if(tempn[0]=='')
  {
    tempn[0] = '0';
  }
  var fim = tempn[0] + '.' + tempn[1]; 
  return parseFloat(fim);
}
//-----------------------------------------------------------------------------------------------------------------------

function FrmValidationElement(oElement) {
  if(!oElement.bProcessed){
    //*** BEGIN OnBlur ********************************************************
    if(oElement.onblur){
      oElement.fblur=oElement.onblur;
    } //end id
    oElement.onblur=function( event ){
    try {
      // -------------------------------------------------------------------
      if(this.fblur && this.fblur()==false){
        event.returnValue=false;
      } //end id
      var sFmtUpperCase=this.getAttribute("FmtUpperCase");
      if(sFmtUpperCase){
        this.value = this.value.toUpperCase();
      } // end if
      var sFmtLowerCase=this.getAttribute("FmtLowerCase");
      if(sFmtLowerCase){
        this.value = this.value.toLowerCase();
      } // end if
      /*var sFmtfilter=this.getAttribute("Fmtfilter");
      if(sFmtfilter){
       var re=new RegExp('[^'+sFmtfilter+']');
       var sFrmFormat=oElement.getAttribute("FrmFormat");
       if(sFrmFormat){
        for(var i=0;i<sFrmFormat.length;i++){
         if(sFrmFormat.substr(i,1)!='*'){
          if(this.value.substr(i,1)!= sFrmFormat.substr(i,1)){
           this.value = '';
           break;
          }
         }
         else{
          if(re.test(this.value.substr(i,1))){
           this.value = '';
           break;
          } // end if
         }
        }
       }
       else{
        if(re.test(this.value)){
         oElement.value = '';
        } // end if
        event.returnValue=false;
       } // end if
      } // end if*/
      // -------------------------------------------------------------------
      } catch (err) {}

      var sFmtFloatBrasil=this.getAttribute("FmtFloatBrasil");
      if(sFmtFloatBrasil){
        this.value = FmtFloatBrasilToBrasilP(this.value);
      } // end if
      var sFmtDate=this.getAttribute("FmtDate");
      if(sFmtDate){
        this.value = FtmDateBrasil(this.value);
      } // end if	  
    } //*** END OnBlur ********************************************************

    //*** BEGIN OnFocus *******************************************************
    if(oElement.onfocus){
      oElement.ffocus=oElement.onfocus;
    } //end if
    oElement.onfocus=function(){
      if(this.ffocus && this.ffocus()==false){
        event.returnValue=false;
      } //end if
      var sFmtFloatBrasil=this.getAttribute("FmtFloatBrasil");
      if(sFmtFloatBrasil){
        this.value = FmtFloatBrasilPToBrasil(this.value);
        this.select();
      } // end if
    } // end function onfocus
    //*** END OnFocus *********************************************************

    //*** BEGIN OnKeyPress ****************************************************
    
    if(oElement.onkeypress){
      oElement.fKeypress=oElement.onkeypress;
    } // end if
    if ( typeof( window.captureEvents ) == 'function' ) window.captureEvents( Event.KEYPRESS );
    oElement.onkeypress=function( event ){
      var keyCode  = ( ! window.event ) ? event.which : window.event.keyCode;
      pressedKey  = String.fromCharCode( keyCode );
      if ( pressedKey == '\r' || parseInt( pressedKey.charCodeAt( 0 ) ) == 0 || parseInt( pressedKey.charCodeAt( 0 ) ) == 8 || pressedKey == '' ) {
        return true;
      }
      if(this.fKeypress && this.fKeypress()==false){
        event.returnValue=false;
      } // end if

      var sFmtfilter=this.getAttribute("Fmtfilter");
      if ( sFmtfilter ) {
        var sKey = String.fromCharCode( keyCode );
        var re   = new RegExp( '[^' + sFmtfilter + ']' );
        if ( re.test( sKey ) ) {
          try {
            event.preventDefault();
          } catch ( err ) {
            window.event.returnValue = false;
          }
          return false
        }
      }

      var sFmtUpperCase=this.getAttribute("FmtUpperCase");
      if(sFmtUpperCase){
        var sKey=String.fromCharCode(event.keyCode);
        sKey = sKey.toUpperCase();
        event.keyCode=sKey.charCodeAt(0);
      } // end if

      var sFmtLowerCase=this.getAttribute("FmtLowerCase");
      if(sFmtLowerCase){
        var sKey=String.fromCharCode(event.keyCode);
        sKey = sKey.toLowerCase();
        event.keyCode=sKey.charCodeAt(0);
      } // end if

      var sFrmFormat=this.getAttribute("FrmFormat");
      if( sFrmFormat ) {
        var stext        = this.value;
        var sKey         = String.fromCharCode( keyCode );
        var strSelection = ( document.selection ) ? document.selection.createRange().text : this.value.substr( this.selectionStart , this.selectionEnd );
        if ( strSelection != '' ) {
          this.value = '';
          try {
            event.preventDefault();
          } catch ( err ) {
            window.event.returnValue = false;
          }
          //document.selection.clear();
        } else {
          if ( sFrmFormat.substr( stext.length , 1 ) == '*' ) {
            if ( ( sFrmFormat.substr( stext.length + 1 , 1 ) != '*' ) && ( sFrmFormat.substr( stext.length + 1 , 1 ) != '' ) ) {
              this.value = this.value + sKey + sFrmFormat.substr( stext.length + 1 , 1 );
              try {
                event.preventDefault();
              } catch ( err ) {
                window.event.returnValue = false;
              }
            } else {
              //event.returnValue=true;
            }
          } else {
            if ( stext.length + 1 <= sFrmFormat.length ){
              this.value = this.value + sFrmFormat.substr( stext.length , 1 ) + sKey;
              //keyCode = 0;
            }
            try {
              event.preventDefault();
            } catch ( err ) {
              window.event.returnValue = false;
            }
          }
        }
      }
      var sAutotab=this.getAttribute("Autotab");
      if(sAutotab){
       e = this.form.elements;
       if(this.value.length+1==this.getAttribute("maxlength")) {
        try {
         var elementobj = eval(sAutotab);
         if(event.keyCode!=0){
          var sKey=String.fromCharCode(event.keyCode);
          this.value = this.value + sKey;
         }
         event.returnValue=false;
         elementobj.focus();
         elementobj.select();
        } // try
        catch (ee){
         for(i=0; i<e.length; i++){
          if(e[i]==this){
           if(event.keyCode!=0){
            var sKey=String.fromCharCode(event.keyCode);
            this.value = this.value + sKey;
           }
           event.returnValue=false;
           try{ 
           if(i+1<e.length){
            e[i+1].focus();
            e[i+1].select();
           }
           else{
            e[0].focus();
            e[0].select();
            }
           }//try
           catch (eee){  }
          }
         } // for
        } // catch
       } // if
      } // end if

      var sFmtFloatBrasil=this.getAttribute("FmtFloatBrasil");
      if(sFmtFloatBrasil){
        var sKey=String.fromCharCode(event.keyCode);
        var re=new RegExp('[^0-9,]|(,[0-9]*,)');
        var atestar = this.value + sKey
        if(sKey!="\r" && re.test(atestar)){
          event.returnValue=false;
        } // end if
        event.keyCode=sKey.charCodeAt(0);
      } // end if

      var sFmtDate=this.getAttribute("FmtDate");
      if(sFmtDate){
        this.maxlength = '10';
        var sKey=String.fromCharCode(event.keyCode);
        var re=new RegExp('[^0-9/]|(/[0-9]*/[0-9]*/)');
        var atestar = this.value + sKey
        if(sKey!="\r" && re.test(atestar)){
          event.returnValue=false;
        } // end if
        else{
          if(document.selection.createRange().text==''){
            atestar = this.value;
            if(sKey!='/'){
              if((atestar.length==1)||(atestar.length==4)){
                this.value += sKey + '/';
                event.returnValue=false;
              } // end if
              else if((atestar.length==2)||(atestar.length==5)){
                this.value += '/';
              } // end else if
            } // end if
            else {
              if((atestar.length==0)||(atestar.length==3)){
                event.returnValue=false;
              } // end if
              else if(atestar.length==1){
                this.value = '0' + this.value;
              } // end else if
              else if(atestar.length==4){
                this.value = this.value.substr(0,3)+ '0' + this.value.substr(3,1);
              } // end else if
            } // end else
          } // end if
        } // end else
        event.keyCode=sKey.charCodeAt(0);
      } // end if data
    } //*** END OnKeyPress ******************************************************
  } // end if oElement.bProcessed
} // end function

function FrmValidation_all() {
  var i,iForms=document.forms.length;
  for(i=0; i<iForms; i++){
    var oForm=document.forms[i];
    if(!oForm.bProcessed){
      var j, iElements=oForm.elements.length;
      for(j=0; j<iElements; j++){
	    var oElement=oForm.elements[j];
	    //alert(oElement.name);//localName
	    FrmValidationElement(oElement);	
      } //end for
    } //end if
  } //end for
} //end function

// Carrega validação dos formulários ao carregar a página
// utiliza função addEvent do dc_framework.js
addEvent(window,'load',FrmValidation_all);
