function validaLogin(form)
{
  if (!isCPF(form.username.value) && !isCNPJ(form.username.value))
  {
    alert('Por favor, informe um CPF ou CNPJ válido.');
    form.username.focus();
    return false;
  }
  if (isEmpty(form.password.value) || 6 > form.password.value.length)
  {
    alert('Por favor, informe uma SENHA com pelo menos 6 caracteres.');
    form.password.focus();
    return false;
  }
  return true;
}

function validaRegistro(form)
{
  if (!isCPF(form.username.value) && !isCNPJ(form.username.value))
  {
    alert('Por favor, informe um CPF ou CNPJ válido.');
    form.username.focus();
    return false;
  }
  if (!isNumeric(form.numero_contrato.value))
  {
    alert ('Por favor, utilize apenas números no campo CONTRATO Nº.');
    form.numero_contrato.focus();
    return false;
  }
  if (!isEmail(form.email.value))
  {
    alert ('Por favor, informe um E-MAIL válido.');
    form.email.focus();
    return false;
  }
  if (isEmpty(form.password.value) || 6 > form.password.value.length)
  {
    alert('Por favor, informe uma SENHA com pelo menos 6 caracteres.');
    form.password.focus();
    return false;
  }
  if (form.password.value != form.passwordOk.value)
  {
    alert('As senhas informadas não conferem.');
    form.password.focus();
    return false;
  }
  return true;
}

function validaNovaSenha(form)
{
  if (!isCPF(form.username.value) && !isCNPJ(form.username.value))
  {
    alert('Por favor, informe um CPF ou CNPJ válido.');
    form.username.focus();
    return false;
  }
  if (!isEmail(form.email.value))
  {
    alert ('Por favor, informe um E-MAIL válido.');
    form.email.focus();
    return false;
  }
  if (isEmpty(form.password.value) || 6 > form.password.value.length)
  {
    alert('Por favor, informe uma SENHA com pelo menos 6 caracteres.');
    form.password.focus();
    return false;
  }
  if (form.password.value != form.passwordOk.value)
  {
    alert('As senhas informadas não conferem.');
    form.password.focus();
    return false;
  }
  return true;
}

function validaSenhas(form)
{
  if (!isEmpty(form.password.value) && 6 > form.password.value.length)
  {
    alert('Por favor, informe uma SENHA com pelo menos 6 caracteres.');
    form.password.focus();
    return false;
  }
  if (form.password.value != form.passwordOk.value)
  {
    alert('As senhas informadas não conferem.');
    form.password.focus();
    return false;
  }
  return true;
}

function validaContatos(form)
{
  if ( ( isEmpty(form.strTelefone.value) || 14 > form.strTelefone.value.length ) && ( isEmpty(form.strCelular.value) || 14 > form.strCelular.value.length ) && ( isEmpty(form.strTelefoneComercial.value) || 14 > form.strTelefoneComercial.value.length) )
  {
    alert('Por favor, informe pelo menos um TELEFONE com o CÓDIGO DE ÁREA.');
    form.strTelefone.focus();
    return false;
  }
  if (!isEmpty(form.strCelular.value) && 14 > form.strCelular.value.length)
  {
    alert('Por favor, ao informar o CELULAR o CÓDIGO DE ÁREA.');
    form.strCelular.focus();
    return false;
  }
  if (!isEmpty(form.strTelefoneComercial.value) && 14 > form.strTelefoneComercial.value.length)
  {
    alert('Por favor, ao informar o TELEFONE COMERCIAL inclua o CÓDIGO DE ÁREA.');
    form.strTelefoneComercial.focus();
    return false;
  }
  if (!isEmpty(form.strFax.value) && 14 > form.strFax.value.length)
  {
    alert('Por favor, ao informar o FAX inclua com o CÓDIGO DE ÁREA.');
    form.strFax.focus();
    return false;
  }
    if (!isEmail(form.strEmail.value))
  {
    alert ('Por favor, informe um E-MAIL válido.');
    form.strEmail.focus();
    return false;
  }
  if (!isEmpty(form.strEmailAlternativo.value))
  {
    if (!isEmail(form.strEmailAlternativo.value))
    {
      alert ('Por favor, informe um E-MAIL ALTERNATIVO válido.');
      form.strEmailAlternativo.focus();
      return false;
    }
  }
  return true;
}

