/********************************************************************
 Retorna TRUE se, e somente se:
 - a data está no formato dd/MM/yyyy; 
 E
 - é uma data válida.
*********************************************************************/
function isDate(dateStr) {
  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = dateStr.match(datePat); // is the format ok?
  if (matchArray == null) {
    alert("Entre uma data válida, no formato (dd/mm/yyyy).");
    return false;
  }
  month = matchArray[3]; // parse date into variables
  day   = matchArray[1];
  year  = matchArray[5];
  if (month < 1 || month > 12) { // check month range
    alert("O mês deve estar entre 1 e 12.");
    return false;
  }
  if (day < 1 || day > 31) {
    alert("O dia deve estar entre 1 e 31.");
    return false;
  }
  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    alert("O mês "+month+" não tem 31 dias!")
    return false;
  }
  if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
      alert("Fevereiro de " + year + " não tem " + day + " dias!");
      return false;
    }
  }
  return true; // date is valid
}


//-------------------------------------------------------------------
// Trim functions
//   Returns string with whitespace trimmed
//-------------------------------------------------------------------
function trimL(str) {
  for (var i=0; str.charAt(i)==" "; i++);
  return str.substring(i,str.length);
}

function trimR(str) {
  for (var i=str.length-1; str.charAt(i)==" "; i--);
  return str.substring(0,i+1);
}

function trim(str) {
  return trimL(trimR(str));
}

//-------------------------------------------------------------------
// CGC / CPF
//-------------------------------------------------------------------


function extrairMascaraCPF(cpf) {
  var tam = cpf.length;
  var cpfNumerico = "";
  for (var idx = 0; idx < tam; idx++) {
    ch = cpf.substring(idx, idx+1);
    if (ch != '.' && ch != '-')
      cpfNumerico += ch;
  }

  return cpfNumerico;
}

function validarMascaraCPF(cpf) {
  var posDot1 = cpf.indexOf('.', 0);
  var posDot2 = cpf.indexOf('.', posDot1+1);
  var posBar = cpf.indexOf('-');

  if (posDot1 > -1 || posDot2 > -1 || posBar > -1) {
    if (posDot1 != 3 || posDot2 != 7 || posBar != 11) {
      return false;
    }
  }
  return true;
}


function extrairMascaraCGC(cgc) {
  var tam = cgc.length;
  var cgcNumerico = "";
  for (var idx = 0; idx < tam; idx++) {
    ch = cgc.substring(idx, idx+1);
    if (ch != '.' && ch != '-' && ch != '/')
      cgcNumerico += ch;
  }

  return cgcNumerico;
}

function validarMascaraCGC(cgc) {
  var posDot1 = cgc.indexOf('.', 0);
  var posDot2 = cgc.indexOf('.', posDot1+1);
  var posSlash = cgc.indexOf('/');
  var posBar = cgc.indexOf('-');

  if (posDot1 > -1 || posDot2 > -1 || posSlash > -1 || posBar > -1) {
    if (posDot1 != 2 || posDot2 != 6 || posSlash != 10 || posBar != 15) {
      return false;
    }
  }
  return true;
}

function verificarCGC(CGCValue) {
  var dig1 = 0;
  var dig2 = 0;
  var i;
  var fator;
  
  CGCValue = extrairMascaraCGC(CGCValue);

  if (CGCValue ==null || trim(CGCValue).length > 14 ||
      trim(CGCValue).length < 14 ){
       return false;
  }

  // primeiro digito
  fator=14;
  for (i=12; i>=1; i--){ 
	if (i==4) 
	  fator= 6;
    
      dig1= dig1 + parseInt(CGCValue.substring(i-1,i),10)*(fator-i);
     }

  dig1= dig1%11;
  if (dig1==0 || dig1==1) dig1=0;
  else dig1= 11-dig1;

  if (!parseInt(dig1,10) == CGCValue.substring(12,13) ) return false;

  // segundo digito
  fator=15;
  for (i=13; i>=1; i--){
	  if (i==5) fator= 7;
	  
      dig2= dig2 + parseInt(CGCValue.substring(i-1,i),10)*(fator-i);
     }

  dig2= dig2%11;
  if (dig2==0 || dig2==1) dig2=0;
  else dig2= 11-dig2;

  if( parseInt(dig2,10) != (CGCValue.substring(13,14)) ){
    return false;
  }
  else{
    return true;
  }
  
}

 
function verificarCPF(CPFValue) {
    var i;
    var dig1 = 0;
    var dig2 = 0;
    
    CPFValue = extrairMascaraCPF(CPFValue);

    if (trim(CPFValue) == null || trim(CPFValue).length > 11 || 
        trim(CPFValue).length < 11){
       return false;

   }

    for (i=1; i<=9; i++){
      dig1= dig1 + parseInt(CPFValue.substring(i-1,i),10) *i;
    }

    dig1= dig1%11;
    
    if (dig1==10) dig1=0;

    if (dig1 != CPFValue.substring(9,10)) return false;

    for (i=2; i<=10; i++){
       dig2= dig2 + parseInt(CPFValue.substring(i-1,i),10)*(i-1); 
    }

    dig2= dig2%11;

    if (dig2==10) dig2=0;

    if(dig2 != CPFValue.substring(10,11)){
      return false;
    }
    else{
      return true;
    }
}

