// Inclui estilos de acordo com o Navegador
function MontaCSS()
{
  var sLinha;
  var sNavegador = navigator.appName;
  if (sNavegador == "Microsoft Internet Explorer")
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ie.css>";
  else
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ns.css>";
  document.write(sLinha);
}

function imprimir(){
// Descrição: Função de impressão
	var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
	document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
	window.onerror=printerrortrap;  // Configura o tratamento de erros na impressão do documento
	WebBrowser1.ExecWB(6, 2);
	window.onerror = null ;  //  Libera o tratamento de erros
	WebBrowser1.outerHTML = "";
}

function printerrortrap(){
// Descrição: Função de tratamento de erro de impressão
	alerta("Impressão do documento não ocorreu.");
	window.onerror = null ;
	WebBrowser1.outerHTML="";
	return true;
}

// Imprime a pagina atual
var da = (document.all) ? 1 : 0;
var pr = (window.print) ? 1 : 0;
var mac = (navigator.userAgent.indexOf("Mac") != -1);

function printPage()
{
  if (pr) // NS4, IE5
    window.print()
  else if (da && !mac) // IE4 (Windows)
    vbPrintPage()
  else // other browsers
    alert("Desculpe seu browser não suporta esta função. Por favor utilize a barra de trabalho para imprimir a página.");
  return false;
}


function MontaCSSMenu()
{
  var sLinha;
  var sNavegador = navigator.appName;
  if (sNavegador == "Microsoft Internet Explorer")
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ie_menu.css>";
  else
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ns_menu.css>";
  document.write(sLinha);
}

function MontaCSSInclude()
{
  var sLinha;
  var sNavegador = navigator.appName;
  if (sNavegador == "Microsoft Internet Explorer")
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ie.css>";
  else
    sLinha = "<link rel=STYLESHEET type=text/css href=estilo/stylos_ns.css>";
  document.write(sLinha);
}

// Move o cursos para o primeiro campo do 1º formulário
function placeFocus()
{
  if (document.forms.length > 0)
  {
    var field = document.forms[0];
    for (i = 0; i < field.length; i++)
    {
      if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type == "password") || (field.elements[i].type.toString().charAt(0) == "s"))
      {
        document.forms[0].elements[i].focus();
        break;
      }
    }
  }
}

/*********************************************************************************
 Função para mascarar o número no momento em que o usuário está digitando
 O número permanece sempre no formato xxxxx,xx
*********************************************************************************/
/*********************************************************************************
 Exemplo: onKeyPress="return(formataNumeroDecimais(this,'.',',',event))"
 retorna 1.057.689,04
*********************************************************************************/
function mascara_campo_numero(campo, sep_mil, sep_dec, evento)
{
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? evento.which : evento.keyCode;

  if (whichCode == 13) return true;  // Enter
  if (whichCode == 0) return true;
  if (whichCode == 1) return true;
  if (whichCode == 2) return true;
  if (whichCode == 3) return true;
  if (whichCode == 4) return true;
  if (whichCode == 5) return true;
  if (whichCode == 6) return true;
  if (whichCode == 7) return true;
  if (whichCode == 8) return true;  // Backspace
  if (whichCode == 9) return true;
  if (whichCode == 10) return true;
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if (campo.value.length >= campo.maxLength) return false;  // Estourou a tamanho maximo do campo
  if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  len = campo.value.length;
  for(i = 0; i < len; i++)
      if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != sep_dec)) break;
  aux = '';
  for(; i < len; i++)
    if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len == 0) campo.value = '';
  if (len == 1) campo.value = '0'+ sep_dec + '0' + aux;
  if (len == 2) campo.value = '0'+ sep_dec + aux;
  if (len > 2)
  {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--)
    {
      if (j == 3)
      {
        aux2 += sep_mil;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    campo.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
      campo.value += aux2.charAt(i);
    campo.value += sep_dec + aux.substr(len - 2, len);
  }
  return false;
}

// Permite que sejam entrados apenas numeros para um determinado campo
function so_numero(campo, evento)
{

 if (campo.length ==0)
  campo.value=0;
 var key;
 var keychar;
 if (window.event)
  key = window.event.keyCode;
 else
  if (evento)
   key = evento.which;
  else
   return true;
 keychar = String.fromCharCode(key);
 if ((key==null) || (key==0) || (key==8) || (key==9)|| (key==13)|| (key==27) )
  return true;
 else
  if ((("0123456789").indexOf(keychar) > -1))
   return true;
  else
   return false;
}

