// pop-up //
// USO <a href="pagina.htm" onclick="return popUp(this.href, 'N', 800, 600);"> //
function popUp(strURL, strType, strWidth, strHeight)
{
  var strOptions = "height=" + strHeight + ", width = " + strWidth + ", status";
  if(strType == "RS")
    strOptions += ", resizable, scrollbars";
  if(strType == "R")
    strOptions += ", resizable";
  if(strType == "S")
    strOptions += ", scrollbars";
  newWin = window.open(strURL, "newWin", strOptions);
  newWin.focus();
  return false;
}

// NoSpan //
// USO <a href="javascript: noSpam('contato', 'dominio.com.br')">email para contato</a> //
function noSpam(user, domain)
{
  lString = "mailto: " + user + "@" + domain;
  window.location = lString;
}

// toggle visibility
function toggle( targetId ){
  if (document.getElementById){
        target = document.getElementById( targetId );
           if (target.style.display == "none" || target.style.display == ""){
              target.style.display = "block";
           } else {
              target.style.display = "none";
           }
     }
}

// Foco //
function focusme(obj)
{
  if(obj)
    obj.focus();
  else
    window.focus();
}

// retorna objeto do html pelo nome //
function getObj(nome)
{
  if(document.getElementById)
    return document.getElementById(nome);
  else if(document.all)
    return document.all[nome];
  else if(document.layers)
    return document.layers[nome];
  else return false;
}

// apresenta objeto html escondido //
function mostra(obj)
{
  obj.style.display = '';
}

// esconde objeto html //
function esconde(obj)
{
  obj.style.display = 'none';
}

// controla a apresentação de objeto html //
function controla(obj)
{
  var dx = getObj(obj);
  if(dx.style.display != 'none')
    esconde(dx);
  else
    mostra(dx);
}

// maximiza a janela //
function fullScreen()
{
  window.moveTo(0, 0);
  if(document.all)
    window.resizeTo(screen.availWidth, screen.availHeight);
  else if(document.layers || document.getElementById)
  {
    if(window.outerHeight < screen.availHeight || window.outerWidth < screen.availWidth)
    {
      window.outerHeight = screen.availHeight;
      window.outerWidth = screen.availWidth;
    }
  }
}

// trim //
function trim(str)
{
  return str.replace(/^(\s)+|(\s)+$/g, '');
}

// cria data a partir de uma string (dd/mm/aaaa) //
function toDate(data)
{
  if(isDate(data))
  {
    dia = parseInt(data.substr(0, 2), 10);
    mes = parseInt(data.substr(3, 2), 10);
    ano = parseInt(data.substr(6, 4), 10);
    return new Date(ano, mes - 1, dia);
  }
  else
    return new Date();
}

// completa com zeros à esquerda //
function Zeros(texto, tamanho)
{
  while(texto.length < tamanho)
    texto = '0' + texto;
  return texto;
}

// convert data para string (dd/mm/aaaa) //
function toDateStr(data)
{
  dia = Zeros(data.getDate().toString(10), 2);
  mes = Zeros((data.getMonth() + 1).toString(10), 2);
  ano = data.getFullYear();
  return dia + '/' + mes + '/' + ano;
}

// retorna tamanho do mes //
function monthLen(mes, ano)
{
  switch(mes)
  {
    // meses com 30 dias //
    case 4:
    case 6:
    case 9:
    case 11:
      return 30;
      break;
    // fevereiro //
    case 2:
      // se ano não for bisexto //
      if(ano % 4)
        return 28;
      else
        return 29;
      break;
    // meses com 31 dias //
    default:
      return 31;
  }
}

// adiciona em uma parte da data um número //
function dateAdd(parte, numero, data)
{
  dia = data.getDate();
  mes = data.getMonth() + 1;
  ano = data.getFullYear();
  switch(parte)
  {
    // acrescenta dias na data //
    case 'd':
      dia += numero;
      while(dia > monthLen(mes, ano))
      {
        dia -= monthLen(mes, ano);
        mes += 1;
        if(mes > 12)
        {
          mes = 1;
          ano += 1;
        }
      }
      break;
    // acrescenta meses na data //
    case 'm':
      mes += numero;
      while(mes > 12)
      {
        mes -= 12;
        ano += 1;
      }
      if(dia > monthLen(mes, ano))
        dia = monthLen(mes, ano);
      break;
    // acrescenta anos na data //
    case 'y':
      ano += numero;
      if(mes == 2 && dia == 29 && ano % 4)
        dia = 28;
      break;
    default:
      // erro de parâmetro (retorna a mesma data) //
  }
  return new Date(ano, mes - 1, dia)
}

// compara duas datas //
function compareDate(data1, data2)
{
  if(data1 < data2)
    return -1;
  else if(data1 > data2)
    return 1;
  else
    return 0;
}