function toCpf(cpf) {

    if(trim(cpf.value)!="" && cpf.value.length == 11) {

      cpf.value = cpf.value.substring(0,3) + "." + cpf.value.substring(3,6) +
            "." + cpf.value.substring(6,9) + "-" + cpf.value.substring(9,11);

    }

    return cpf;
}
/*
function toCnpj(cnpj) {

    if(trim(cnpj.value)!="" && cnpj.value.length == 14) {

      cnpj.value = cnpj.value.substring(0,2) + "." + cnpj.value.substring(2,5) + "." 
             + cnpj.value.substring(5,8) + "/" + cnpj.value.substring(8,12) 
             + "-" + cnpj.value.substring(12,14);

    }

    return cnpj;
}
 */

function toCnpj(cnpj){

    if(trim(cnpj)!="" && cnpj.length == 14) {

      cnpj = cnpj.substring(0,2) + "." + cnpj.substring(2,5) + "." 
             + cnpj.substring(5,8) + "/" + cnpj.substring(8,12) 
             + "-" + cnpj.substring(12,14);

    }

    return cnpj;

} 
 
// ------------------------------------------------------------------------------------------------------------
function VerificaCep(cep){
	cep = cep.replace(" ","");
	cep = cep.replace("-","");
	cep = cep.replace(".","");
	if(cep.length != 5 && cep.length != 8){
		alert ("O comprimeto do CEP não é válido.");
		return(true);
	}
	else if(isNaN(cep)){
		alert ("O CEP não pode conter valores não numéricos.");
		return(true);
	}
	return(false);
}

// ------------------------------------------------------------------------------------------------------------
// TODO: Nomear para isFieldEmpty ou isEmptyField, pois é mais util para fields.
//       Depois criar um metodo isEmpty que realmente só verifica se é vazio ou nao.
//       Ps: Javascript nao suporta Overload.
function isEmpty(pField,pMessage)
{
        if(pField.type == "text"){
	    var txt = pField.value.replace(/(\s+)/gi,"");
	    if (txt.length == 0)
	    {
	    	if (pMessage.length > 0)
	    	{
	    		alert(pMessage);
	    		pField.focus();
	    	}
	    	return true;
	    }
        }
        else if(pField.type == "select-one"){
                if(pField.selectedIndex == 0){
	    	    if (pMessage.length > 0){
	    	    	alert(pMessage);
	    	    	pField.focus();
	    	    }
	    	    return true;
                }
             }
             else if(pField.type == "checkbox"){
                if(!pField.checked){
	    	    if (pMessage.length > 0){
	    	    	alert(pMessage);
	    	    	pField.focus();
	    	    }
	    	    return true;
                }
             }



	return false;
}

// ------------------------------------------------------------------------------------------------------------

function VerificaEMail(email)
{
	if (email.indexOf('\@') == -1){
		alert("Atenção:\n' "+email+" ' não é um e-mail válido!\nPor favor, verifique.");
		return true;
	}
	provedor = email.substr(email.indexOf('\@') + 1).toLowerCase();
	usuario = email.substr(email.indexOf('\@') + 1);

	if ((usuario == "") || (provedor == "") || (provedor.indexOf('.') < 0)){
		alert("Atenção:\n' "+email+" ' não é um e-mail válido!\nPor favor, verifique.");
		return true;
	}
	return false;
}

// ------------------------------------------------------------------------------------------------------------
// INICIO VALIDA TELEFONE
function TelefoneInvalido(telefone){
	telefone = telefone.replace(" ","");
	telefone = telefone.replace("-","");
	telefone = telefone.replace(".","");
	if(telefone.length == 0){
		alert("O campo telefone deve ser preenchido.\nTente novamente.");
		return true;
	}	
	if(telefone.length != 7 && telefone.length != 8){
		alert("O comprimento do telefone é inválido.\nTente novamente.");
		return true;
	}
	if(isNaN(telefone)){
		alert("Formato de Telefone inválido! Letras não são aceitas.");
		return true;
	}
	return false;
}

// FIM  VALIDA TELEFONE
 
 
// ------------------------------------------------------------------------------------------------------------
function VerificaAreaCode(pAreaCode)
{
	if (isEmpty(pAreaCode, "O DDD está em branco, por favor verifique.")) {pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length != 2) && (pAreaCode.value.length != 3)) {alert ("O campo DDD está incorreto.\nO formato correto é 0XX ou YY"); pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length == 3) && (pAreaCode.value.substr(0,1) != "0")) {alert ("o campo DDD está incorreto.\nO formato correto é 0XX ou YY"); pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length == 3) && isalpha("DDD",pAreaCode.value.substr(1,1))) {pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length == 3) && isalpha("DDD",pAreaCode.value.substr(2,1))) {pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length == 2) && isalpha("DDD",pAreaCode.value.substr(0,1))) {pAreaCode.focus(); return true;}
	if ((pAreaCode.value.length == 2) && isalpha("DDD",pAreaCode.value.substr(1,1))) {pAreaCode.focus(); return true;}
	return false;
}