// Mascara o campo data colocando automaticamente as barras e permite apenas a entrada de numeros no campo
function mascara_campo_data(campo, evento)
{
  if (so_numero(campo, evento))
  {
    var tecla = evento.keyCode;
    vr  = campo.value;
    vr  = vr.replace( "/", "" );
    vr  = vr.replace( "/", "" );
    tam = vr.length + 1;

    if ( tecla != 9 && tecla != 8 )
    {
      if ( tam > 2 && tam < 5 )
        campo.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
      if ( tam >= 5 && tam <= 10 )
        campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
    }
    return true;
  }
  else
    return false;
}

// Função que verifica se uma data é válida.

function ver_data(data, ano_ini, ano_fim)
{


  erro  = false;
  meses = new Array (31,28,31,30,31,30,31,31,30,31,30,31);

  if (data.length <10)
   erro = true;
  else
  {
    if ((data.substr(2,1) != "/") && (data.substr(5,1) != "/"))
    {
      erro = true;
    }
    else
    {
      d = parseFloat(data.substr(0,2));
      m = parseFloat(data.substr(3,2));
      a = parseFloat(data.substr(6,4));
      if (((d>0) && (d<32)) && ((m>0) && (m<13)) && ((a>=ano_ini) && (a<=ano_fim)))
      {
        if (m==2)
        {
          if (a%4==0)
          {
            if ((d<1) || (d>29))
              erro = true;
          }
          else
          {
            if ((d<1) || (d>meses[m-1]))
              erro = true;
          }
        }
        else
        {
          if ((d<1) || (d>meses[m-1]))
            erro = true;
        }
      }
      else
        erro = true;
    }
  }
  return (!erro);
}

//**********************************************************************************************
// Faz o chamada de alerta
// Opções:
// tipo: incluir, n_incluir, alterar, n_alterar, sn_excluir, excluir, n_excluir, form e unica
// chamada: erro, aviso, cc, sn
// Ex.: alertaAviso('Carro Sport','incluir','aviso');
// Ex.: alertaAviso('@Campo nome obrigatório@Campo idade Obrigatorio','form','erro');
// Ex.: alertaAviso('Inflatores corrigidos','unica','erro');
//**********************************************************************************************
function alertaAviso(objeto,tipo,chamada,sessao)
{
  var x = 350;
  var y = 200;
  var sessaoid = sessao.substr(10,6);
  var sArq = '../estrutura/principal.php?pg=4&'+sessao+'&tipo='+tipo+'&chamada='+chamada+'&obj='+objeto;
//  var sArq = '../include/mensagem.php?'+sessao+'&tipo='+tipo+'&chamada='+chamada+'&obj='+objeto;
  //var wVolta=false;
  //var sAux = "msga"+ sessaoid +" = window.open(sArq,'msga"+ sessaoid +"','width=300px,height=200px,resizable=1,scrollbars=0,left="+x+",top="+y+"');";
  //eval(sAux);
  mudaTelaMensagem(sArq);
}

function mudaTelaMensagem(sPag)
{
  parent.frames["telaMensagem"].location.replace(sPag);
}

function limpaTelaMensagem()
{
  parent.frames["telaMensagem"].location.replace('../estrutura/principal.php?pg=4');
}

// Descrição: Garante retorno numérico para entradas de strings
// toFloat('-12,345') -> -12.345
// toFloat('') -> 0
// toFloat('12.3') -> 12.3
// toFloat('-12.3') -> -12.3
// toFloat() -> 0
// toFloat('12,3') -> 12.3
// toFloat('-12,3') -> -12.3
// toFloat('abc') -> 0
function toFloat(strValor)
{
	if ( (strValor == null) || (strValor.length == 0) )
		return 0;
	if (!isNaN(strValor))
		return parseFloat(strValor);
	retorno = strValor;
  retorno = retorno.replace(".", "");
  retorno = retorno.replace(",", ".");
	if ( (retorno == "") || (isNaN(retorno)) )
		return 0;
	return parseFloat(retorno);
}