function validaMensagem(form)
{
  if (isEmpty(form.strNome.value))
  {
    alert('Por favor, dê um NOME à mensagem.');
    form.strNome.focus();
    return false;
  }
  if (!isEmpty(form.datInicio.value))
  {
    if(!validaData(form.datInicio, "DATA DE INÍCIO"))
        return false;
  }
  if (!isEmpty(form.datTermino.value))
  {
    if(!validaData(form.datTermino, "DATA DE TÉRMINO"))
        return false;
  }
  if (!isEmpty(form.datInicio.value) && !isEmpty(form.datTermino.value))
  {
    var dia1 = form.datInicio.value.substring(0,2);
    var mes1 = form.datInicio.value.substring(3,5);
    var ano1 = form.datInicio.value.substring(6,10);

    var dia2 = form.datTermino.value.substring(0,2);
    var mes2 = form.datTermino.value.substring(3,5);
    var ano2 = form.datTermino.value.substring(6,10);

    if ( (ano1 > ano2) || (ano1 == ano2 && mes1 > mes2) || (ano1 == ano2 && mes1 == mes2 && dia1 > dia2) )
    {
        alert('A DATA DE INÍCIO é POSTERIOR à DATA DE TÉRMINO');
        form.datInicio.focus();
        return false;
    }
  }

  if (isEmpty(form.strMensagem.value))
  {
    alert('Por favor, preencha o campo MENSAGEM.');
    form.strMensagem.focus();
    return false;
  }

  return true;
}

function validaFaleConosco(form)
{
  if (isEmpty(form.strNomeFaleConosco.value))
  {
    alert('Por favor, informe seu NOME.');
    form.strNomeFaleConosco.focus();
    return false;
  }
  if (!isEmail(form.strEmailFaleConosco.value))
  {
    alert ('Por favor, informe um E-MAIL válido.');
    form.strEmailFaleConosco.focus();
    return false;
  }
  if (isEmpty(form.strMensagemFaleConosco.value))
  {
    alert('Por favor, preencha o campo MENSAGEM.');
    form.strMensagemFaleConosco.focus();
    return false;
  }
  return true;
}


function fechaDivMensagens(strDiv)
{
  document.getElementById(strDiv).style.display = "none";

  if("alertas" == strDiv)
  {
    if(document.getElementById("informativos"))
    {
      if("none" == document.getElementById("informativos").style.display)
        document.getElementById("mensagens").style.display = "none";
        w3cookies.create('indMensagens','Não',1);
    }
    else
    {
      document.getElementById("mensagens").style.display = "none";
        w3cookies.create('indMensagens','Não',1);
    }
  }
  else
  {
    if(document.getElementById("alertas"))
    {
      if("none" == document.getElementById("alertas").style.display)
        document.getElementById("mensagens").style.display = "none";
        w3cookies.create('indMensagens','Não',1);
    }
    else
    {
      document.getElementById("mensagens").style.display = "none";
        w3cookies.create('indMensagens','Não',1);
    }
  }

}

var arrMenuCliente = new Array("mensagens", "contratos", "contrato", "historico_contratual", "boletos", "indices", "ir", "cliente", "alterar_contatos", "alterar_senha");

var arrMenuGerencia = new Array("lista_alertas", "lista_informativos", "lista_usuarios");