// ------------------------------------------------------------------------------------------------------------
function isalpha(field, dig)
{
	if (dig != "0" && dig != "1" && dig != "2" && dig != "3" && dig != "4" &&
	     dig != "5" && dig != "6" && dig != "7" && dig != "8" && dig != "9"   )
	{
		alert (field+" tem que ser numérico")
		return true;
	}
	return false;
}

/********************************************************************
 Retorna TRUE se:
- senha não for fazia
- senha e senhaConf forem iguais;
*********************************************************************/
function confirmPassword(login, senha, senhaConf){
	
	//se login vazio
	if (login.value == '') {
		alert("O campo login deve ser preenchido e ter no mínimo 8 caracteres!");
		login.focus();
		return false;
	} 
	if(login.value.length < 8){
		alert("O campo login deve ter no mínimo 8 caracteres!");
		login.focus();
		return false;
	}
	
	//se senha vazia
	if (senha.value == '') {
		alert("O campo senha deve ser preenchido!");
		senha.focus();
		return false;
	} 
	//se não confirmada
	if (senha.value != senhaConf.value) {
		alert("As senhas digitadas não conferem!");
		senha.focus();
		return false;
	} 
	return true;
}
// ------------------------------------------------------------------------------------------------------------
// Abra pop up
function popjan(url, objName, objW, objH)
{
     return window.open( montaUrl(url), objName, "modal,menubar=no, toolbar=no, location=no, scrollbars=yes, status=no,resizable=no, width="+objW+", height="+objH+", left="+(screen.width/2 - (objW/2))+", top="+(screen.height/2 - (objH/2)));
}

function popjanNoModal(url, objName, objW, objH)
{
     return window.open( montaUrl(url), objName, "menubar=no, toolbar=no, location=no, scrollbars=yes, status=no,resizable=no, width="+objW+", height="+objH+", left="+(screen.width/2 - (objW/2))+", top="+(screen.height/2 - (objH/2)));
}

function popjanResizable(url, objName, objW, objH)
{
     return window.open( montaUrl(url), objName, "modal,menubar=no, toolbar=no, location=no, scrollbars=yes, status=no,resizable=yes, width="+objW+", height="+objH+", left="+(screen.width/2 - (objW/2))+", top="+(screen.height/2 - (objH/2)));
}


// Abre popup sem deixar abrir duas vezes. (na segunda vez ganha foco)
// recebe window handler da pág. de origem como parâmetro
function openPopUp(popUpWindowHandler, url, objName, objW, objH)
{
     if( popUpWindowHandler==null || popUpWindowHandler.closed==true){
     	popUpWindowHandler = popjanNoModal(url, objName, objW, objH);
	 }else{
	 	popUpWindowHandler.focus();
	 }
}

var buscaAvancadaWindowHandler = null;

// Abre popup sem deixar abrir duas vezes. (na segunda vez ganha foco)
function popupBuscaAvancada(url, objName, objW, objH)
{
     if( buscaAvancadaWindowHandler==null || buscaAvancadaWindowHandler.closed==true){
     	buscaAvancadaWindowHandler = popjanResizable(url, objName, objW, objH);
     	buscaAvancadaWindowHandler.focus();
	 }else{
	 	buscaAvancadaWindowHandler.focus();
	 	buscaAvancadaWindowHandler = popjanResizable(url, objName, objW, objH);
	 }
}

// Faz o submit de uma página passando o form, action e o method
function goTo(objForm, actionName, methodName){

    objForm.action = actionName + ".do";
    objForm.method.value = methodName;
  
    objForm.submit();
}

/**
 * Move todos os options de um SELECT para um outro SELECT.
 */
   function moveSelect(objFrom, objTo){
	  for(var i=0; i<objFrom.options.length; i++){
		var opt = objFrom.options[i];
		var newOpt = new Option();
		newOpt.text = opt.text;
		newOpt.value = opt.value;
		objTo.options[i] = newOpt;
	  }
  }

  
/**
 * Track Count
 */  
	function trackCount(objTextArea,objCountTextField,maxChars)
	{
		objCountTextField.value = maxChars - objTextArea.value.length;

	} 

/**
 * Url Rnd
 */
  function getNewRndNumber(){
  	return Math.round(Math.random()*99999999999);
  }
  
  function montaUrl( strUrl ){
  
    var jaExisteRnd = strUrl.indexOf("_rnd=")==-1;

	/* Coloca o _rnd se nao encontrar nenhuma ocorrencia de _rnd */ 
  	if( jaExisteRnd ){
  
	    var symbol = strUrl.indexOf("?")==-1?"?":"&";
	    
	    return strUrl + symbol + "_rnd=" + getNewRndNumber();
	}else{
		return strUrl;
	}
	
	
  
  }
  
  
 	function direcionaUrl(pURL){
		var aleatorio = getNewRndNumber();
		var symbol = pURL.indexOf("?")==-1?"?":"&"; 
		window.location = pURL +  symbol + '_rnd=' + aleatorio;
	} 
  
  
  