/**
 * Cria um objeto XMLHttpRequest para gerenciar uma chamada AJAX.
 * 
 * @param params Par&acirc;metros para enviar ao servidor.
 * @param pagina Endere&ccedil;o da p&aacute;gina.
 * @param funcao Nome da fun&ccedil;&atilde;o que ir&aacute; processar o retorno.
 * @param tipoRetorno Tipo do retorno (XML, HTTP, TXT)
 */
function makeRequest(params, pagina, funcao, tipoRetorno) {
  var httpRequest;
  var retorno;

  if (window.XMLHttpRequest) {
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType && (tipoRetorno == "XML")) {
      httpRequest.overrideMimeType('text/xml');
    }
  }else if (window.ActiveXObject){
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e){
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e) {
        alert("problema");
      }
    }
  }

  if (!httpRequest) return false;
  else{
    httpRequest.onreadystatechange = function(){
      if (httpRequest.readyState == 4){
        if (httpRequest.status == 200){
          if (tipoRetorno == "XML"){
            retorno = httpRequest.responseXML;
/*
            if (retorno.getElementsByTagName("RESULTADO").item(0).firstChild.data == 3)
              window.location = "login.html";
            else
            */
              eval(funcao + "(retorno)");
          }else{
            retorno = httpRequest.responseText;
            eval(funcao + "(retorno)");
          }
        }else
          alert("Problema:\n readyState=" + httpRequest.readyState + "\nstatus=" + httpRequest.status);
      }
    };
    httpRequest.open("POST", pagina, true);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send(params);
  }

}

/**
 * Validar um n&uacute;mero de CPF.
 * 
 * @param cpf N&uacute;mero do CPF.
 * @return bool Valor l&oacute;gico indicando a validade do CPF.
 */
function validarCpf(cpf){
// Obrigado a Thiago Prado

  regCpf = /^((\d{3}\.?){2})(\d{3})\-?(\d{2})$/;
  if (!regCpf.test(cpf))
    return false;
  else {
    cpf = cpf.replace(".", "", "g");
    cpf = cpf.replace("-", "", "g");
    
    if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222"
        || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555"
        || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888"
        || cpf == "99999999999")
      return false;
    var a = [];
    var b = new Number;
    var c = 11;
    for (i=0; i<11; i++){
      a[i] = cpf.charAt(i);
      if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
    b = 0;
    c = 11;
    for (y=0; y<10; y++) b += (a[y] * c--);
    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
      return false;
    else
      return true;
  }
}

/**
 * Validar um n&uacute;mero de CNPJ.
 *
 * @param cnpj N&uacute;mero do CNPJ.
 * @return bool Valor l&oacute;gico indicando a validade do CNPJ.
 */
function validarCnpj(cnpj){
// Obrigado a Thiago Prado

  regCnpj = /^(\d{2})(\.?\d{3}){2}\/?\d{4}\-?(\d{2})$/;
  if (!regCnpj.test(cnpj))
    return false;
  
  cnpj = cnpj.replace(".", "", "g");
  cnpj = cnpj.replace("/", "", "g");
  cnpj = cnpj.replace("-", "", "g");

  var a = [];
  var b = new Number;
  var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
  for (i=0; i<12; i++){
    a[i] = cnpj.charAt(i);
    b += a[i] * c[i+1];
  }
  if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
  b = 0;
  for (y=0; y<13; y++)
    b += (a[y] * c[y]);

  if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
  if ((cnpj.charAt(12) != a[12]) || (cnpj.charAt(13) != a[13]))
    return false;
  else
    return true;

}

/**
 * Mostra uma div popup.
 * <p>
 * Para que a div seja popup, o layout deve ter uma div com id=popup e a div que representa
 * a janela desejada deve estar dentro da popup.
 * 
 * @param idPopup Id da div que representa a janela.
 * @param mostrar Flag indicando se deve mostrar ou ocultar a janela popup
 */
function popup(idPopup, mostrar){

  if (mostrar){
    document.getElementById("popup").style.display = "block";
    document.getElementById(idPopup).style.display = "block";
  }else{
    document.getElementById("popup").style.display = "none";
    document.getElementById(idPopup).style.display = "none";
  }
}

/**
 * Retorna as vari&aacute;veis GET passadas na URL.
 * 
 * @return array Retorna todas as vari&aacute;veis GET em um array.
 */
function getUrlVars(){

var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

  for(var i = 0; i < hashes.length; i++){
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;

}