// compara duas datas como string (dd/mm/aaaa) //
function compareDateStr(data1, data2)
{
  d1 = toDate(data1);
  d2 = toDate(data2);
  return compareDate(d1, d2);
}

// converte texto para valor numerico
function toNumber(valor) {
  return parseFloat(valor.replace(',', '.').replace('.', ''));
}

// aceita a digitação somente de números com ou sem máscara (keypress) //
function Numeric(ev, campo, mask)
{
  if(ev.keyCode) {
    if((ev.keyCode < 48 || ev.keyCode > 57) && ev.keyCode != 13) {
      ev.returnValue = false;
      return false;
    }
  }
  else if((ev.charCode < 48 || ev.charCode > 57) && ev.charCode != 13) {
    ev.preventDefault(false);
    ev.stopPropagation();
    return false;
  }
  if(campo && mask)
  {
    i = campo.value.length;
    if(i < mask.length && i < campo.maxLength)
    {
      c = mask.charAt(i);
      if(c != '9')
        campo.value += c;
    }
  }
}

// coloca mascara em campo data (dd/mm/aaaa) [keypress] //
function MascareDate(ev, campo)
{
  return Numeric(ev, campo, '99/99/9999 99:99:99');
}

// verifica se um campo de um formulário está vazio ou só com espaços //
function Empty(campo, msg)
{
  if(campo.value.length)
    if(trim(campo.value) != '')
      return false;
  if(msg != '')
  {
    alert(msg);
    campo.focus();
  }
  return true;
}

// verifica se um campo tipo checkbox ou radio de um formulário foi marcado //
function Check(campo, msg)
{
  if(campo.length)
    for(i = 0; i < campo.length; i++)
      if(campo[i].checked)
        return true;
  else if(campo.checked)
    return true;
  if(msg != '')
    alert(msg);
  return false;
}

// verifica se uma string é uma data (dd/mm/aaaa) //
function isDate(data)
{
  if(data.length == 10)
  {
    dia = parseInt(data.substr(0, 2), 10);
    mes = parseInt(data.substr(3, 2), 10);
    ano = parseInt(data.substr(6, 4), 10);
    if(dia > 0 && dia < 32 && mes > 0 && mes < 13 && ano > 999 && ano < 10000)
    {
      if(mes == 2 && dia > 28)
      {
        if(ano % 4)
          return false;
        else if(dia > 29)
          return false;
      }
      switch(mes)
      {
        case 4:
        case 6:
        case 9:
        case 11:
          if(dia > 30)
            return false;
          break;
      }
    }
    else
      return false;
  }
  else if(data.length)
    return false;
  return true;
}