function menuCliente(strOpcao)
{
  var strURL = window.location.pathname;
  var strPagina = strURL.substring(strURL.lastIndexOf('/') + 1);

  if("index.php" == strPagina)
  {
    
    if(document.getElementById('notificacao_sistema'))
      document.getElementById('notificacao_sistema').innerHTML = '';

    for(i=0;i<arrMenuCliente.length;i++)
    {
      if(strOpcao == arrMenuCliente[i] && document.getElementById(arrMenuCliente[i]))
        document.getElementById(arrMenuCliente[i]).style.display = "block";
      else if(document.getElementById(arrMenuCliente[i]))
        document.getElementById(arrMenuCliente[i]).style.display = "none";
    }

    if('mensagens' == strOpcao)
    {
      if(document.getElementById('alertas'))
        document.getElementById('alertas').style.display = "block";
      if(document.getElementById('informativos'))
        document.getElementById('informativos').style.display = "block";
    }

    if('historico_contratual' == strOpcao || 'boletos' == strOpcao || 'indices' == strOpcao || 'ir' == strOpcao)
    {
      document.getElementById('contratos').style.display = "block";
      document.getElementById('contrato').style.display = "block";
    }

    location.href = "index.php#a_" + strOpcao;
  }
  else
  {
    location.href = "index.php#a_" + strOpcao;
  }

}

function menuGerencia(strOpcao)
{
  var strURL = window.location.pathname;
  var strPagina = strURL.substring(strURL.lastIndexOf('/') + 1);

  if(document.getElementById('notificacao_sistema'))
    document.getElementById('notificacao_sistema').innerHTML = '';

  if("index.php" == strPagina)
  {
    for(i=0;i<arrMenuGerencia.length;i++)
    {
      if(strOpcao == arrMenuGerencia[i])
        document.getElementById(arrMenuGerencia[i]).style.display = "block";
      else
        document.getElementById(arrMenuGerencia[i]).style.display = "none";
    }
  }
  else
  {
    location.href = "index.php#a_" + strOpcao;
  }
}

function showHide(strElemento)
{
  if("block" != document.getElementById(strElemento).style.display)
    document.getElementById(strElemento).style.display = "block";
  else
    document.getElementById(strElemento).style.display = "none";
}

function isNumeric(input)
{
  var regexp = /^[0-9]+$/;

  if(regexp .test(input))
  {
    return true;
  }
  return false;
}

function isEmpty(strTexto)
{
  strTexto = trim(strTexto);
  if (0 < strTexto.length)
  {
    return false;
  }
  return true;
}

function trim(strTexto)
{
  return strTexto.replace(/^\s+|\s+$/g,"");
}

function isEmail(strEmail)
{
  var str = strEmail;
  var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

  if(filter.test(str))
    return true;
  else
    return false;
}

function isCPF(strCPF)
{
  var numeros, digitos, soma, i, resultado, digitos_iguais;
  digitos_iguais = 1;

  if (strCPF.length < 11)
    return false;
  for (i = 0; i < strCPF.length - 1; i++)
    if (strCPF.charAt(i) != strCPF.charAt(i + 1))
      {
        digitos_iguais = 0;
        break;
      }

  if (!digitos_iguais)
  {
    numeros = strCPF.substring(0,9);
    digitos = strCPF.substring(9);
    soma = 0;

    for (i = 10; i > 1; i--)
      soma += numeros.charAt(10 - i) * i;

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(0))
      return false;

    numeros = strCPF.substring(0,10);
    soma = 0;

    for (i = 11; i > 1; i--)
      soma += numeros.charAt(11 - i) * i;

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(1))
      return false;

    return true;
  }
  else
    return false;
}