function mascara_valor(valor, sep_mil, sep_dec, decimais)
{
  retorno = '';
  valor = valor.toFixed(decimais);
  valor = valor.toString();
  var strCheck = '0123456789';
  len = valor.length;
  for(i = 0; i < len; i++)
      if ((valor.charAt(i) != '0') && (valor.charAt(i) != sep_dec)) break;
  aux = '';
  for(; i < len; i++)
    if (strCheck.indexOf(valor.charAt(i))!=-1) aux += valor.charAt(i);
  len = aux.length;
  if (len == 0) retorno = '';
  if (len == 1) retorno = '0'+ sep_dec + '0' + aux;
  if (len == 2) retorno = '0'+ sep_dec + aux;
  if (len > 2)
  {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--)
    {
      if (j == 3)
      {
        aux2 += sep_mil;
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    retorno = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
      retorno += aux2.charAt(i);
    retorno += sep_dec + aux.substr(len - 2, len);
  }
  return retorno;
}

function mascara_servico(campo, teclapres)
{

 tecla = teclapres.keyCode;

 vr = new String(campo.value);
 vr = vr.replace(".", "");

 tam = vr.length + 1 ;

 if (tecla != 9 && tecla != 8)
 {
  if (tam > 3 && tam < 5)
   campo.value = vr.substr(0, 1) + '.' + vr.substr(1, tam);
    if (tam >=5)
      campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
 }
}

function mascara_cpf(campo, teclapres)
{

 tecla = teclapres.keyCode;

 vr = new String(campo.value);
 vr = vr.replace(".", "");
 vr = vr.replace(".", "");
 vr = vr.replace("/", "");
 vr = vr.replace("-", "");

 tam = vr.length + 1 ;

 if (tecla != 9 && tecla != 8)
 {
  if (tam > 3 && tam < 7)
   campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
   if (tam >= 7 && tam < 10)
    campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
   if (tam >= 10 && tam < 14)
    campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
 }
}

function mascara_cnpj(campo, teclapres)
{

 tecla = teclapres.keyCode;

 vr = new String(campo.value);
 vr = vr.replace(".", "");
 vr = vr.replace(".", "");
 vr = vr.replace("/", "");
 vr = vr.replace("-", "");

 tam = vr.length + 1 ;

 if (tecla != 9 && tecla != 8)
 {
  if (tam > 2 && tam < 6)
   campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
   if (tam >= 6 && tam < 9)
    campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
   if (tam >= 9 && tam < 13)
    campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
   if (tam >= 13 && tam < 15)
    campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
 }
}

function verifica_cnpj(valor)
{
 aux1 = 0;
 aux2 = 0;
 aux3 = 1;
 aux4 = 0;
 for (i=0;i<valor.length-2;i++)
 {
  if ((valor.substr(i,1) != "/") && (valor.substr(i,1) != "-") && (valor.substr(i,1) != "."))
  {
   (aux3 < 5) ? aux4 = 6-aux3 : aux4 = 14-aux3;
   aux1 = aux1+(valor.substr(i,1)*aux4);
   (aux3 < 6) ? aux4 = 7-aux3 : aux4 = 15-aux3;
   aux2 = aux2+(valor.substr(i,1)*aux4);
   aux3++;
  }
 }
 resto = aux1-((Math.floor(aux1/11))*11);
 (resto < 2) ? dig1=0 : dig1=11-resto;
 aux2 = aux2+(2*dig1);
 resto = aux2-((Math.floor(aux2/11))*11);
 (resto < 2) ? dig2=0 : dig2=11-resto;
 aux = dig1+" "+dig2;
 aux = aux.substr(0,1)+aux.substr(2,1);
 if (aux != valor.substr(valor.length-2))
  return false;
 else
  return true;
}

function verifica_cpf(valor)
{
 erro = 0;
 aux1 = 0;
 aux2 = 0;
 aux3 = 1;
 for (i=0;i<valor.length-2;i++)
 {
  if ((valor.substr(i,1) != "/") && (valor.substr(i,1) != "-") && (valor.substr(i,1) != "."))
  {
   aux1 = aux1+(11-aux3)*valor.substr(i,1);
   aux2 = aux2+(12-aux3)*valor.substr(i,1);
   aux3++;
  }
 }
 resto = aux1-((Math.floor(aux1/11))*11);
 (resto < 2) ? dig1=0 : dig1=11-resto;
 aux2 = aux2+(2*dig1);
 resto = aux2-((Math.floor(aux2/11))*11);
 (resto < 2) ? dig2=0 : dig2=11-resto;
 aux = dig1+" "+dig2;
 aux = aux.substr(0,1)+aux.substr(2,1);
 if (aux != valor.substr(valor.length-2))
  return false;
 else
  if ((valor == "000.000.000-00") || (valor == "111.111.111-11") || (valor == "222.222.222-22") ||
  (valor == "333.333.333-33") || (valor == "444.444.444-44") || (valor == "555.555.555-55") ||
  (valor == "666.666.666-66") || (valor == "777.777.777-77") || (valor == "888.888.888-88") ||
  (valor == "999.999.999-99"))
   return false;
  else
   return true;
}