// valida o e-mail //
function isEmail(email)
{
  if(email.length)
    return(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
  return true;
}

// valida CPF //
function isCPF(CPF)
{
  var i, j, soma;
  if(CPF.length != 11)
    return false;
  j = true;
  for(i = 0; i < 9; i++)
  {
    if(parseInt(CPF.charAt(i), 10) != parseInt(CPF.charAt(i + 1), 10))
    {
      j = false;
      break;
    }
  }
  if(j) return false;
  for(j = 0; j < 2; j++)
  {
    soma = 0;
    for(i = 0; i < 9 + j; i++)
      soma += parseInt(CPF.charAt(i), 10) * (10 + j - i);
    soma = 11 - (soma % 11);
    if(soma > 9) soma = 0;
    if(soma != parseInt(CPF.charAt(9 + j), 10))
      return false;
  }
  return true;
}

// valida CNPJ //
function isCNPJ(CNPJ)
{
  var i, j, k, soma;
  if(CNPJ.length != 14)
    return false;
  for(k = 0; k < 2; k++)
  {
    soma = 0;
    j = 5 + k;
    for(i = 0; i < 12 + k; i++)
    {
      soma += parseInt(CNPJ.charAt(i), 10) * j;
      if(j > 2) j--;
      else j = 9;
    }
    soma = 11 - soma % 11;
    if(soma > 9) soma = 0;
    if(soma != parseInt(CNPJ.charAt(12 + k)))
      return false;
  }
  return true;
}

// limita o tamanho do textarea na digitação //
function textCounter(ev, field, limit, diplay)
{
	if(field.value.length >= limit)
	{
		if(ev.keyCode)
			ev.returnValue = false;
		else
		{
			ev.preventDefault(false);
			ev.stopPropagation();
		}
		return false;
	}
	getObj(diplay).innerHTML = field.value.length + 1;
}

// limita e mostra o tamanho do textarea //
function textLimit(field, limit, diplay)
{
	field.value = field.value.substr(0, limit);
	getObj(diplay).innerHTML = field.value.length;
}

// marca alteração //
var alterou = false;
function altera(campo)
{
  alterou = campo;
}

// confirma alteração //
function confirma(campo)
{
  if(alterou && alterou != campo)
    return confirm('você não salvou as alterações. \n deseja continuar ?');
  return true;
}

// calcula módulo //
function modulo(numero, mod, x)
{
  total = 0;
  for(i = 0; i < numero.length; i++)
    total += parseInt(numero.substr(numero.length - (i + 1), 1)) * ((i % 8) + 2);
  digito = mod - (total % mod);
  return (digito > 9) ? x : digito;
}

// substitui todas as ocorrências de um char //
function substitui(chr, rpl, str)
{
  while(str.search(chr) >= 0)
    str = str.replace(chr, rpl);
  return str;
}

// acessa url de forma síncrona //
function getUrl(url, method, enctype, post, xml)
{
  var obj = false;
  if(window.XMLHttpRequest)
    obj = new XMLHttpRequest();
  else if(window.ActiveXObject)
    obj = new ActiveXObject('Microsoft.XMLHTTP');
  if(obj)
  {
    obj.open(method, url, false);
    obj.setRequestHeader('Content-type', enctype);
    obj.send(post);
    if(xml) return obj.responseXML;
    return obj.responseText;
  }
  else
    alert('Error: Not suport for XMLHttpRequest!');
}

// retorna todas as ocorrências de uma tag xml //
function getTags(docx, tag)
{
  node = docx.getElementsByTagName(tag);
  if(node.length)
    return node;
  return false;
}

// retorna valor de tag xml //
function getValue(node, i)
{
  if(node.length) {
    if(child = node[i])
      return unescape(child.firstChild.nodeValue);
    return null;
  }
  return null;
}

// seleciona um formulário //
function getForm(file, name, onload)
{
  if(div = getObj(name))
  {
    div.innerHTML = getUrl(file, 'get', 'text/plain', '', false);
    if(onload) eval(onload);
  }
  else
    alert('Elemento inválido!');
  return false;
}

// posta um formulário //
function postForm(frm, name, onload)
{
  flds = '';
  if(frm.length)
  {
    for(i = 0; i < frm.length; i++)
    {
      elm = frm.elements[i];
      if(elm.name != '')
      {
        if(!Validate(elm))
          return false;
        if(tp = elm.getAttribute('type'))
        {
          switch(tp.toLowerCase())
          {
            case 'checkbox':
            case 'radio':
              if(elm.checked)
                flds += elm.name + '=' + escape(elm.value) + '&';
              break;
            default:
              flds += elm.name + '=' + escape(elm.value) + '&';
          }
        }
        else
          flds += elm.name + '=' + escape(elm.value) + '&';
      }
    }
    if(div = getObj(name)) {
      div.innerHTML = getUrl(frm.action, frm.method, frm.enctype, flds, false);
      if(onload) eval(onload);
    }
    else
      alert("Elemento inválido!");
  }
  else
    alert("Formulário inválido!");
  return false;
}

// valida um formulário //
function validForm(frm)
{
  if(frm.length)
  {
    for(i = 0; i < frm.length; i++)
    {
      elm = frm.elements[i];
      if(elm.name != '')
        if(!Validate(elm))
          return false;
    }
    return true;
  }
  else
    alert("Formulário inválido!");
  return false;
}

// valida um elemento de um formulário //
function Validate(elm)
{
  if(elm.getAttribute('required'))
  {
    if(tp = elm.getAttribute('type'))
    {
      switch(tp.toLowerCase())
      {
        case 'checkbox':
        case 'radio':
          break;
        default:
          if(Empty(elm, elm.getAttribute('validationmsg')))
            return false;
      }
    }
    else if(Empty(elm, elm.getAttribute('validationmsg')))
      return false;
  }
  switch(elm.getAttribute('param'))
  {
    case 'date':
      if(!isDate(elm.value))
      {
        alert('Data Inválida!');
        elm.focus();
        return false;
      }
      break;
    case 'email':
      if(!isEmail(elm.value))
      {
        alert('E-mail Inválido!');
        elm.focus();
        return false;
      }
      break;
    case 'cpf':
      if(!isCPF(elm.value))
      {
        alert('CPF Inválido!');
        elm.focus();
        return false;
      }
      break;
    case 'cnpj':
      if(!isCNPJ(elm.value))
      {
        alert('CNPJ Inválido!');
        elm.focus();
        return false;
      }
      break;
    case 'cpfcnpj':
      if(!isCPF(elm.value) && !isCNPJ(elm.value))
      {
        alert('CPF / CNPJ Inválido!');
        elm.focus();
        return false;
      }
      break;
  }
  return true;
}

// mensagem de erro //
function erro() {
  if(obj = getObj('erro')) {
		if(obj.title != '') {
	   	alert(obj.title);
  	 	return true;
		}
  }
  return false;
}

//Altera o link da página
function novaURL (url) {
	window.location = url;
}

// ajax //
var ajax;

// inicia ajax //
function iniciaAjax(name) {
  ajax = getObj(name);
}

// carrega ajax //
function carregaAjax(doc) {
  if(ajax)
    ajax.innerHTML = doc.body.innerHTML;
  ajax = false;
}