function isCNPJ(strCNPJ)
{
  var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
  digitos_iguais = 1;

  if (strCNPJ.length < 14 && strCNPJ.length < 15)
    return false;

  for (i = 0; i < strCNPJ.length - 1; i++)
  {
    if (strCNPJ.charAt(i) != strCNPJ.charAt(i + 1))
    {
      digitos_iguais = 0;
      break;
    }
  }

  if (!digitos_iguais)
  {
    tamanho = strCNPJ.length - 2
    numeros = strCNPJ.substring(0,tamanho);
    digitos = strCNPJ.substring(tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (i = tamanho; i >= 1; i--)
    {
      soma += numeros.charAt(tamanho - i) * pos--;
      if (pos < 2)
        pos = 9;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(0))
          return false;

    tamanho = tamanho + 1;
    numeros = strCNPJ.substring(0,tamanho);
    soma = 0;
    pos = tamanho - 7;

    for (i = tamanho; i >= 1; i--)
    {
      soma += numeros.charAt(tamanho - i) * pos--;
      if (pos < 2)
        pos = 9;
    }

    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

    if (resultado != digitos.charAt(1))
      return false;

    return true;
    }
    else
      return false;
}

function mascaraNumero(evt)
{
  if (navigator.appName.indexOf("Netscape") != -1)
    _isNav = true;
  else
    _isNav = false;

  if (navigator.appName.indexOf("Microsoft") != -1 )
    _isIE = true;
  else
    _isIE = false;

  var key;

  if (_isNav || _isIE)
  {
    key = (_isNav)? evt.which: evt.keyCode;
    return (key > 47 && key < 58) || key == 8 || key == 0 ? true: false;
  }
  return true;
}

function mascaraTelefone(campo, evt)
{
  if (navigator.appName.indexOf("Netscape") != -1) _isNav = true;
  if (navigator.appName.indexOf("Microsoft") != -1 ) _isIE = true;

  var key;

  if (_isNav || _isIE)
  {
    key = (_isNav)? evt.which: evt.keyCode;

    if(campo.value.length == 1)
      campo.value = '(' + campo.value;

    if(campo.value.length == 3)
      campo.value = campo.value + ')';

    if(campo.value.length == 4)
      campo.value = campo.value + ' ';

    if(campo.value.length == 9)
      campo.value = campo.value + '-';

    return (key > 47 && key < 58) || key == 8 || key == 0 ? true: false;
  }
}

function mascaraData(campo, evt)
{
  if (navigator.appName.indexOf("Netscape") != -1) _isNav = true;
  if (navigator.appName.indexOf("Microsoft") != -1 ) _isIE = true;

  var key;

  if (_isNav || _isIE)
  {
    key = (_isNav)? evt.which: evt.keyCode;

    if(campo.value.length == 2)
      campo.value = campo.value + '/';

    if(campo.value.length == 5)
      campo.value = campo.value + '/';

    return (key > 47 && key < 58) || key == 8 || key == 0 ? true: false;
  }
}

function validaData(campo, personalizacao)
{
  var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;

  if ((campo.value.match(expReg)) && (campo.value!=''))
  {
    var dia = campo.value.substring(0,2);
    var mes = campo.value.substring(3,5);
    var ano = campo.value.substring(6,10);

    if( ( mes==4 || mes==6 || mes==9 || mes==11 ) && dia > 30 )
    {
      alert("Data inválida. O mês informado tem no máximo 30 dias.");
      campo.focus();
      return false;
    }
    else
    {
      if( ano%4!=0 && mes==2 && dia>28 )
      {
        alert("Data inválida. O mês informado tem no máximo 28 dias.");
        campo.focus();
        return false;
      }
      else
      {
        if( ano%4==0 && mes==2 && dia>29 )
        {
          alert("Data inválida. O mês informado tem no máximo 29 dias.");
          campo.focus();
          return false;
        }
      }
    }
  }
  else
  {
    alert(personalizacao + " inválida.");
    campo.focus();
    return false;
  }
  return true;
}

var w3cookies = {
  date: new Date(),
  create: function(strName, strValue, intDays)
  {
    if(intDays)
    {
      this.date.setTime(this.date.getTime()+(intDays*24*60*60*1000));
      var expires = "; expires=" + this.date.toGMTString();
    }
    else
    {
      var expires = "";
    }
    document.cookie = strName + "=" + strValue + expires + "; path=/";
  },
	read: function(strName)
    {
      var strNameIgual = strName + "=";
      var arrCookies = document.cookie.split(";");
      for ( var i = 0, strCookie; strCookie = arrCookies[i]; i++ )
      {
      	while ( strCookie.charAt(0) == " ")
        {
          strCookie = strCookie.substring(1,strCookie.length);
      	}
      	if ( strCookie.indexOf(strNameIgual) == 0 )
        {
          return strCookie.substring(strNameIgual.length,strCookie.length);
      	}
      }
      return null;
	},
	erase: function(strName)
    {
      this.create(strName,"",-1);
	}
}

function imprimir(strSetor)
{
  document.getElementById("strImpressao").value = document.getElementById("contrato").innerHTML + document.getElementById(strSetor).innerHTML;
  document.getElementById("formImpressao").submit();
}
